blob: b0a712dcaafd55ad67181e30228e9a384aacd622 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
119 _PyUnicode_Ready((PyObject *)(op))))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
257 const Py_UNICODE *unicode, Py_ssize_t size,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Martin v. Löwis9e816682011-11-02 12:45:42 +0100260static void
261raise_encode_exception_obj(PyObject **exceptionObject,
262 const char *encoding,
263 PyObject *unicode,
264 Py_ssize_t startpos, Py_ssize_t endpos,
265 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000266
Christian Heimes190d79e2008-01-30 11:58:22 +0000267/* Same for linebreaks */
268static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000271/* 0x000B, * LINE TABULATION */
272/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000273/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000274 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000276/* 0x001C, * FILE SEPARATOR */
277/* 0x001D, * GROUP SEPARATOR */
278/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 1, 1, 1, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000284
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
292 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000293};
294
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300295/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
296 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000298PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000299{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000300#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000303 /* This is actually an illegal character, so it should
304 not be passed to unichr. */
305 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000306#endif
307}
308
Victor Stinner910337b2011-10-03 03:20:16 +0200309#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200310int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200311/* FIXME: use PyObject* type for op */
312_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200313{
314 PyASCIIObject *ascii;
315 unsigned int kind;
316
317 assert(PyUnicode_Check(op));
318
319 ascii = (PyASCIIObject *)op;
320 kind = ascii->state.kind;
321
Victor Stinnera3b334d2011-10-03 13:53:37 +0200322 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200324 assert(ascii->state.ready == 1);
325 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200326 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200327 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200328 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200329
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 if (ascii->state.compact == 1) {
331 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200332 assert(kind == PyUnicode_1BYTE_KIND
333 || kind == PyUnicode_2BYTE_KIND
334 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200335 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200336 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 assert (compact->utf8 != data);
338 } else {
339 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
340
341 data = unicode->data.any;
342 if (kind == PyUnicode_WCHAR_KIND) {
343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
346 assert(ascii->wstr != NULL);
347 assert(data == NULL);
348 assert(compact->utf8 == NULL);
349 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
391 void *data = PyUnicode_DATA(ascii);
392 for (i=0; i < ascii->length; i++)
393 {
394 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
395 if (ch > maxchar)
396 maxchar = ch;
397 }
398 if (kind == PyUnicode_1BYTE_KIND) {
399 if (ascii->state.ascii == 0)
400 assert(maxchar >= 128);
401 else
402 assert(maxchar < 128);
403 }
404 else if (kind == PyUnicode_2BYTE_KIND)
405 assert(maxchar >= 0x100);
406 else
407 assert(maxchar >= 0x10000);
408 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200409 if (check_content && !unicode_is_singleton((PyObject*)ascii))
410 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400411 return 1;
412}
Victor Stinner910337b2011-10-03 03:20:16 +0200413#endif
414
Victor Stinner3a50e702011-10-18 21:21:00 +0200415#ifdef HAVE_MBCS
416static OSVERSIONINFOEX winver;
417#endif
418
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419/* --- Bloom Filters ----------------------------------------------------- */
420
421/* stuff to implement simple "bloom filters" for Unicode characters.
422 to keep things simple, we use a single bitmask, using the least 5
423 bits from each unicode characters as the bit index. */
424
425/* the linebreak mask is set up by Unicode_Init below */
426
Antoine Pitrouf068f942010-01-13 14:19:12 +0000427#if LONG_BIT >= 128
428#define BLOOM_WIDTH 128
429#elif LONG_BIT >= 64
430#define BLOOM_WIDTH 64
431#elif LONG_BIT >= 32
432#define BLOOM_WIDTH 32
433#else
434#error "LONG_BIT is smaller than 32"
435#endif
436
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437#define BLOOM_MASK unsigned long
438
439static BLOOM_MASK bloom_linebreak;
440
Antoine Pitrouf068f942010-01-13 14:19:12 +0000441#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
442#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Benjamin Peterson29060642009-01-31 22:14:21 +0000444#define BLOOM_LINEBREAK(ch) \
445 ((ch) < 128U ? ascii_linebreak[(ch)] : \
446 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Alexander Belopolsky40018472011-02-26 01:02:56 +0000448Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200449make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450{
451 /* calculate simple bloom-style bitmask for a given unicode string */
452
Antoine Pitrouf068f942010-01-13 14:19:12 +0000453 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 Py_ssize_t i;
455
456 mask = 0;
457 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200458 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459
460 return mask;
461}
462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200463#define BLOOM_MEMBER(mask, chr, str) \
464 (BLOOM(mask, chr) \
465 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000466
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200467/* Compilation of templated routines */
468
469#include "stringlib/asciilib.h"
470#include "stringlib/fastsearch.h"
471#include "stringlib/partition.h"
472#include "stringlib/split.h"
473#include "stringlib/count.h"
474#include "stringlib/find.h"
475#include "stringlib/find_max_char.h"
476#include "stringlib/localeutil.h"
477#include "stringlib/undef.h"
478
479#include "stringlib/ucs1lib.h"
480#include "stringlib/fastsearch.h"
481#include "stringlib/partition.h"
482#include "stringlib/split.h"
483#include "stringlib/count.h"
484#include "stringlib/find.h"
485#include "stringlib/find_max_char.h"
486#include "stringlib/localeutil.h"
487#include "stringlib/undef.h"
488
489#include "stringlib/ucs2lib.h"
490#include "stringlib/fastsearch.h"
491#include "stringlib/partition.h"
492#include "stringlib/split.h"
493#include "stringlib/count.h"
494#include "stringlib/find.h"
495#include "stringlib/find_max_char.h"
496#include "stringlib/localeutil.h"
497#include "stringlib/undef.h"
498
499#include "stringlib/ucs4lib.h"
500#include "stringlib/fastsearch.h"
501#include "stringlib/partition.h"
502#include "stringlib/split.h"
503#include "stringlib/count.h"
504#include "stringlib/find.h"
505#include "stringlib/find_max_char.h"
506#include "stringlib/localeutil.h"
507#include "stringlib/undef.h"
508
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200509#include "stringlib/unicodedefs.h"
510#include "stringlib/fastsearch.h"
511#include "stringlib/count.h"
512#include "stringlib/find.h"
513
Guido van Rossumd57fd912000-03-10 22:53:23 +0000514/* --- Unicode Object ----------------------------------------------------- */
515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200516static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200517fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
520 Py_ssize_t size, Py_UCS4 ch,
521 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200522{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200523 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
524
525 switch (kind) {
526 case PyUnicode_1BYTE_KIND:
527 {
528 Py_UCS1 ch1 = (Py_UCS1) ch;
529 if (ch1 == ch)
530 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
531 else
532 return -1;
533 }
534 case PyUnicode_2BYTE_KIND:
535 {
536 Py_UCS2 ch2 = (Py_UCS2) ch;
537 if (ch2 == ch)
538 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
539 else
540 return -1;
541 }
542 case PyUnicode_4BYTE_KIND:
543 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
544 default:
545 assert(0);
546 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200547 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200548}
549
Victor Stinnerfe226c02011-10-03 03:52:20 +0200550static PyObject*
551resize_compact(PyObject *unicode, Py_ssize_t length)
552{
553 Py_ssize_t char_size;
554 Py_ssize_t struct_size;
555 Py_ssize_t new_size;
556 int share_wstr;
557
558 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200559 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200560 if (PyUnicode_IS_COMPACT_ASCII(unicode))
561 struct_size = sizeof(PyASCIIObject);
562 else
563 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200564 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200565
566 _Py_DEC_REFTOTAL;
567 _Py_ForgetReference(unicode);
568
569 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
570 PyErr_NoMemory();
571 return NULL;
572 }
573 new_size = (struct_size + (length + 1) * char_size);
574
575 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
576 if (unicode == NULL) {
577 PyObject_Del(unicode);
578 PyErr_NoMemory();
579 return NULL;
580 }
581 _Py_NewReference(unicode);
582 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200583 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200585 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
586 _PyUnicode_WSTR_LENGTH(unicode) = length;
587 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200588 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
589 length, 0);
590 return unicode;
591}
592
Alexander Belopolsky40018472011-02-26 01:02:56 +0000593static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200594resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000595{
Victor Stinner95663112011-10-04 01:03:50 +0200596 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200597 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200598 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000599
Victor Stinner95663112011-10-04 01:03:50 +0200600 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200601
602 if (PyUnicode_IS_READY(unicode)) {
603 Py_ssize_t char_size;
604 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200605 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200606 void *data;
607
608 data = _PyUnicode_DATA_ANY(unicode);
609 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200610 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200611 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
612 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200613 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
614 {
615 PyObject_DEL(_PyUnicode_UTF8(unicode));
616 _PyUnicode_UTF8(unicode) = NULL;
617 _PyUnicode_UTF8_LENGTH(unicode) = 0;
618 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200619
620 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
621 PyErr_NoMemory();
622 return -1;
623 }
624 new_size = (length + 1) * char_size;
625
626 data = (PyObject *)PyObject_REALLOC(data, new_size);
627 if (data == NULL) {
628 PyErr_NoMemory();
629 return -1;
630 }
631 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200632 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200633 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_WSTR_LENGTH(unicode) = length;
635 }
636 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200637 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200638 _PyUnicode_UTF8_LENGTH(unicode) = length;
639 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 _PyUnicode_LENGTH(unicode) = length;
641 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200642 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200643 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200644 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200645 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200646 }
Victor Stinner95663112011-10-04 01:03:50 +0200647 assert(_PyUnicode_WSTR(unicode) != NULL);
648
649 /* check for integer overflow */
650 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
651 PyErr_NoMemory();
652 return -1;
653 }
654 wstr = _PyUnicode_WSTR(unicode);
655 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
656 if (!wstr) {
657 PyErr_NoMemory();
658 return -1;
659 }
660 _PyUnicode_WSTR(unicode) = wstr;
661 _PyUnicode_WSTR(unicode)[length] = 0;
662 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200663 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000664 return 0;
665}
666
Victor Stinnerfe226c02011-10-03 03:52:20 +0200667static PyObject*
668resize_copy(PyObject *unicode, Py_ssize_t length)
669{
670 Py_ssize_t copy_length;
671 if (PyUnicode_IS_COMPACT(unicode)) {
672 PyObject *copy;
673 assert(PyUnicode_IS_READY(unicode));
674
675 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
676 if (copy == NULL)
677 return NULL;
678
679 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200680 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200682 }
683 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200684 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200685 assert(_PyUnicode_WSTR(unicode) != NULL);
686 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200687 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200688 if (w == NULL)
689 return NULL;
690 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
691 copy_length = Py_MIN(copy_length, length);
692 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
693 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200694 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 }
696}
697
Guido van Rossumd57fd912000-03-10 22:53:23 +0000698/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000699 Ux0000 terminated; some code (e.g. new_identifier)
700 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000701
702 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000703 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000704
705*/
706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200707#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200708static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709#endif
710
Alexander Belopolsky40018472011-02-26 01:02:56 +0000711static PyUnicodeObject *
712_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000713{
714 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200715 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000716
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000718 if (length == 0 && unicode_empty != NULL) {
719 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200720 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000721 }
722
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000723 /* Ensure we won't overflow the size. */
724 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
725 return (PyUnicodeObject *)PyErr_NoMemory();
726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200727 if (length < 0) {
728 PyErr_SetString(PyExc_SystemError,
729 "Negative size passed to _PyUnicode_New");
730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000731 }
732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200733#ifdef Py_DEBUG
734 ++unicode_old_new_calls;
735#endif
736
737 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
738 if (unicode == NULL)
739 return NULL;
740 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
741 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
742 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000743 PyErr_NoMemory();
744 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200746
Jeremy Hyltond8082792003-09-16 19:41:39 +0000747 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000748 * the caller fails before initializing str -- unicode_resize()
749 * reads str[0], and the Keep-Alive optimization can keep memory
750 * allocated for str alive across a call to unicode_dealloc(unicode).
751 * We don't want unicode_resize to read uninitialized memory in
752 * that case.
753 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200754 _PyUnicode_WSTR(unicode)[0] = 0;
755 _PyUnicode_WSTR(unicode)[length] = 0;
756 _PyUnicode_WSTR_LENGTH(unicode) = length;
757 _PyUnicode_HASH(unicode) = -1;
758 _PyUnicode_STATE(unicode).interned = 0;
759 _PyUnicode_STATE(unicode).kind = 0;
760 _PyUnicode_STATE(unicode).compact = 0;
761 _PyUnicode_STATE(unicode).ready = 0;
762 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200763 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200764 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200765 _PyUnicode_UTF8(unicode) = NULL;
766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner67072932011-10-18 22:10:14 +0200767 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000768 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769
Benjamin Peterson29060642009-01-31 22:14:21 +0000770 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000771 /* XXX UNREF/NEWREF interface should be more symmetrical */
772 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000773 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000774 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000776}
777
Victor Stinnerf42dc442011-10-02 23:33:16 +0200778static const char*
779unicode_kind_name(PyObject *unicode)
780{
Victor Stinner42dfd712011-10-03 14:41:45 +0200781 /* don't check consistency: unicode_kind_name() is called from
782 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200783 if (!PyUnicode_IS_COMPACT(unicode))
784 {
785 if (!PyUnicode_IS_READY(unicode))
786 return "wstr";
787 switch(PyUnicode_KIND(unicode))
788 {
789 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200790 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200791 return "legacy ascii";
792 else
793 return "legacy latin1";
794 case PyUnicode_2BYTE_KIND:
795 return "legacy UCS2";
796 case PyUnicode_4BYTE_KIND:
797 return "legacy UCS4";
798 default:
799 return "<legacy invalid kind>";
800 }
801 }
802 assert(PyUnicode_IS_READY(unicode));
803 switch(PyUnicode_KIND(unicode))
804 {
805 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200806 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200807 return "ascii";
808 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200811 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200812 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200813 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200814 default:
815 return "<invalid compact kind>";
816 }
817}
818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200820static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821
822/* Functions wrapping macros for use in debugger */
823char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200824 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200825}
826
827void *_PyUnicode_compact_data(void *unicode) {
828 return _PyUnicode_COMPACT_DATA(unicode);
829}
830void *_PyUnicode_data(void *unicode){
831 printf("obj %p\n", unicode);
832 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
833 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
834 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
835 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
836 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
837 return PyUnicode_DATA(unicode);
838}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200839
840void
841_PyUnicode_Dump(PyObject *op)
842{
843 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
845 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
846 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200847
Victor Stinnera849a4b2011-10-03 12:12:11 +0200848 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200849 {
850 if (ascii->state.ascii)
851 data = (ascii + 1);
852 else
853 data = (compact + 1);
854 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 else
856 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200857 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
858
Victor Stinnera849a4b2011-10-03 12:12:11 +0200859 if (ascii->wstr == data)
860 printf("shared ");
861 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200862
Victor Stinnera3b334d2011-10-03 13:53:37 +0200863 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200864 printf(" (%zu), ", compact->wstr_length);
865 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
866 printf("shared ");
867 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200868 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200869 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200870}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871#endif
872
873PyObject *
874PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
875{
876 PyObject *obj;
877 PyCompactUnicodeObject *unicode;
878 void *data;
879 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200880 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200881 Py_ssize_t char_size;
882 Py_ssize_t struct_size;
883
884 /* Optimization for empty strings */
885 if (size == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200888 }
889
890#ifdef Py_DEBUG
891 ++unicode_new_new_calls;
892#endif
893
Victor Stinner9e9d6892011-10-04 01:02:02 +0200894 is_ascii = 0;
895 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 struct_size = sizeof(PyCompactUnicodeObject);
897 if (maxchar < 128) {
898 kind_state = PyUnicode_1BYTE_KIND;
899 char_size = 1;
900 is_ascii = 1;
901 struct_size = sizeof(PyASCIIObject);
902 }
903 else if (maxchar < 256) {
904 kind_state = PyUnicode_1BYTE_KIND;
905 char_size = 1;
906 }
907 else if (maxchar < 65536) {
908 kind_state = PyUnicode_2BYTE_KIND;
909 char_size = 2;
910 if (sizeof(wchar_t) == 2)
911 is_sharing = 1;
912 }
913 else {
914 kind_state = PyUnicode_4BYTE_KIND;
915 char_size = 4;
916 if (sizeof(wchar_t) == 4)
917 is_sharing = 1;
918 }
919
920 /* Ensure we won't overflow the size. */
921 if (size < 0) {
922 PyErr_SetString(PyExc_SystemError,
923 "Negative size passed to PyUnicode_New");
924 return NULL;
925 }
926 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
927 return PyErr_NoMemory();
928
929 /* Duplicated allocation code from _PyObject_New() instead of a call to
930 * PyObject_New() so we are able to allocate space for the object and
931 * it's data buffer.
932 */
933 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
934 if (obj == NULL)
935 return PyErr_NoMemory();
936 obj = PyObject_INIT(obj, &PyUnicode_Type);
937 if (obj == NULL)
938 return NULL;
939
940 unicode = (PyCompactUnicodeObject *)obj;
941 if (is_ascii)
942 data = ((PyASCIIObject*)obj) + 1;
943 else
944 data = unicode + 1;
945 _PyUnicode_LENGTH(unicode) = size;
946 _PyUnicode_HASH(unicode) = -1;
947 _PyUnicode_STATE(unicode).interned = 0;
948 _PyUnicode_STATE(unicode).kind = kind_state;
949 _PyUnicode_STATE(unicode).compact = 1;
950 _PyUnicode_STATE(unicode).ready = 1;
951 _PyUnicode_STATE(unicode).ascii = is_ascii;
952 if (is_ascii) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 }
956 else if (kind_state == PyUnicode_1BYTE_KIND) {
957 ((char*)data)[size] = 0;
958 _PyUnicode_WSTR(unicode) = NULL;
959 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 }
963 else {
964 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200965 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200966 if (kind_state == PyUnicode_2BYTE_KIND)
967 ((Py_UCS2*)data)[size] = 0;
968 else /* kind_state == PyUnicode_4BYTE_KIND */
969 ((Py_UCS4*)data)[size] = 0;
970 if (is_sharing) {
971 _PyUnicode_WSTR_LENGTH(unicode) = size;
972 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
973 }
974 else {
975 _PyUnicode_WSTR_LENGTH(unicode) = 0;
976 _PyUnicode_WSTR(unicode) = NULL;
977 }
978 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200979 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 return obj;
981}
982
983#if SIZEOF_WCHAR_T == 2
984/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
985 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200986 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987
988 This function assumes that unicode can hold one more code point than wstr
989 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200990static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200991unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200992 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993{
994 const wchar_t *iter;
995 Py_UCS4 *ucs4_out;
996
Victor Stinner910337b2011-10-03 03:20:16 +0200997 assert(unicode != NULL);
998 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200999 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1000 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1001
1002 for (iter = begin; iter < end; ) {
1003 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1004 _PyUnicode_GET_LENGTH(unicode)));
1005 if (*iter >= 0xD800 && *iter <= 0xDBFF
1006 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1007 {
1008 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1009 iter += 2;
1010 }
1011 else {
1012 *ucs4_out++ = *iter;
1013 iter++;
1014 }
1015 }
1016 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1017 _PyUnicode_GET_LENGTH(unicode)));
1018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001019}
1020#endif
1021
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022static int
1023_PyUnicode_Dirty(PyObject *unicode)
1024{
Victor Stinner910337b2011-10-03 03:20:16 +02001025 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001026 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001027 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001028 "Cannot modify a string having more than 1 reference");
1029 return -1;
1030 }
1031 _PyUnicode_DIRTY(unicode);
1032 return 0;
1033}
1034
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001035static int
1036_copy_characters(PyObject *to, Py_ssize_t to_start,
1037 PyObject *from, Py_ssize_t from_start,
1038 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001040 unsigned int from_kind, to_kind;
1041 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001042 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001044 assert(PyUnicode_Check(from));
1045 assert(PyUnicode_Check(to));
1046 assert(PyUnicode_IS_READY(from));
1047 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001049 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1050 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1051 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001053 if (how_many == 0)
1054 return 0;
1055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001057 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001059 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001061#ifdef Py_DEBUG
1062 if (!check_maxchar
1063 && (from_kind > to_kind
1064 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001065 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001066 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1067 Py_UCS4 ch;
1068 Py_ssize_t i;
1069 for (i=0; i < how_many; i++) {
1070 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1071 assert(ch <= to_maxchar);
1072 }
1073 }
1074#endif
1075 fast = (from_kind == to_kind);
1076 if (check_maxchar
1077 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1078 {
1079 /* deny latin1 => ascii */
1080 fast = 0;
1081 }
1082
1083 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001084 Py_MEMCPY((char*)to_data + to_kind * to_start,
1085 (char*)from_data + from_kind * from_start,
1086 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001088 else if (from_kind == PyUnicode_1BYTE_KIND
1089 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001090 {
1091 _PyUnicode_CONVERT_BYTES(
1092 Py_UCS1, Py_UCS2,
1093 PyUnicode_1BYTE_DATA(from) + from_start,
1094 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1095 PyUnicode_2BYTE_DATA(to) + to_start
1096 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001097 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001098 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001099 && to_kind == PyUnicode_4BYTE_KIND)
1100 {
1101 _PyUnicode_CONVERT_BYTES(
1102 Py_UCS1, Py_UCS4,
1103 PyUnicode_1BYTE_DATA(from) + from_start,
1104 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1105 PyUnicode_4BYTE_DATA(to) + to_start
1106 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001107 }
1108 else if (from_kind == PyUnicode_2BYTE_KIND
1109 && to_kind == PyUnicode_4BYTE_KIND)
1110 {
1111 _PyUnicode_CONVERT_BYTES(
1112 Py_UCS2, Py_UCS4,
1113 PyUnicode_2BYTE_DATA(from) + from_start,
1114 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1115 PyUnicode_4BYTE_DATA(to) + to_start
1116 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001117 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001118 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 /* check if max_char(from substring) <= max_char(to) */
1120 if (from_kind > to_kind
1121 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001122 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001123 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001124 /* slow path to check for character overflow */
1125 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001126 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 Py_ssize_t i;
1128
Victor Stinner56c161a2011-10-06 02:47:11 +02001129#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001130 for (i=0; i < how_many; i++) {
1131 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001132 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001133 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1134 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001135#else
1136 if (!check_maxchar) {
1137 for (i=0; i < how_many; i++) {
1138 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1139 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1140 }
1141 }
1142 else {
1143 for (i=0; i < how_many; i++) {
1144 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1145 if (ch > to_maxchar)
1146 return 1;
1147 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1148 }
1149 }
1150#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001153 assert(0 && "inconsistent state");
1154 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001155 }
1156 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 return 0;
1158}
1159
1160static void
1161copy_characters(PyObject *to, Py_ssize_t to_start,
1162 PyObject *from, Py_ssize_t from_start,
1163 Py_ssize_t how_many)
1164{
1165 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1166}
1167
1168Py_ssize_t
1169PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1170 PyObject *from, Py_ssize_t from_start,
1171 Py_ssize_t how_many)
1172{
1173 int err;
1174
1175 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1176 PyErr_BadInternalCall();
1177 return -1;
1178 }
1179
1180 if (PyUnicode_READY(from))
1181 return -1;
1182 if (PyUnicode_READY(to))
1183 return -1;
1184
1185 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1186 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1187 PyErr_Format(PyExc_SystemError,
1188 "Cannot write %zi characters at %zi "
1189 "in a string of %zi characters",
1190 how_many, to_start, PyUnicode_GET_LENGTH(to));
1191 return -1;
1192 }
1193
1194 if (how_many == 0)
1195 return 0;
1196
1197 if (_PyUnicode_Dirty(to))
1198 return -1;
1199
1200 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1201 if (err) {
1202 PyErr_Format(PyExc_SystemError,
1203 "Cannot copy %s characters "
1204 "into a string of %s characters",
1205 unicode_kind_name(from),
1206 unicode_kind_name(to));
1207 return -1;
1208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210}
1211
Victor Stinner17222162011-09-28 22:15:37 +02001212/* Find the maximum code point and count the number of surrogate pairs so a
1213 correct string length can be computed before converting a string to UCS4.
1214 This function counts single surrogates as a character and not as a pair.
1215
1216 Return 0 on success, or -1 on error. */
1217static int
1218find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1219 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220{
1221 const wchar_t *iter;
1222
Victor Stinnerc53be962011-10-02 21:33:54 +02001223 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 *num_surrogates = 0;
1225 *maxchar = 0;
1226
1227 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001228 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001230#if SIZEOF_WCHAR_T != 2
1231 if (*maxchar >= 0x10000)
1232 return 0;
1233#endif
1234 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235#if SIZEOF_WCHAR_T == 2
1236 if (*iter >= 0xD800 && *iter <= 0xDBFF
1237 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1238 {
1239 Py_UCS4 surrogate_val;
1240 surrogate_val = (((iter[0] & 0x3FF)<<10)
1241 | (iter[1] & 0x3FF)) + 0x10000;
1242 ++(*num_surrogates);
1243 if (surrogate_val > *maxchar)
1244 *maxchar = surrogate_val;
1245 iter += 2;
1246 }
1247 else
1248 iter++;
1249#else
1250 iter++;
1251#endif
1252 }
1253 return 0;
1254}
1255
1256#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001257static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258#endif
1259
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001260static int
1261unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001263 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 wchar_t *end;
1265 Py_UCS4 maxchar = 0;
1266 Py_ssize_t num_surrogates;
1267#if SIZEOF_WCHAR_T == 2
1268 Py_ssize_t length_wo_surrogates;
1269#endif
1270
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001271 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001272 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001273
Georg Brandl7597add2011-10-05 16:36:47 +02001274 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001275 strings were created using _PyObject_New() and where no canonical
1276 representation (the str field) has been set yet aka strings
1277 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001278 assert(_PyUnicode_CHECK(unicode));
1279 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001280 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001281 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001282 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001283 /* Actually, it should neither be interned nor be anything else: */
1284 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285
1286#ifdef Py_DEBUG
1287 ++unicode_ready_calls;
1288#endif
1289
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001290#ifdef Py_DEBUG
1291 assert(!replace || Py_REFCNT(unicode) == 1);
1292#else
1293 if (replace && Py_REFCNT(unicode) != 1)
1294 replace = 0;
1295#endif
1296 if (replace) {
1297 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1298 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1299 /* Optimization for empty strings */
1300 if (len == 0) {
1301 Py_INCREF(unicode_empty);
1302 Py_DECREF(*p_obj);
1303 *p_obj = unicode_empty;
1304 return 0;
1305 }
1306 if (len == 1 && wstr[0] < 256) {
1307 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1308 if (latin1_char == NULL)
1309 return -1;
1310 Py_DECREF(*p_obj);
1311 *p_obj = latin1_char;
1312 return 0;
1313 }
1314 }
1315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001317 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001318 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320
1321 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001322 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1323 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 PyErr_NoMemory();
1325 return -1;
1326 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001327 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328 _PyUnicode_WSTR(unicode), end,
1329 PyUnicode_1BYTE_DATA(unicode));
1330 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1331 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1332 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1333 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001334 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001335 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337 }
1338 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001339 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001340 _PyUnicode_UTF8(unicode) = NULL;
1341 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 }
1343 PyObject_FREE(_PyUnicode_WSTR(unicode));
1344 _PyUnicode_WSTR(unicode) = NULL;
1345 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1346 }
1347 /* In this case we might have to convert down from 4-byte native
1348 wchar_t to 2-byte unicode. */
1349 else if (maxchar < 65536) {
1350 assert(num_surrogates == 0 &&
1351 "FindMaxCharAndNumSurrogatePairs() messed up");
1352
Victor Stinner506f5922011-09-28 22:34:18 +02001353#if SIZEOF_WCHAR_T == 2
1354 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001355 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001356 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1357 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1358 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001359 _PyUnicode_UTF8(unicode) = NULL;
1360 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001361#else
1362 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001363 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001364 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001365 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001366 PyErr_NoMemory();
1367 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 }
Victor Stinner506f5922011-09-28 22:34:18 +02001369 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1370 _PyUnicode_WSTR(unicode), end,
1371 PyUnicode_2BYTE_DATA(unicode));
1372 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1373 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1374 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001375 _PyUnicode_UTF8(unicode) = NULL;
1376 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001377 PyObject_FREE(_PyUnicode_WSTR(unicode));
1378 _PyUnicode_WSTR(unicode) = NULL;
1379 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1380#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 }
1382 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1383 else {
1384#if SIZEOF_WCHAR_T == 2
1385 /* in case the native representation is 2-bytes, we need to allocate a
1386 new normalized 4-byte version. */
1387 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1389 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 PyErr_NoMemory();
1391 return -1;
1392 }
1393 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1394 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001395 _PyUnicode_UTF8(unicode) = NULL;
1396 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001397 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1398 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001399 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 PyObject_FREE(_PyUnicode_WSTR(unicode));
1401 _PyUnicode_WSTR(unicode) = NULL;
1402 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1403#else
1404 assert(num_surrogates == 0);
1405
Victor Stinnerc3c74152011-10-02 20:39:55 +02001406 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001408 _PyUnicode_UTF8(unicode) = NULL;
1409 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1411#endif
1412 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1413 }
1414 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001415 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416 return 0;
1417}
1418
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001419int
1420_PyUnicode_ReadyReplace(PyObject **op)
1421{
1422 return unicode_ready(op, 1);
1423}
1424
1425int
1426_PyUnicode_Ready(PyObject *op)
1427{
1428 return unicode_ready(&op, 0);
1429}
1430
Alexander Belopolsky40018472011-02-26 01:02:56 +00001431static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001432unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001433{
Walter Dörwald16807132007-05-25 13:52:07 +00001434 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001435 case SSTATE_NOT_INTERNED:
1436 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001437
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 case SSTATE_INTERNED_MORTAL:
1439 /* revive dead object temporarily for DelItem */
1440 Py_REFCNT(unicode) = 3;
1441 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1442 Py_FatalError(
1443 "deletion of interned string failed");
1444 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001445
Benjamin Peterson29060642009-01-31 22:14:21 +00001446 case SSTATE_INTERNED_IMMORTAL:
1447 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001448
Benjamin Peterson29060642009-01-31 22:14:21 +00001449 default:
1450 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001451 }
1452
Victor Stinner03490912011-10-03 23:45:12 +02001453 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001454 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001455 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001456 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001457
1458 if (PyUnicode_IS_COMPACT(unicode)) {
1459 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001460 }
1461 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 if (_PyUnicode_DATA_ANY(unicode))
1463 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001464 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001465 }
1466}
1467
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001468#ifdef Py_DEBUG
1469static int
1470unicode_is_singleton(PyObject *unicode)
1471{
1472 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1473 if (unicode == unicode_empty)
1474 return 1;
1475 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1476 {
1477 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1478 if (ch < 256 && unicode_latin1[ch] == unicode)
1479 return 1;
1480 }
1481 return 0;
1482}
1483#endif
1484
Alexander Belopolsky40018472011-02-26 01:02:56 +00001485static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001486unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001487{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001488 if (Py_REFCNT(unicode) != 1)
1489 return 0;
1490 if (PyUnicode_CHECK_INTERNED(unicode))
1491 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001492#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001493 /* singleton refcount is greater than 1 */
1494 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001495#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001496 return 1;
1497}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001498
Victor Stinnerfe226c02011-10-03 03:52:20 +02001499static int
1500unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1501{
1502 PyObject *unicode;
1503 Py_ssize_t old_length;
1504
1505 assert(p_unicode != NULL);
1506 unicode = *p_unicode;
1507
1508 assert(unicode != NULL);
1509 assert(PyUnicode_Check(unicode));
1510 assert(0 <= length);
1511
Victor Stinner910337b2011-10-03 03:20:16 +02001512 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001513 old_length = PyUnicode_WSTR_LENGTH(unicode);
1514 else
1515 old_length = PyUnicode_GET_LENGTH(unicode);
1516 if (old_length == length)
1517 return 0;
1518
Victor Stinnerfe226c02011-10-03 03:52:20 +02001519 if (!unicode_resizable(unicode)) {
1520 PyObject *copy = resize_copy(unicode, length);
1521 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001522 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001523 Py_DECREF(*p_unicode);
1524 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001526 }
1527
Victor Stinnerfe226c02011-10-03 03:52:20 +02001528 if (PyUnicode_IS_COMPACT(unicode)) {
1529 *p_unicode = resize_compact(unicode, length);
1530 if (*p_unicode == NULL)
1531 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001532 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001533 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001534 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001535 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001536}
1537
Alexander Belopolsky40018472011-02-26 01:02:56 +00001538int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001539PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001540{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001541 PyObject *unicode;
1542 if (p_unicode == NULL) {
1543 PyErr_BadInternalCall();
1544 return -1;
1545 }
1546 unicode = *p_unicode;
1547 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1548 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1549 {
1550 PyErr_BadInternalCall();
1551 return -1;
1552 }
1553 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001554}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001556static PyObject*
1557get_latin1_char(unsigned char ch)
1558{
Victor Stinnera464fc12011-10-02 20:39:30 +02001559 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001561 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001562 if (!unicode)
1563 return NULL;
1564 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 unicode_latin1[ch] = unicode;
1567 }
1568 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001569 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001570}
1571
Alexander Belopolsky40018472011-02-26 01:02:56 +00001572PyObject *
1573PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001574{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001575 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001576 Py_UCS4 maxchar = 0;
1577 Py_ssize_t num_surrogates;
1578
1579 if (u == NULL)
1580 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001581
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001582 /* If the Unicode data is known at construction time, we can apply
1583 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585 /* Optimization for empty strings */
1586 if (size == 0 && unicode_empty != NULL) {
1587 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001588 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001589 }
Tim Petersced69f82003-09-16 20:30:58 +00001590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001591 /* Single character Unicode objects in the Latin-1 range are
1592 shared when using this constructor */
1593 if (size == 1 && *u < 256)
1594 return get_latin1_char((unsigned char)*u);
1595
1596 /* If not empty and not single character, copy the Unicode data
1597 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001598 if (find_maxchar_surrogates(u, u + size,
1599 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600 return NULL;
1601
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001602 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001604 if (!unicode)
1605 return NULL;
1606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607 switch (PyUnicode_KIND(unicode)) {
1608 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001609 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1611 break;
1612 case PyUnicode_2BYTE_KIND:
1613#if Py_UNICODE_SIZE == 2
1614 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1615#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001616 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1618#endif
1619 break;
1620 case PyUnicode_4BYTE_KIND:
1621#if SIZEOF_WCHAR_T == 2
1622 /* This is the only case which has to process surrogates, thus
1623 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001624 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001625#else
1626 assert(num_surrogates == 0);
1627 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1628#endif
1629 break;
1630 default:
1631 assert(0 && "Impossible state");
1632 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001633
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001634 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001635 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636}
1637
Alexander Belopolsky40018472011-02-26 01:02:56 +00001638PyObject *
1639PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001640{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001641 if (size < 0) {
1642 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001643 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001644 return NULL;
1645 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001646
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001647 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001648 some optimizations which share commonly used objects.
1649 Also, this means the input must be UTF-8, so fall back to the
1650 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001651 if (u != NULL) {
1652
Benjamin Peterson29060642009-01-31 22:14:21 +00001653 /* Optimization for empty strings */
1654 if (size == 0 && unicode_empty != NULL) {
1655 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001656 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001657 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001658
1659 /* Single characters are shared when using this constructor.
1660 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001661 if (size == 1 && (unsigned char)*u < 128)
1662 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001663
1664 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001665 }
1666
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001672{
1673 size_t size = strlen(u);
1674 if (size > PY_SSIZE_T_MAX) {
1675 PyErr_SetString(PyExc_OverflowError, "input too long");
1676 return NULL;
1677 }
1678
1679 return PyUnicode_FromStringAndSize(u, size);
1680}
1681
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001682PyObject *
1683_PyUnicode_FromId(_Py_Identifier *id)
1684{
1685 if (!id->object) {
1686 id->object = PyUnicode_FromString(id->string);
1687 if (!id->object)
1688 return NULL;
1689 PyUnicode_InternInPlace(&id->object);
1690 assert(!id->next);
1691 id->next = static_strings;
1692 static_strings = id;
1693 }
1694 Py_INCREF(id->object);
1695 return id->object;
1696}
1697
1698void
1699_PyUnicode_ClearStaticStrings()
1700{
1701 _Py_Identifier *i;
1702 for (i = static_strings; i; i = i->next) {
1703 Py_DECREF(i->object);
1704 i->object = NULL;
1705 i->next = NULL;
1706 }
1707}
1708
Victor Stinnere57b1c02011-09-28 22:20:48 +02001709static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001710unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001711{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001712 PyObject *res;
1713#ifdef Py_DEBUG
1714 const unsigned char *p;
1715 const unsigned char *end = s + size;
1716 for (p=s; p < end; p++) {
1717 assert(*p < 128);
1718 }
1719#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001720 if (size == 1)
1721 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001722 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001723 if (!res)
1724 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001725 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001726 return res;
1727}
1728
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001729static Py_UCS4
1730kind_maxchar_limit(unsigned int kind)
1731{
1732 switch(kind) {
1733 case PyUnicode_1BYTE_KIND:
1734 return 0x80;
1735 case PyUnicode_2BYTE_KIND:
1736 return 0x100;
1737 case PyUnicode_4BYTE_KIND:
1738 return 0x10000;
1739 default:
1740 assert(0 && "invalid kind");
1741 return 0x10ffff;
1742 }
1743}
1744
Victor Stinner702c7342011-10-05 13:50:52 +02001745static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001746_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001749 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001750
1751 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001752 if (size == 1)
1753 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001754 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001755 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 if (!res)
1757 return NULL;
1758 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001759 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001761}
1762
Victor Stinnere57b1c02011-09-28 22:20:48 +02001763static PyObject*
1764_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765{
1766 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001767 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001768
1769 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001770 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001771 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001772 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001773 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001774 if (!res)
1775 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001776 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001777 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001778 else {
1779 _PyUnicode_CONVERT_BYTES(
1780 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1781 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001782 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 return res;
1784}
1785
Victor Stinnere57b1c02011-09-28 22:20:48 +02001786static PyObject*
1787_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788{
1789 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001790 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001791
1792 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001793 if (size == 1 && u[0] < 256)
1794 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001795 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001796 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797 if (!res)
1798 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001799 if (max_char < 256)
1800 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1801 PyUnicode_1BYTE_DATA(res));
1802 else if (max_char < 0x10000)
1803 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1804 PyUnicode_2BYTE_DATA(res));
1805 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001807 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 return res;
1809}
1810
1811PyObject*
1812PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1813{
1814 switch(kind) {
1815 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001816 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001817 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001818 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001820 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 default:
1822 assert(0 && "invalid kind");
1823 PyErr_SetString(PyExc_SystemError, "invalid kind");
1824 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001826}
1827
Victor Stinner25a4b292011-10-06 12:31:55 +02001828/* Ensure that a string uses the most efficient storage, if it is not the
1829 case: create a new string with of the right kind. Write NULL into *p_unicode
1830 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001831static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001832unicode_adjust_maxchar(PyObject **p_unicode)
1833{
1834 PyObject *unicode, *copy;
1835 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001836 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001837 unsigned int kind;
1838
1839 assert(p_unicode != NULL);
1840 unicode = *p_unicode;
1841 assert(PyUnicode_IS_READY(unicode));
1842 if (PyUnicode_IS_ASCII(unicode))
1843 return;
1844
1845 len = PyUnicode_GET_LENGTH(unicode);
1846 kind = PyUnicode_KIND(unicode);
1847 if (kind == PyUnicode_1BYTE_KIND) {
1848 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001849 max_char = ucs1lib_find_max_char(u, u + len);
1850 if (max_char >= 128)
1851 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001852 }
1853 else if (kind == PyUnicode_2BYTE_KIND) {
1854 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001855 max_char = ucs2lib_find_max_char(u, u + len);
1856 if (max_char >= 256)
1857 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001858 }
1859 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001860 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001861 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001862 max_char = ucs4lib_find_max_char(u, u + len);
1863 if (max_char >= 0x10000)
1864 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001865 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001866 copy = PyUnicode_New(len, max_char);
1867 copy_characters(copy, 0, unicode, 0, len);
1868 Py_DECREF(unicode);
1869 *p_unicode = copy;
1870}
1871
Victor Stinner034f6cf2011-09-30 02:26:44 +02001872PyObject*
1873PyUnicode_Copy(PyObject *unicode)
1874{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001875 Py_ssize_t size;
1876 PyObject *copy;
1877 void *data;
1878
Victor Stinner034f6cf2011-09-30 02:26:44 +02001879 if (!PyUnicode_Check(unicode)) {
1880 PyErr_BadInternalCall();
1881 return NULL;
1882 }
1883 if (PyUnicode_READY(unicode))
1884 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001885
1886 size = PyUnicode_GET_LENGTH(unicode);
1887 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1888 if (!copy)
1889 return NULL;
1890 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1891
1892 data = PyUnicode_DATA(unicode);
1893 switch (PyUnicode_KIND(unicode))
1894 {
1895 case PyUnicode_1BYTE_KIND:
1896 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1897 break;
1898 case PyUnicode_2BYTE_KIND:
1899 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1900 break;
1901 case PyUnicode_4BYTE_KIND:
1902 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1903 break;
1904 default:
1905 assert(0);
1906 break;
1907 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001908 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001909 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001910}
1911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912
Victor Stinnerbc603d12011-10-02 01:00:40 +02001913/* Widen Unicode objects to larger buffers. Don't write terminating null
1914 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915
1916void*
1917_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1918{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001919 Py_ssize_t len;
1920 void *result;
1921 unsigned int skind;
1922
1923 if (PyUnicode_READY(s))
1924 return NULL;
1925
1926 len = PyUnicode_GET_LENGTH(s);
1927 skind = PyUnicode_KIND(s);
1928 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001929 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001930 return NULL;
1931 }
1932 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001933 case PyUnicode_2BYTE_KIND:
1934 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1935 if (!result)
1936 return PyErr_NoMemory();
1937 assert(skind == PyUnicode_1BYTE_KIND);
1938 _PyUnicode_CONVERT_BYTES(
1939 Py_UCS1, Py_UCS2,
1940 PyUnicode_1BYTE_DATA(s),
1941 PyUnicode_1BYTE_DATA(s) + len,
1942 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001944 case PyUnicode_4BYTE_KIND:
1945 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1946 if (!result)
1947 return PyErr_NoMemory();
1948 if (skind == PyUnicode_2BYTE_KIND) {
1949 _PyUnicode_CONVERT_BYTES(
1950 Py_UCS2, Py_UCS4,
1951 PyUnicode_2BYTE_DATA(s),
1952 PyUnicode_2BYTE_DATA(s) + len,
1953 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001955 else {
1956 assert(skind == PyUnicode_1BYTE_KIND);
1957 _PyUnicode_CONVERT_BYTES(
1958 Py_UCS1, Py_UCS4,
1959 PyUnicode_1BYTE_DATA(s),
1960 PyUnicode_1BYTE_DATA(s) + len,
1961 result);
1962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001963 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001964 default:
1965 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 }
Victor Stinner01698042011-10-04 00:04:26 +02001967 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 return NULL;
1969}
1970
1971static Py_UCS4*
1972as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1973 int copy_null)
1974{
1975 int kind;
1976 void *data;
1977 Py_ssize_t len, targetlen;
1978 if (PyUnicode_READY(string) == -1)
1979 return NULL;
1980 kind = PyUnicode_KIND(string);
1981 data = PyUnicode_DATA(string);
1982 len = PyUnicode_GET_LENGTH(string);
1983 targetlen = len;
1984 if (copy_null)
1985 targetlen++;
1986 if (!target) {
1987 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1988 PyErr_NoMemory();
1989 return NULL;
1990 }
1991 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1992 if (!target) {
1993 PyErr_NoMemory();
1994 return NULL;
1995 }
1996 }
1997 else {
1998 if (targetsize < targetlen) {
1999 PyErr_Format(PyExc_SystemError,
2000 "string is longer than the buffer");
2001 if (copy_null && 0 < targetsize)
2002 target[0] = 0;
2003 return NULL;
2004 }
2005 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002006 if (kind == PyUnicode_1BYTE_KIND) {
2007 Py_UCS1 *start = (Py_UCS1 *) data;
2008 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002010 else if (kind == PyUnicode_2BYTE_KIND) {
2011 Py_UCS2 *start = (Py_UCS2 *) data;
2012 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2013 }
2014 else {
2015 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 if (copy_null)
2019 target[len] = 0;
2020 return target;
2021}
2022
2023Py_UCS4*
2024PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2025 int copy_null)
2026{
2027 if (target == NULL || targetsize < 1) {
2028 PyErr_BadInternalCall();
2029 return NULL;
2030 }
2031 return as_ucs4(string, target, targetsize, copy_null);
2032}
2033
2034Py_UCS4*
2035PyUnicode_AsUCS4Copy(PyObject *string)
2036{
2037 return as_ucs4(string, NULL, 0, 1);
2038}
2039
2040#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002041
Alexander Belopolsky40018472011-02-26 01:02:56 +00002042PyObject *
2043PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002044{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002045 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002046 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002048 PyErr_BadInternalCall();
2049 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 }
2051
Martin v. Löwis790465f2008-04-05 20:41:37 +00002052 if (size == -1) {
2053 size = wcslen(w);
2054 }
2055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002057}
2058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002060
Walter Dörwald346737f2007-05-31 10:44:43 +00002061static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002062makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2063 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002064{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002065 *fmt++ = '%';
2066 if (width) {
2067 if (zeropad)
2068 *fmt++ = '0';
2069 fmt += sprintf(fmt, "%d", width);
2070 }
2071 if (precision)
2072 fmt += sprintf(fmt, ".%d", precision);
2073 if (longflag)
2074 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002075 else if (longlongflag) {
2076 /* longlongflag should only ever be nonzero on machines with
2077 HAVE_LONG_LONG defined */
2078#ifdef HAVE_LONG_LONG
2079 char *f = PY_FORMAT_LONG_LONG;
2080 while (*f)
2081 *fmt++ = *f++;
2082#else
2083 /* we shouldn't ever get here */
2084 assert(0);
2085 *fmt++ = 'l';
2086#endif
2087 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002088 else if (size_tflag) {
2089 char *f = PY_FORMAT_SIZE_T;
2090 while (*f)
2091 *fmt++ = *f++;
2092 }
2093 *fmt++ = c;
2094 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002095}
2096
Victor Stinner96865452011-03-01 23:44:09 +00002097/* helper for PyUnicode_FromFormatV() */
2098
2099static const char*
2100parse_format_flags(const char *f,
2101 int *p_width, int *p_precision,
2102 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2103{
2104 int width, precision, longflag, longlongflag, size_tflag;
2105
2106 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2107 f++;
2108 width = 0;
2109 while (Py_ISDIGIT((unsigned)*f))
2110 width = (width*10) + *f++ - '0';
2111 precision = 0;
2112 if (*f == '.') {
2113 f++;
2114 while (Py_ISDIGIT((unsigned)*f))
2115 precision = (precision*10) + *f++ - '0';
2116 if (*f == '%') {
2117 /* "%.3%s" => f points to "3" */
2118 f--;
2119 }
2120 }
2121 if (*f == '\0') {
2122 /* bogus format "%.1" => go backward, f points to "1" */
2123 f--;
2124 }
2125 if (p_width != NULL)
2126 *p_width = width;
2127 if (p_precision != NULL)
2128 *p_precision = precision;
2129
2130 /* Handle %ld, %lu, %lld and %llu. */
2131 longflag = 0;
2132 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002133 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002134
2135 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002136 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002137 longflag = 1;
2138 ++f;
2139 }
2140#ifdef HAVE_LONG_LONG
2141 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002142 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002143 longlongflag = 1;
2144 f += 2;
2145 }
2146#endif
2147 }
2148 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002149 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002150 size_tflag = 1;
2151 ++f;
2152 }
2153 if (p_longflag != NULL)
2154 *p_longflag = longflag;
2155 if (p_longlongflag != NULL)
2156 *p_longlongflag = longlongflag;
2157 if (p_size_tflag != NULL)
2158 *p_size_tflag = size_tflag;
2159 return f;
2160}
2161
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002162/* maximum number of characters required for output of %ld. 21 characters
2163 allows for 64-bit integers (in decimal) and an optional sign. */
2164#define MAX_LONG_CHARS 21
2165/* maximum number of characters required for output of %lld.
2166 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2167 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2168#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2169
Walter Dörwaldd2034312007-05-18 16:29:38 +00002170PyObject *
2171PyUnicode_FromFormatV(const char *format, va_list vargs)
2172{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002173 va_list count;
2174 Py_ssize_t callcount = 0;
2175 PyObject **callresults = NULL;
2176 PyObject **callresult = NULL;
2177 Py_ssize_t n = 0;
2178 int width = 0;
2179 int precision = 0;
2180 int zeropad;
2181 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002182 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002183 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002184 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2186 Py_UCS4 argmaxchar;
2187 Py_ssize_t numbersize = 0;
2188 char *numberresults = NULL;
2189 char *numberresult = NULL;
2190 Py_ssize_t i;
2191 int kind;
2192 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002193
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002194 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002195 /* step 1: count the number of %S/%R/%A/%s format specifications
2196 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2197 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002199 * also estimate a upper bound for all the number formats in the string,
2200 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002202 for (f = format; *f; f++) {
2203 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002204 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2206 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2207 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2208 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002211#ifdef HAVE_LONG_LONG
2212 if (longlongflag) {
2213 if (width < MAX_LONG_LONG_CHARS)
2214 width = MAX_LONG_LONG_CHARS;
2215 }
2216 else
2217#endif
2218 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2219 including sign. Decimal takes the most space. This
2220 isn't enough for octal. If a width is specified we
2221 need more (which we allocate later). */
2222 if (width < MAX_LONG_CHARS)
2223 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224
2225 /* account for the size + '\0' to separate numbers
2226 inside of the numberresults buffer */
2227 numbersize += (width + 1);
2228 }
2229 }
2230 else if ((unsigned char)*f > 127) {
2231 PyErr_Format(PyExc_ValueError,
2232 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2233 "string, got a non-ASCII byte: 0x%02x",
2234 (unsigned char)*f);
2235 return NULL;
2236 }
2237 }
2238 /* step 2: allocate memory for the results of
2239 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2240 if (callcount) {
2241 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2242 if (!callresults) {
2243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246 callresult = callresults;
2247 }
2248 /* step 2.5: allocate memory for the results of formating numbers */
2249 if (numbersize) {
2250 numberresults = PyObject_Malloc(numbersize);
2251 if (!numberresults) {
2252 PyErr_NoMemory();
2253 goto fail;
2254 }
2255 numberresult = numberresults;
2256 }
2257
2258 /* step 3: format numbers and figure out how large a buffer we need */
2259 for (f = format; *f; f++) {
2260 if (*f == '%') {
2261 const char* p;
2262 int longflag;
2263 int longlongflag;
2264 int size_tflag;
2265 int numprinted;
2266
2267 p = f;
2268 zeropad = (f[1] == '0');
2269 f = parse_format_flags(f, &width, &precision,
2270 &longflag, &longlongflag, &size_tflag);
2271 switch (*f) {
2272 case 'c':
2273 {
2274 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002275 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 n++;
2277 break;
2278 }
2279 case '%':
2280 n++;
2281 break;
2282 case 'i':
2283 case 'd':
2284 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2285 width, precision, *f);
2286 if (longflag)
2287 numprinted = sprintf(numberresult, fmt,
2288 va_arg(count, long));
2289#ifdef HAVE_LONG_LONG
2290 else if (longlongflag)
2291 numprinted = sprintf(numberresult, fmt,
2292 va_arg(count, PY_LONG_LONG));
2293#endif
2294 else if (size_tflag)
2295 numprinted = sprintf(numberresult, fmt,
2296 va_arg(count, Py_ssize_t));
2297 else
2298 numprinted = sprintf(numberresult, fmt,
2299 va_arg(count, int));
2300 n += numprinted;
2301 /* advance by +1 to skip over the '\0' */
2302 numberresult += (numprinted + 1);
2303 assert(*(numberresult - 1) == '\0');
2304 assert(*(numberresult - 2) != '\0');
2305 assert(numprinted >= 0);
2306 assert(numberresult <= numberresults + numbersize);
2307 break;
2308 case 'u':
2309 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2310 width, precision, 'u');
2311 if (longflag)
2312 numprinted = sprintf(numberresult, fmt,
2313 va_arg(count, unsigned long));
2314#ifdef HAVE_LONG_LONG
2315 else if (longlongflag)
2316 numprinted = sprintf(numberresult, fmt,
2317 va_arg(count, unsigned PY_LONG_LONG));
2318#endif
2319 else if (size_tflag)
2320 numprinted = sprintf(numberresult, fmt,
2321 va_arg(count, size_t));
2322 else
2323 numprinted = sprintf(numberresult, fmt,
2324 va_arg(count, unsigned int));
2325 n += numprinted;
2326 numberresult += (numprinted + 1);
2327 assert(*(numberresult - 1) == '\0');
2328 assert(*(numberresult - 2) != '\0');
2329 assert(numprinted >= 0);
2330 assert(numberresult <= numberresults + numbersize);
2331 break;
2332 case 'x':
2333 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2334 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2335 n += numprinted;
2336 numberresult += (numprinted + 1);
2337 assert(*(numberresult - 1) == '\0');
2338 assert(*(numberresult - 2) != '\0');
2339 assert(numprinted >= 0);
2340 assert(numberresult <= numberresults + numbersize);
2341 break;
2342 case 'p':
2343 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2344 /* %p is ill-defined: ensure leading 0x. */
2345 if (numberresult[1] == 'X')
2346 numberresult[1] = 'x';
2347 else if (numberresult[1] != 'x') {
2348 memmove(numberresult + 2, numberresult,
2349 strlen(numberresult) + 1);
2350 numberresult[0] = '0';
2351 numberresult[1] = 'x';
2352 numprinted += 2;
2353 }
2354 n += numprinted;
2355 numberresult += (numprinted + 1);
2356 assert(*(numberresult - 1) == '\0');
2357 assert(*(numberresult - 2) != '\0');
2358 assert(numprinted >= 0);
2359 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002360 break;
2361 case 's':
2362 {
2363 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002364 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002365 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2366 if (!str)
2367 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002368 /* since PyUnicode_DecodeUTF8 returns already flexible
2369 unicode objects, there is no need to call ready on them */
2370 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002371 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002372 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002373 /* Remember the str and switch to the next slot */
2374 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002375 break;
2376 }
2377 case 'U':
2378 {
2379 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002380 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002381 if (PyUnicode_READY(obj) == -1)
2382 goto fail;
2383 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002384 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002385 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002386 break;
2387 }
2388 case 'V':
2389 {
2390 PyObject *obj = va_arg(count, PyObject *);
2391 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002392 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002393 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002394 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002395 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002396 if (PyUnicode_READY(obj) == -1)
2397 goto fail;
2398 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002399 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002400 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002401 *callresult++ = NULL;
2402 }
2403 else {
2404 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2405 if (!str_obj)
2406 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002407 if (PyUnicode_READY(str_obj)) {
2408 Py_DECREF(str_obj);
2409 goto fail;
2410 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002412 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002414 *callresult++ = str_obj;
2415 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002416 break;
2417 }
2418 case 'S':
2419 {
2420 PyObject *obj = va_arg(count, PyObject *);
2421 PyObject *str;
2422 assert(obj);
2423 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002424 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002425 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002427 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002429 /* Remember the str and switch to the next slot */
2430 *callresult++ = str;
2431 break;
2432 }
2433 case 'R':
2434 {
2435 PyObject *obj = va_arg(count, PyObject *);
2436 PyObject *repr;
2437 assert(obj);
2438 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002440 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002441 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002442 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002443 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002444 /* Remember the repr and switch to the next slot */
2445 *callresult++ = repr;
2446 break;
2447 }
2448 case 'A':
2449 {
2450 PyObject *obj = va_arg(count, PyObject *);
2451 PyObject *ascii;
2452 assert(obj);
2453 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002455 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002457 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002458 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002459 /* Remember the repr and switch to the next slot */
2460 *callresult++ = ascii;
2461 break;
2462 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002463 default:
2464 /* if we stumble upon an unknown
2465 formatting code, copy the rest of
2466 the format string to the output
2467 string. (we cannot just skip the
2468 code, since there's no way to know
2469 what's in the argument list) */
2470 n += strlen(p);
2471 goto expand;
2472 }
2473 } else
2474 n++;
2475 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002476 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002477 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 we don't have to resize the string.
2480 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002481 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002482 if (!string)
2483 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 kind = PyUnicode_KIND(string);
2485 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002491 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002492
2493 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002494 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2495 /* checking for == because the last argument could be a empty
2496 string, which causes i to point to end, the assert at the end of
2497 the loop */
2498 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002499
Benjamin Peterson14339b62009-01-31 16:36:08 +00002500 switch (*f) {
2501 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002502 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 const int ordinal = va_arg(vargs, int);
2504 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002505 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002506 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002507 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 case 'p':
2512 /* unused, since we already have the result */
2513 if (*f == 'p')
2514 (void) va_arg(vargs, void *);
2515 else
2516 (void) va_arg(vargs, int);
2517 /* extract the result from numberresults and append. */
2518 for (; *numberresult; ++i, ++numberresult)
2519 PyUnicode_WRITE(kind, data, i, *numberresult);
2520 /* skip over the separating '\0' */
2521 assert(*numberresult == '\0');
2522 numberresult++;
2523 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002524 break;
2525 case 's':
2526 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002527 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002529 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 size = PyUnicode_GET_LENGTH(*callresult);
2531 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002532 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002533 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002534 /* We're done with the unicode()/repr() => forget it */
2535 Py_DECREF(*callresult);
2536 /* switch to next unicode()/repr() result */
2537 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002538 break;
2539 }
2540 case 'U':
2541 {
2542 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002543 Py_ssize_t size;
2544 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2545 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002546 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002547 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 break;
2549 }
2550 case 'V':
2551 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002552 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002553 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002554 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002556 size = PyUnicode_GET_LENGTH(obj);
2557 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002558 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002560 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 size = PyUnicode_GET_LENGTH(*callresult);
2562 assert(PyUnicode_KIND(*callresult) <=
2563 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002564 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002565 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002566 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002568 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
2570 }
2571 case 'S':
2572 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002573 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002574 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002575 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 /* unused, since we already have the result */
2577 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002579 copy_characters(string, i, *callresult, 0, size);
2580 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002581 /* We're done with the unicode()/repr() => forget it */
2582 Py_DECREF(*callresult);
2583 /* switch to next unicode()/repr() result */
2584 ++callresult;
2585 break;
2586 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002587 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002588 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002589 break;
2590 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 for (; *p; ++p, ++i)
2592 PyUnicode_WRITE(kind, data, i, *p);
2593 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 goto end;
2595 }
Victor Stinner1205f272010-09-11 00:54:47 +00002596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 else {
2598 assert(i < PyUnicode_GET_LENGTH(string));
2599 PyUnicode_WRITE(kind, data, i++, *f);
2600 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002601 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002602 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002603
Benjamin Peterson29060642009-01-31 22:14:21 +00002604 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 if (callresults)
2606 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002607 if (numberresults)
2608 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002609 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002611 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 if (callresults) {
2613 PyObject **callresult2 = callresults;
2614 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002615 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002616 ++callresult2;
2617 }
2618 PyObject_Free(callresults);
2619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 if (numberresults)
2621 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002623}
2624
Walter Dörwaldd2034312007-05-18 16:29:38 +00002625PyObject *
2626PyUnicode_FromFormat(const char *format, ...)
2627{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002628 PyObject* ret;
2629 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002630
2631#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002633#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002634 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002635#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 ret = PyUnicode_FromFormatV(format, vargs);
2637 va_end(vargs);
2638 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002639}
2640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641#ifdef HAVE_WCHAR_H
2642
Victor Stinner5593d8a2010-10-02 11:11:27 +00002643/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2644 convert a Unicode object to a wide character string.
2645
Victor Stinnerd88d9832011-09-06 02:00:05 +02002646 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002647 character) required to convert the unicode object. Ignore size argument.
2648
Victor Stinnerd88d9832011-09-06 02:00:05 +02002649 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002650 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002651 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002652static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002653unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002654 wchar_t *w,
2655 Py_ssize_t size)
2656{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002657 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 const wchar_t *wstr;
2659
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002660 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 if (wstr == NULL)
2662 return -1;
2663
Victor Stinner5593d8a2010-10-02 11:11:27 +00002664 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002665 if (size > res)
2666 size = res + 1;
2667 else
2668 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002669 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002670 return res;
2671 }
2672 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002674}
2675
2676Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002677PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002678 wchar_t *w,
2679 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002680{
2681 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002682 PyErr_BadInternalCall();
2683 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002684 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002685 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002686}
2687
Victor Stinner137c34c2010-09-29 10:25:54 +00002688wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002689PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002690 Py_ssize_t *size)
2691{
2692 wchar_t* buffer;
2693 Py_ssize_t buflen;
2694
2695 if (unicode == NULL) {
2696 PyErr_BadInternalCall();
2697 return NULL;
2698 }
2699
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002700 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 if (buflen == -1)
2702 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002703 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002704 PyErr_NoMemory();
2705 return NULL;
2706 }
2707
Victor Stinner137c34c2010-09-29 10:25:54 +00002708 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2709 if (buffer == NULL) {
2710 PyErr_NoMemory();
2711 return NULL;
2712 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002713 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002714 if (buflen == -1)
2715 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002716 if (size != NULL)
2717 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002718 return buffer;
2719}
2720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002721#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002722
Alexander Belopolsky40018472011-02-26 01:02:56 +00002723PyObject *
2724PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002726 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002727 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002728 PyErr_SetString(PyExc_ValueError,
2729 "chr() arg not in range(0x110000)");
2730 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002731 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002733 if (ordinal < 256)
2734 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 v = PyUnicode_New(1, ordinal);
2737 if (v == NULL)
2738 return NULL;
2739 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002740 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002742}
2743
Alexander Belopolsky40018472011-02-26 01:02:56 +00002744PyObject *
2745PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002746{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002747 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002748 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002749 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002750 if (PyUnicode_READY(obj))
2751 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002752 Py_INCREF(obj);
2753 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002754 }
2755 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002756 /* For a Unicode subtype that's not a Unicode object,
2757 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002758 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002759 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002760 PyErr_Format(PyExc_TypeError,
2761 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002762 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002763 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002764}
2765
Alexander Belopolsky40018472011-02-26 01:02:56 +00002766PyObject *
2767PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002768 const char *encoding,
2769 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002770{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002771 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002772 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002773
Guido van Rossumd57fd912000-03-10 22:53:23 +00002774 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002775 PyErr_BadInternalCall();
2776 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002778
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002779 /* Decoding bytes objects is the most common case and should be fast */
2780 if (PyBytes_Check(obj)) {
2781 if (PyBytes_GET_SIZE(obj) == 0) {
2782 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002783 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002784 }
2785 else {
2786 v = PyUnicode_Decode(
2787 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2788 encoding, errors);
2789 }
2790 return v;
2791 }
2792
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002793 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002794 PyErr_SetString(PyExc_TypeError,
2795 "decoding str is not supported");
2796 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002797 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002798
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002799 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2800 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2801 PyErr_Format(PyExc_TypeError,
2802 "coercing to str: need bytes, bytearray "
2803 "or buffer-like object, %.80s found",
2804 Py_TYPE(obj)->tp_name);
2805 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002806 }
Tim Petersced69f82003-09-16 20:30:58 +00002807
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002808 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002809 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002810 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002811 }
Tim Petersced69f82003-09-16 20:30:58 +00002812 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002813 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002814
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002816 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002817}
2818
Victor Stinner600d3be2010-06-10 12:00:55 +00002819/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002820 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2821 1 on success. */
2822static int
2823normalize_encoding(const char *encoding,
2824 char *lower,
2825 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002826{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002827 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002828 char *l;
2829 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002830
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002831 if (encoding == NULL) {
2832 strcpy(lower, "utf-8");
2833 return 1;
2834 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002835 e = encoding;
2836 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002837 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002838 while (*e) {
2839 if (l == l_end)
2840 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002841 if (Py_ISUPPER(*e)) {
2842 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002843 }
2844 else if (*e == '_') {
2845 *l++ = '-';
2846 e++;
2847 }
2848 else {
2849 *l++ = *e++;
2850 }
2851 }
2852 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002853 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002854}
2855
Alexander Belopolsky40018472011-02-26 01:02:56 +00002856PyObject *
2857PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002858 Py_ssize_t size,
2859 const char *encoding,
2860 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002861{
2862 PyObject *buffer = NULL, *unicode;
2863 Py_buffer info;
2864 char lower[11]; /* Enough for any encoding shortcut */
2865
Fred Drakee4315f52000-05-09 19:53:39 +00002866 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002867 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002868 if ((strcmp(lower, "utf-8") == 0) ||
2869 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002870 return PyUnicode_DecodeUTF8(s, size, errors);
2871 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002872 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002873 (strcmp(lower, "iso-8859-1") == 0))
2874 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002875#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002876 else if (strcmp(lower, "mbcs") == 0)
2877 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002878#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002879 else if (strcmp(lower, "ascii") == 0)
2880 return PyUnicode_DecodeASCII(s, size, errors);
2881 else if (strcmp(lower, "utf-16") == 0)
2882 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2883 else if (strcmp(lower, "utf-32") == 0)
2884 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2885 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886
2887 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002888 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002889 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002890 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002891 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002892 if (buffer == NULL)
2893 goto onError;
2894 unicode = PyCodec_Decode(buffer, encoding, errors);
2895 if (unicode == NULL)
2896 goto onError;
2897 if (!PyUnicode_Check(unicode)) {
2898 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002899 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002900 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002901 Py_DECREF(unicode);
2902 goto onError;
2903 }
2904 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002905#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002906 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002907 Py_DECREF(unicode);
2908 return NULL;
2909 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002910#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002911 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002912 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002913
Benjamin Peterson29060642009-01-31 22:14:21 +00002914 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002915 Py_XDECREF(buffer);
2916 return NULL;
2917}
2918
Alexander Belopolsky40018472011-02-26 01:02:56 +00002919PyObject *
2920PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002921 const char *encoding,
2922 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002923{
2924 PyObject *v;
2925
2926 if (!PyUnicode_Check(unicode)) {
2927 PyErr_BadArgument();
2928 goto onError;
2929 }
2930
2931 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002932 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002933
2934 /* Decode via the codec registry */
2935 v = PyCodec_Decode(unicode, encoding, errors);
2936 if (v == NULL)
2937 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002938 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002939 return v;
2940
Benjamin Peterson29060642009-01-31 22:14:21 +00002941 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002942 return NULL;
2943}
2944
Alexander Belopolsky40018472011-02-26 01:02:56 +00002945PyObject *
2946PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002947 const char *encoding,
2948 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002949{
2950 PyObject *v;
2951
2952 if (!PyUnicode_Check(unicode)) {
2953 PyErr_BadArgument();
2954 goto onError;
2955 }
2956
2957 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002958 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002959
2960 /* Decode via the codec registry */
2961 v = PyCodec_Decode(unicode, encoding, errors);
2962 if (v == NULL)
2963 goto onError;
2964 if (!PyUnicode_Check(v)) {
2965 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002966 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002967 Py_TYPE(v)->tp_name);
2968 Py_DECREF(v);
2969 goto onError;
2970 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002971 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002972 return v;
2973
Benjamin Peterson29060642009-01-31 22:14:21 +00002974 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002975 return NULL;
2976}
2977
Alexander Belopolsky40018472011-02-26 01:02:56 +00002978PyObject *
2979PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002980 Py_ssize_t size,
2981 const char *encoding,
2982 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002983{
2984 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002985
Guido van Rossumd57fd912000-03-10 22:53:23 +00002986 unicode = PyUnicode_FromUnicode(s, size);
2987 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002988 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002989 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2990 Py_DECREF(unicode);
2991 return v;
2992}
2993
Alexander Belopolsky40018472011-02-26 01:02:56 +00002994PyObject *
2995PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002996 const char *encoding,
2997 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002998{
2999 PyObject *v;
3000
3001 if (!PyUnicode_Check(unicode)) {
3002 PyErr_BadArgument();
3003 goto onError;
3004 }
3005
3006 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003007 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003008
3009 /* Encode via the codec registry */
3010 v = PyCodec_Encode(unicode, encoding, errors);
3011 if (v == NULL)
3012 goto onError;
3013 return v;
3014
Benjamin Peterson29060642009-01-31 22:14:21 +00003015 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003016 return NULL;
3017}
3018
Victor Stinnerad158722010-10-27 00:25:46 +00003019PyObject *
3020PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003021{
Victor Stinner99b95382011-07-04 14:23:54 +02003022#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003023 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3024 PyUnicode_GET_SIZE(unicode),
3025 NULL);
3026#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003027 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003028#else
Victor Stinner793b5312011-04-27 00:24:21 +02003029 PyInterpreterState *interp = PyThreadState_GET()->interp;
3030 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3031 cannot use it to encode and decode filenames before it is loaded. Load
3032 the Python codec requires to encode at least its own filename. Use the C
3033 version of the locale codec until the codec registry is initialized and
3034 the Python codec is loaded.
3035
3036 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3037 cannot only rely on it: check also interp->fscodec_initialized for
3038 subinterpreters. */
3039 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003040 return PyUnicode_AsEncodedString(unicode,
3041 Py_FileSystemDefaultEncoding,
3042 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003043 }
3044 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003045 /* locale encoding with surrogateescape */
3046 wchar_t *wchar;
3047 char *bytes;
3048 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003049 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003050
3051 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3052 if (wchar == NULL)
3053 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003054 bytes = _Py_wchar2char(wchar, &error_pos);
3055 if (bytes == NULL) {
3056 if (error_pos != (size_t)-1) {
3057 char *errmsg = strerror(errno);
3058 PyObject *exc = NULL;
3059 if (errmsg == NULL)
3060 errmsg = "Py_wchar2char() failed";
3061 raise_encode_exception(&exc,
3062 "filesystemencoding",
3063 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3064 error_pos, error_pos+1,
3065 errmsg);
3066 Py_XDECREF(exc);
3067 }
3068 else
3069 PyErr_NoMemory();
3070 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003071 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003072 }
3073 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003074
3075 bytes_obj = PyBytes_FromString(bytes);
3076 PyMem_Free(bytes);
3077 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003078 }
Victor Stinnerad158722010-10-27 00:25:46 +00003079#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003080}
3081
Alexander Belopolsky40018472011-02-26 01:02:56 +00003082PyObject *
3083PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003084 const char *encoding,
3085 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086{
3087 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003088 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003089
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 if (!PyUnicode_Check(unicode)) {
3091 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003092 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003093 }
Fred Drakee4315f52000-05-09 19:53:39 +00003094
Fred Drakee4315f52000-05-09 19:53:39 +00003095 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003096 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003097 if ((strcmp(lower, "utf-8") == 0) ||
3098 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003099 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003100 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003101 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003102 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003103 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003104 }
Victor Stinner37296e82010-06-10 13:36:23 +00003105 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003106 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003107 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003108 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003109#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003110 else if (strcmp(lower, "mbcs") == 0)
3111 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3112 PyUnicode_GET_SIZE(unicode),
3113 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003114#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003115 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003116 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003117 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118
3119 /* Encode via the codec registry */
3120 v = PyCodec_Encode(unicode, encoding, errors);
3121 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 return NULL;
3123
3124 /* The normal path */
3125 if (PyBytes_Check(v))
3126 return v;
3127
3128 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003129 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003130 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003131 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003132
3133 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3134 "encoder %s returned bytearray instead of bytes",
3135 encoding);
3136 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003137 Py_DECREF(v);
3138 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003139 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003140
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003141 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3142 Py_DECREF(v);
3143 return b;
3144 }
3145
3146 PyErr_Format(PyExc_TypeError,
3147 "encoder did not return a bytes object (type=%.400s)",
3148 Py_TYPE(v)->tp_name);
3149 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003150 return NULL;
3151}
3152
Alexander Belopolsky40018472011-02-26 01:02:56 +00003153PyObject *
3154PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003155 const char *encoding,
3156 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003157{
3158 PyObject *v;
3159
3160 if (!PyUnicode_Check(unicode)) {
3161 PyErr_BadArgument();
3162 goto onError;
3163 }
3164
3165 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003166 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003167
3168 /* Encode via the codec registry */
3169 v = PyCodec_Encode(unicode, encoding, errors);
3170 if (v == NULL)
3171 goto onError;
3172 if (!PyUnicode_Check(v)) {
3173 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003174 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003175 Py_TYPE(v)->tp_name);
3176 Py_DECREF(v);
3177 goto onError;
3178 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003179 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003180
Benjamin Peterson29060642009-01-31 22:14:21 +00003181 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003182 return NULL;
3183}
3184
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003185PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003186PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003187 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003188 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3189}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003190
Christian Heimes5894ba72007-11-04 11:43:14 +00003191PyObject*
3192PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3193{
Victor Stinner99b95382011-07-04 14:23:54 +02003194#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003195 return PyUnicode_DecodeMBCS(s, size, NULL);
3196#elif defined(__APPLE__)
3197 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3198#else
Victor Stinner793b5312011-04-27 00:24:21 +02003199 PyInterpreterState *interp = PyThreadState_GET()->interp;
3200 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3201 cannot use it to encode and decode filenames before it is loaded. Load
3202 the Python codec requires to encode at least its own filename. Use the C
3203 version of the locale codec until the codec registry is initialized and
3204 the Python codec is loaded.
3205
3206 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3207 cannot only rely on it: check also interp->fscodec_initialized for
3208 subinterpreters. */
3209 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003210 return PyUnicode_Decode(s, size,
3211 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003212 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003213 }
3214 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003215 /* locale encoding with surrogateescape */
3216 wchar_t *wchar;
3217 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003218 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003219
3220 if (s[size] != '\0' || size != strlen(s)) {
3221 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3222 return NULL;
3223 }
3224
Victor Stinner168e1172010-10-16 23:16:16 +00003225 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003226 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003227 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003228
Victor Stinner168e1172010-10-16 23:16:16 +00003229 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003230 PyMem_Free(wchar);
3231 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003232 }
Victor Stinnerad158722010-10-27 00:25:46 +00003233#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003234}
3235
Martin v. Löwis011e8422009-05-05 04:43:17 +00003236
3237int
3238PyUnicode_FSConverter(PyObject* arg, void* addr)
3239{
3240 PyObject *output = NULL;
3241 Py_ssize_t size;
3242 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003243 if (arg == NULL) {
3244 Py_DECREF(*(PyObject**)addr);
3245 return 1;
3246 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003247 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003248 output = arg;
3249 Py_INCREF(output);
3250 }
3251 else {
3252 arg = PyUnicode_FromObject(arg);
3253 if (!arg)
3254 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003255 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003256 Py_DECREF(arg);
3257 if (!output)
3258 return 0;
3259 if (!PyBytes_Check(output)) {
3260 Py_DECREF(output);
3261 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3262 return 0;
3263 }
3264 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003265 size = PyBytes_GET_SIZE(output);
3266 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003267 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003268 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003269 Py_DECREF(output);
3270 return 0;
3271 }
3272 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003273 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003274}
3275
3276
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003277int
3278PyUnicode_FSDecoder(PyObject* arg, void* addr)
3279{
3280 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003281 if (arg == NULL) {
3282 Py_DECREF(*(PyObject**)addr);
3283 return 1;
3284 }
3285 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003286 if (PyUnicode_READY(arg))
3287 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003288 output = arg;
3289 Py_INCREF(output);
3290 }
3291 else {
3292 arg = PyBytes_FromObject(arg);
3293 if (!arg)
3294 return 0;
3295 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3296 PyBytes_GET_SIZE(arg));
3297 Py_DECREF(arg);
3298 if (!output)
3299 return 0;
3300 if (!PyUnicode_Check(output)) {
3301 Py_DECREF(output);
3302 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3303 return 0;
3304 }
3305 }
Victor Stinner065836e2011-10-27 01:56:33 +02003306 if (PyUnicode_READY(output) < 0) {
3307 Py_DECREF(output);
3308 return 0;
3309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003311 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003312 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3313 Py_DECREF(output);
3314 return 0;
3315 }
3316 *(PyObject**)addr = output;
3317 return Py_CLEANUP_SUPPORTED;
3318}
3319
3320
Martin v. Löwis5b222132007-06-10 09:51:05 +00003321char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003322PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003323{
Christian Heimesf3863112007-11-22 07:46:41 +00003324 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003325
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003326 if (!PyUnicode_Check(unicode)) {
3327 PyErr_BadArgument();
3328 return NULL;
3329 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003330 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003331 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003332
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003333 if (PyUnicode_UTF8(unicode) == NULL) {
3334 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003335 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3336 if (bytes == NULL)
3337 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003338 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3339 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003340 Py_DECREF(bytes);
3341 return NULL;
3342 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003343 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3344 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3345 PyBytes_AS_STRING(bytes),
3346 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003347 Py_DECREF(bytes);
3348 }
3349
3350 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003351 *psize = PyUnicode_UTF8_LENGTH(unicode);
3352 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003353}
3354
3355char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003357{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003358 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3359}
3360
3361#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003362static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003363#endif
3364
3365
3366Py_UNICODE *
3367PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3368{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003369 const unsigned char *one_byte;
3370#if SIZEOF_WCHAR_T == 4
3371 const Py_UCS2 *two_bytes;
3372#else
3373 const Py_UCS4 *four_bytes;
3374 const Py_UCS4 *ucs4_end;
3375 Py_ssize_t num_surrogates;
3376#endif
3377 wchar_t *w;
3378 wchar_t *wchar_end;
3379
3380 if (!PyUnicode_Check(unicode)) {
3381 PyErr_BadArgument();
3382 return NULL;
3383 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003384 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003385 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003386 assert(_PyUnicode_KIND(unicode) != 0);
3387 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388
3389#ifdef Py_DEBUG
3390 ++unicode_as_unicode_calls;
3391#endif
3392
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003393 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003395 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3396 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003397 num_surrogates = 0;
3398
3399 for (; four_bytes < ucs4_end; ++four_bytes) {
3400 if (*four_bytes > 0xFFFF)
3401 ++num_surrogates;
3402 }
3403
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003404 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3405 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3406 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003407 PyErr_NoMemory();
3408 return NULL;
3409 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003410 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003411
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003412 w = _PyUnicode_WSTR(unicode);
3413 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3414 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003415 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3416 if (*four_bytes > 0xFFFF) {
3417 /* encode surrogate pair in this case */
3418 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3419 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3420 }
3421 else
3422 *w = *four_bytes;
3423
3424 if (w > wchar_end) {
3425 assert(0 && "Miscalculated string end");
3426 }
3427 }
3428 *w = 0;
3429#else
3430 /* sizeof(wchar_t) == 4 */
3431 Py_FatalError("Impossible unicode object state, wstr and str "
3432 "should share memory already.");
3433 return NULL;
3434#endif
3435 }
3436 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003437 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3438 (_PyUnicode_LENGTH(unicode) + 1));
3439 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003440 PyErr_NoMemory();
3441 return NULL;
3442 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003443 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3444 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3445 w = _PyUnicode_WSTR(unicode);
3446 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003447
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003448 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3449 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003450 for (; w < wchar_end; ++one_byte, ++w)
3451 *w = *one_byte;
3452 /* null-terminate the wstr */
3453 *w = 0;
3454 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003455 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003456#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003457 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003458 for (; w < wchar_end; ++two_bytes, ++w)
3459 *w = *two_bytes;
3460 /* null-terminate the wstr */
3461 *w = 0;
3462#else
3463 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003464 PyObject_FREE(_PyUnicode_WSTR(unicode));
3465 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003466 Py_FatalError("Impossible unicode object state, wstr "
3467 "and str should share memory already.");
3468 return NULL;
3469#endif
3470 }
3471 else {
3472 assert(0 && "This should never happen.");
3473 }
3474 }
3475 }
3476 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003477 *size = PyUnicode_WSTR_LENGTH(unicode);
3478 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003479}
3480
Alexander Belopolsky40018472011-02-26 01:02:56 +00003481Py_UNICODE *
3482PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003484 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003485}
3486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003487
Alexander Belopolsky40018472011-02-26 01:02:56 +00003488Py_ssize_t
3489PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003490{
3491 if (!PyUnicode_Check(unicode)) {
3492 PyErr_BadArgument();
3493 goto onError;
3494 }
3495 return PyUnicode_GET_SIZE(unicode);
3496
Benjamin Peterson29060642009-01-31 22:14:21 +00003497 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 return -1;
3499}
3500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003501Py_ssize_t
3502PyUnicode_GetLength(PyObject *unicode)
3503{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003504 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003505 PyErr_BadArgument();
3506 return -1;
3507 }
3508
3509 return PyUnicode_GET_LENGTH(unicode);
3510}
3511
3512Py_UCS4
3513PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3514{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003515 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3516 PyErr_BadArgument();
3517 return (Py_UCS4)-1;
3518 }
3519 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3520 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003521 return (Py_UCS4)-1;
3522 }
3523 return PyUnicode_READ_CHAR(unicode, index);
3524}
3525
3526int
3527PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3528{
3529 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003530 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531 return -1;
3532 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003533 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3534 PyErr_SetString(PyExc_IndexError, "string index out of range");
3535 return -1;
3536 }
3537 if (_PyUnicode_Dirty(unicode))
3538 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003539 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3540 index, ch);
3541 return 0;
3542}
3543
Alexander Belopolsky40018472011-02-26 01:02:56 +00003544const char *
3545PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003546{
Victor Stinner42cb4622010-09-01 19:39:01 +00003547 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003548}
3549
Victor Stinner554f3f02010-06-16 23:33:54 +00003550/* create or adjust a UnicodeDecodeError */
3551static void
3552make_decode_exception(PyObject **exceptionObject,
3553 const char *encoding,
3554 const char *input, Py_ssize_t length,
3555 Py_ssize_t startpos, Py_ssize_t endpos,
3556 const char *reason)
3557{
3558 if (*exceptionObject == NULL) {
3559 *exceptionObject = PyUnicodeDecodeError_Create(
3560 encoding, input, length, startpos, endpos, reason);
3561 }
3562 else {
3563 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3564 goto onError;
3565 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3566 goto onError;
3567 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3568 goto onError;
3569 }
3570 return;
3571
3572onError:
3573 Py_DECREF(*exceptionObject);
3574 *exceptionObject = NULL;
3575}
3576
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003577/* error handling callback helper:
3578 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003579 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003580 and adjust various state variables.
3581 return 0 on success, -1 on error
3582*/
3583
Alexander Belopolsky40018472011-02-26 01:02:56 +00003584static int
3585unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003586 const char *encoding, const char *reason,
3587 const char **input, const char **inend, Py_ssize_t *startinpos,
3588 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3589 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003590{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003591 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003592
3593 PyObject *restuple = NULL;
3594 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003595 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003596 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003597 Py_ssize_t requiredsize;
3598 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003599 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003600 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003601 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003602 int res = -1;
3603
3604 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003605 *errorHandler = PyCodec_LookupError(errors);
3606 if (*errorHandler == NULL)
3607 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003608 }
3609
Victor Stinner554f3f02010-06-16 23:33:54 +00003610 make_decode_exception(exceptionObject,
3611 encoding,
3612 *input, *inend - *input,
3613 *startinpos, *endinpos,
3614 reason);
3615 if (*exceptionObject == NULL)
3616 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003617
3618 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3619 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003620 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003621 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003622 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003623 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003624 }
3625 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003626 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003627
3628 /* Copy back the bytes variables, which might have been modified by the
3629 callback */
3630 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3631 if (!inputobj)
3632 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003633 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003634 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003635 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003636 *input = PyBytes_AS_STRING(inputobj);
3637 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003638 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003639 /* we can DECREF safely, as the exception has another reference,
3640 so the object won't go away. */
3641 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003642
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003644 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003645 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3647 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003648 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003649
3650 /* need more space? (at least enough for what we
3651 have+the replacement+the rest of the string (starting
3652 at the new input position), so we won't have to check space
3653 when there are no errors in the rest of the string) */
3654 repptr = PyUnicode_AS_UNICODE(repunicode);
3655 repsize = PyUnicode_GET_SIZE(repunicode);
3656 requiredsize = *outpos + repsize + insize-newpos;
3657 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003658 if (requiredsize<2*outsize)
3659 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003660 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003661 goto onError;
3662 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003663 }
3664 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003665 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003666 Py_UNICODE_COPY(*outptr, repptr, repsize);
3667 *outptr += repsize;
3668 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003670 /* we made it! */
3671 res = 0;
3672
Benjamin Peterson29060642009-01-31 22:14:21 +00003673 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003674 Py_XDECREF(restuple);
3675 return res;
3676}
3677
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003678/* --- UTF-7 Codec -------------------------------------------------------- */
3679
Antoine Pitrou244651a2009-05-04 18:56:13 +00003680/* See RFC2152 for details. We encode conservatively and decode liberally. */
3681
3682/* Three simple macros defining base-64. */
3683
3684/* Is c a base-64 character? */
3685
3686#define IS_BASE64(c) \
3687 (((c) >= 'A' && (c) <= 'Z') || \
3688 ((c) >= 'a' && (c) <= 'z') || \
3689 ((c) >= '0' && (c) <= '9') || \
3690 (c) == '+' || (c) == '/')
3691
3692/* given that c is a base-64 character, what is its base-64 value? */
3693
3694#define FROM_BASE64(c) \
3695 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3696 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3697 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3698 (c) == '+' ? 62 : 63)
3699
3700/* What is the base-64 character of the bottom 6 bits of n? */
3701
3702#define TO_BASE64(n) \
3703 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3704
3705/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3706 * decoded as itself. We are permissive on decoding; the only ASCII
3707 * byte not decoding to itself is the + which begins a base64
3708 * string. */
3709
3710#define DECODE_DIRECT(c) \
3711 ((c) <= 127 && (c) != '+')
3712
3713/* The UTF-7 encoder treats ASCII characters differently according to
3714 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3715 * the above). See RFC2152. This array identifies these different
3716 * sets:
3717 * 0 : "Set D"
3718 * alphanumeric and '(),-./:?
3719 * 1 : "Set O"
3720 * !"#$%&*;<=>@[]^_`{|}
3721 * 2 : "whitespace"
3722 * ht nl cr sp
3723 * 3 : special (must be base64 encoded)
3724 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3725 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003726
Tim Petersced69f82003-09-16 20:30:58 +00003727static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003728char utf7_category[128] = {
3729/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3730 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3731/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3732 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3733/* sp ! " # $ % & ' ( ) * + , - . / */
3734 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3735/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3736 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3737/* @ A B C D E F G H I J K L M N O */
3738 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3739/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3740 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3741/* ` a b c d e f g h i j k l m n o */
3742 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3743/* p q r s t u v w x y z { | } ~ del */
3744 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003745};
3746
Antoine Pitrou244651a2009-05-04 18:56:13 +00003747/* ENCODE_DIRECT: this character should be encoded as itself. The
3748 * answer depends on whether we are encoding set O as itself, and also
3749 * on whether we are encoding whitespace as itself. RFC2152 makes it
3750 * clear that the answers to these questions vary between
3751 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003752
Antoine Pitrou244651a2009-05-04 18:56:13 +00003753#define ENCODE_DIRECT(c, directO, directWS) \
3754 ((c) < 128 && (c) > 0 && \
3755 ((utf7_category[(c)] == 0) || \
3756 (directWS && (utf7_category[(c)] == 2)) || \
3757 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003758
Alexander Belopolsky40018472011-02-26 01:02:56 +00003759PyObject *
3760PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003761 Py_ssize_t size,
3762 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003763{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003764 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3765}
3766
Antoine Pitrou244651a2009-05-04 18:56:13 +00003767/* The decoder. The only state we preserve is our read position,
3768 * i.e. how many characters we have consumed. So if we end in the
3769 * middle of a shift sequence we have to back off the read position
3770 * and the output to the beginning of the sequence, otherwise we lose
3771 * all the shift state (seen bits, number of bits seen, high
3772 * surrogate). */
3773
Alexander Belopolsky40018472011-02-26 01:02:56 +00003774PyObject *
3775PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003776 Py_ssize_t size,
3777 const char *errors,
3778 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003779{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003780 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003781 Py_ssize_t startinpos;
3782 Py_ssize_t endinpos;
3783 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003784 const char *e;
3785 PyUnicodeObject *unicode;
3786 Py_UNICODE *p;
3787 const char *errmsg = "";
3788 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003789 Py_UNICODE *shiftOutStart;
3790 unsigned int base64bits = 0;
3791 unsigned long base64buffer = 0;
3792 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003793 PyObject *errorHandler = NULL;
3794 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003795
3796 unicode = _PyUnicode_New(size);
3797 if (!unicode)
3798 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003799 if (size == 0) {
3800 if (consumed)
3801 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003802 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003803 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003806 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003807 e = s + size;
3808
3809 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003810 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003811 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003812 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003813
Antoine Pitrou244651a2009-05-04 18:56:13 +00003814 if (inShift) { /* in a base-64 section */
3815 if (IS_BASE64(ch)) { /* consume a base-64 character */
3816 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3817 base64bits += 6;
3818 s++;
3819 if (base64bits >= 16) {
3820 /* we have enough bits for a UTF-16 value */
3821 Py_UNICODE outCh = (Py_UNICODE)
3822 (base64buffer >> (base64bits-16));
3823 base64bits -= 16;
3824 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3825 if (surrogate) {
3826 /* expecting a second surrogate */
3827 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3828#ifdef Py_UNICODE_WIDE
3829 *p++ = (((surrogate & 0x3FF)<<10)
3830 | (outCh & 0x3FF)) + 0x10000;
3831#else
3832 *p++ = surrogate;
3833 *p++ = outCh;
3834#endif
3835 surrogate = 0;
3836 }
3837 else {
3838 surrogate = 0;
3839 errmsg = "second surrogate missing";
3840 goto utf7Error;
3841 }
3842 }
3843 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3844 /* first surrogate */
3845 surrogate = outCh;
3846 }
3847 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3848 errmsg = "unexpected second surrogate";
3849 goto utf7Error;
3850 }
3851 else {
3852 *p++ = outCh;
3853 }
3854 }
3855 }
3856 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003857 inShift = 0;
3858 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003859 if (surrogate) {
3860 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003861 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003863 if (base64bits > 0) { /* left-over bits */
3864 if (base64bits >= 6) {
3865 /* We've seen at least one base-64 character */
3866 errmsg = "partial character in shift sequence";
3867 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003869 else {
3870 /* Some bits remain; they should be zero */
3871 if (base64buffer != 0) {
3872 errmsg = "non-zero padding bits in shift sequence";
3873 goto utf7Error;
3874 }
3875 }
3876 }
3877 if (ch != '-') {
3878 /* '-' is absorbed; other terminating
3879 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003880 *p++ = ch;
3881 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003882 }
3883 }
3884 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003885 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 s++; /* consume '+' */
3887 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003888 s++;
3889 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003890 }
3891 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003892 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003893 shiftOutStart = p;
3894 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003895 }
3896 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003898 *p++ = ch;
3899 s++;
3900 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003901 else {
3902 startinpos = s-starts;
3903 s++;
3904 errmsg = "unexpected special character";
3905 goto utf7Error;
3906 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003907 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003908utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003909 outpos = p-PyUnicode_AS_UNICODE(unicode);
3910 endinpos = s-starts;
3911 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003912 errors, &errorHandler,
3913 "utf7", errmsg,
3914 &starts, &e, &startinpos, &endinpos, &exc, &s,
3915 &unicode, &outpos, &p))
3916 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003917 }
3918
Antoine Pitrou244651a2009-05-04 18:56:13 +00003919 /* end of string */
3920
3921 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3922 /* if we're in an inconsistent state, that's an error */
3923 if (surrogate ||
3924 (base64bits >= 6) ||
3925 (base64bits > 0 && base64buffer != 0)) {
3926 outpos = p-PyUnicode_AS_UNICODE(unicode);
3927 endinpos = size;
3928 if (unicode_decode_call_errorhandler(
3929 errors, &errorHandler,
3930 "utf7", "unterminated shift sequence",
3931 &starts, &e, &startinpos, &endinpos, &exc, &s,
3932 &unicode, &outpos, &p))
3933 goto onError;
3934 if (s < e)
3935 goto restart;
3936 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003937 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938
3939 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003940 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003941 if (inShift) {
3942 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003943 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003944 }
3945 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003946 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003947 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003948 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003949
Victor Stinnerfe226c02011-10-03 03:52:20 +02003950 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003951 goto onError;
3952
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003953 Py_XDECREF(errorHandler);
3954 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003955#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003956 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003957 Py_DECREF(unicode);
3958 return NULL;
3959 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003960#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003961 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003962 return (PyObject *)unicode;
3963
Benjamin Peterson29060642009-01-31 22:14:21 +00003964 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003965 Py_XDECREF(errorHandler);
3966 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003967 Py_DECREF(unicode);
3968 return NULL;
3969}
3970
3971
Alexander Belopolsky40018472011-02-26 01:02:56 +00003972PyObject *
3973PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003974 Py_ssize_t size,
3975 int base64SetO,
3976 int base64WhiteSpace,
3977 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003978{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003979 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003980 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003981 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003982 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003983 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003984 unsigned int base64bits = 0;
3985 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003986 char * out;
3987 char * start;
3988
3989 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003991
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003992 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003993 return PyErr_NoMemory();
3994
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003996 if (v == NULL)
3997 return NULL;
3998
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003999 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004000 for (;i < size; ++i) {
4001 Py_UNICODE ch = s[i];
4002
Antoine Pitrou244651a2009-05-04 18:56:13 +00004003 if (inShift) {
4004 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4005 /* shifting out */
4006 if (base64bits) { /* output remaining bits */
4007 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4008 base64buffer = 0;
4009 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004010 }
4011 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004012 /* Characters not in the BASE64 set implicitly unshift the sequence
4013 so no '-' is required, except if the character is itself a '-' */
4014 if (IS_BASE64(ch) || ch == '-') {
4015 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004016 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004017 *out++ = (char) ch;
4018 }
4019 else {
4020 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004021 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004022 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004023 else { /* not in a shift sequence */
4024 if (ch == '+') {
4025 *out++ = '+';
4026 *out++ = '-';
4027 }
4028 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4029 *out++ = (char) ch;
4030 }
4031 else {
4032 *out++ = '+';
4033 inShift = 1;
4034 goto encode_char;
4035 }
4036 }
4037 continue;
4038encode_char:
4039#ifdef Py_UNICODE_WIDE
4040 if (ch >= 0x10000) {
4041 /* code first surrogate */
4042 base64bits += 16;
4043 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4044 while (base64bits >= 6) {
4045 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4046 base64bits -= 6;
4047 }
4048 /* prepare second surrogate */
4049 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4050 }
4051#endif
4052 base64bits += 16;
4053 base64buffer = (base64buffer << 16) | ch;
4054 while (base64bits >= 6) {
4055 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4056 base64bits -= 6;
4057 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004058 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004059 if (base64bits)
4060 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4061 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004062 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004063 if (_PyBytes_Resize(&v, out - start) < 0)
4064 return NULL;
4065 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004066}
4067
Antoine Pitrou244651a2009-05-04 18:56:13 +00004068#undef IS_BASE64
4069#undef FROM_BASE64
4070#undef TO_BASE64
4071#undef DECODE_DIRECT
4072#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004073
Guido van Rossumd57fd912000-03-10 22:53:23 +00004074/* --- UTF-8 Codec -------------------------------------------------------- */
4075
Tim Petersced69f82003-09-16 20:30:58 +00004076static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004077char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004078 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4079 illegal prefix. See RFC 3629 for details */
4080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004082 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004083 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4084 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4085 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4086 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004087 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4088 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 +00004089 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4090 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004091 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4092 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4093 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4094 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4095 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 +00004096};
4097
Alexander Belopolsky40018472011-02-26 01:02:56 +00004098PyObject *
4099PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004100 Py_ssize_t size,
4101 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004102{
Walter Dörwald69652032004-09-07 20:24:22 +00004103 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4104}
4105
Antoine Pitrouab868312009-01-10 15:40:25 +00004106/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4107#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4108
4109/* Mask to quickly check whether a C 'long' contains a
4110 non-ASCII, UTF8-encoded char. */
4111#if (SIZEOF_LONG == 8)
4112# define ASCII_CHAR_MASK 0x8080808080808080L
4113#elif (SIZEOF_LONG == 4)
4114# define ASCII_CHAR_MASK 0x80808080L
4115#else
4116# error C 'long' size should be either 4 or 8!
4117#endif
4118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004119/* Scans a UTF-8 string and returns the maximum character to be expected,
4120 the size of the decoded unicode string and if any major errors were
4121 encountered.
4122
4123 This function does check basic UTF-8 sanity, it does however NOT CHECK
4124 if the string contains surrogates, and if all continuation bytes are
4125 within the correct ranges, these checks are performed in
4126 PyUnicode_DecodeUTF8Stateful.
4127
4128 If it sets has_errors to 1, it means the value of unicode_size and max_char
4129 will be bogus and you should not rely on useful information in them.
4130 */
4131static Py_UCS4
4132utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4133 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4134 int *has_errors)
4135{
4136 Py_ssize_t n;
4137 Py_ssize_t char_count = 0;
4138 Py_UCS4 max_char = 127, new_max;
4139 Py_UCS4 upper_bound;
4140 const unsigned char *p = (const unsigned char *)s;
4141 const unsigned char *end = p + string_size;
4142 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4143 int err = 0;
4144
4145 for (; p < end && !err; ++p, ++char_count) {
4146 /* Only check value if it's not a ASCII char... */
4147 if (*p < 0x80) {
4148 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4149 an explanation. */
4150 if (!((size_t) p & LONG_PTR_MASK)) {
4151 /* Help register allocation */
4152 register const unsigned char *_p = p;
4153 while (_p < aligned_end) {
4154 unsigned long value = *(unsigned long *) _p;
4155 if (value & ASCII_CHAR_MASK)
4156 break;
4157 _p += SIZEOF_LONG;
4158 char_count += SIZEOF_LONG;
4159 }
4160 p = _p;
4161 if (p == end)
4162 break;
4163 }
4164 }
4165 if (*p >= 0x80) {
4166 n = utf8_code_length[*p];
4167 new_max = max_char;
4168 switch (n) {
4169 /* invalid start byte */
4170 case 0:
4171 err = 1;
4172 break;
4173 case 2:
4174 /* Code points between 0x00FF and 0x07FF inclusive.
4175 Approximate the upper bound of the code point,
4176 if this flips over 255 we can be sure it will be more
4177 than 255 and the string will need 2 bytes per code coint,
4178 if it stays under or equal to 255, we can be sure 1 byte
4179 is enough.
4180 ((*p & 0b00011111) << 6) | 0b00111111 */
4181 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4182 if (max_char < upper_bound)
4183 new_max = upper_bound;
4184 /* Ensure we track at least that we left ASCII space. */
4185 if (new_max < 128)
4186 new_max = 128;
4187 break;
4188 case 3:
4189 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4190 always > 255 and <= 65535 and will always need 2 bytes. */
4191 if (max_char < 65535)
4192 new_max = 65535;
4193 break;
4194 case 4:
4195 /* Code point will be above 0xFFFF for sure in this case. */
4196 new_max = 65537;
4197 break;
4198 /* Internal error, this should be caught by the first if */
4199 case 1:
4200 default:
4201 assert(0 && "Impossible case in utf8_max_char_and_size");
4202 err = 1;
4203 }
4204 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004205 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004206 --n;
4207 /* Check if the follow up chars are all valid continuation bytes */
4208 if (n >= 1) {
4209 const unsigned char *cont;
4210 if ((p + n) >= end) {
4211 if (consumed == 0)
4212 /* incomplete data, non-incremental decoding */
4213 err = 1;
4214 break;
4215 }
4216 for (cont = p + 1; cont < (p + n); ++cont) {
4217 if ((*cont & 0xc0) != 0x80) {
4218 err = 1;
4219 break;
4220 }
4221 }
4222 p += n;
4223 }
4224 else
4225 err = 1;
4226 max_char = new_max;
4227 }
4228 }
4229
4230 if (unicode_size)
4231 *unicode_size = char_count;
4232 if (has_errors)
4233 *has_errors = err;
4234 return max_char;
4235}
4236
4237/* Similar to PyUnicode_WRITE but can also write into wstr field
4238 of the legacy unicode representation */
4239#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4240 do { \
4241 const int k_ = (kind); \
4242 if (k_ == PyUnicode_WCHAR_KIND) \
4243 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4244 else if (k_ == PyUnicode_1BYTE_KIND) \
4245 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4246 else if (k_ == PyUnicode_2BYTE_KIND) \
4247 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4248 else \
4249 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4250 } while (0)
4251
Alexander Belopolsky40018472011-02-26 01:02:56 +00004252PyObject *
4253PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004254 Py_ssize_t size,
4255 const char *errors,
4256 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004257{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004258 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004259 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004260 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004261 Py_ssize_t startinpos;
4262 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004263 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004264 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004265 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266 PyObject *errorHandler = NULL;
4267 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004268 Py_UCS4 maxchar = 0;
4269 Py_ssize_t unicode_size;
4270 Py_ssize_t i;
4271 int kind;
4272 void *data;
4273 int has_errors;
4274 Py_UNICODE *error_outptr;
4275#if SIZEOF_WCHAR_T == 2
4276 Py_ssize_t wchar_offset = 0;
4277#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004278
Walter Dörwald69652032004-09-07 20:24:22 +00004279 if (size == 0) {
4280 if (consumed)
4281 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004282 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004283 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004284 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4285 consumed, &has_errors);
4286 if (has_errors) {
4287 unicode = _PyUnicode_New(size);
4288 if (!unicode)
4289 return NULL;
4290 kind = PyUnicode_WCHAR_KIND;
4291 data = PyUnicode_AS_UNICODE(unicode);
4292 assert(data != NULL);
4293 }
4294 else {
4295 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4296 if (!unicode)
4297 return NULL;
4298 /* When the string is ASCII only, just use memcpy and return.
4299 unicode_size may be != size if there is an incomplete UTF-8
4300 sequence at the end of the ASCII block. */
4301 if (maxchar < 128 && size == unicode_size) {
4302 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4303 return (PyObject *)unicode;
4304 }
4305 kind = PyUnicode_KIND(unicode);
4306 data = PyUnicode_DATA(unicode);
4307 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004309 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004310 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004311 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004312
4313 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004314 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004315
4316 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004317 /* Fast path for runs of ASCII characters. Given that common UTF-8
4318 input will consist of an overwhelming majority of ASCII
4319 characters, we try to optimize for this case by checking
4320 as many characters as a C 'long' can contain.
4321 First, check if we can do an aligned read, as most CPUs have
4322 a penalty for unaligned reads.
4323 */
4324 if (!((size_t) s & LONG_PTR_MASK)) {
4325 /* Help register allocation */
4326 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004327 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004328 while (_s < aligned_end) {
4329 /* Read a whole long at a time (either 4 or 8 bytes),
4330 and do a fast unrolled copy if it only contains ASCII
4331 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004332 unsigned long value = *(unsigned long *) _s;
4333 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004334 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004335 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4336 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4337 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4338 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004339#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004340 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4341 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4342 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4343 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004344#endif
4345 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004346 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004347 }
4348 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004349 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004350 if (s == e)
4351 break;
4352 ch = (unsigned char)*s;
4353 }
4354 }
4355
4356 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004357 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004358 s++;
4359 continue;
4360 }
4361
4362 n = utf8_code_length[ch];
4363
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004364 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004365 if (consumed)
4366 break;
4367 else {
4368 errmsg = "unexpected end of data";
4369 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004370 endinpos = startinpos+1;
4371 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4372 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004373 goto utf8Error;
4374 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004375 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004376
4377 switch (n) {
4378
4379 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004380 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004381 startinpos = s-starts;
4382 endinpos = startinpos+1;
4383 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004384
4385 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004386 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004387 startinpos = s-starts;
4388 endinpos = startinpos+1;
4389 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004390
4391 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004392 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004393 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004395 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004396 goto utf8Error;
4397 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004398 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004399 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004400 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004401 break;
4402
4403 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004404 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4405 will result in surrogates in range d800-dfff. Surrogates are
4406 not valid UTF-8 so they are rejected.
4407 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4408 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004409 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004410 (s[2] & 0xc0) != 0x80 ||
4411 ((unsigned char)s[0] == 0xE0 &&
4412 (unsigned char)s[1] < 0xA0) ||
4413 ((unsigned char)s[0] == 0xED &&
4414 (unsigned char)s[1] > 0x9F)) {
4415 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004416 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004417 endinpos = startinpos + 1;
4418
4419 /* if s[1] first two bits are 1 and 0, then the invalid
4420 continuation byte is s[2], so increment endinpos by 1,
4421 if not, s[1] is invalid and endinpos doesn't need to
4422 be incremented. */
4423 if ((s[1] & 0xC0) == 0x80)
4424 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004425 goto utf8Error;
4426 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004427 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004428 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004429 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004430 break;
4431
4432 case 4:
4433 if ((s[1] & 0xc0) != 0x80 ||
4434 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004435 (s[3] & 0xc0) != 0x80 ||
4436 ((unsigned char)s[0] == 0xF0 &&
4437 (unsigned char)s[1] < 0x90) ||
4438 ((unsigned char)s[0] == 0xF4 &&
4439 (unsigned char)s[1] > 0x8F)) {
4440 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004442 endinpos = startinpos + 1;
4443 if ((s[1] & 0xC0) == 0x80) {
4444 endinpos++;
4445 if ((s[2] & 0xC0) == 0x80)
4446 endinpos++;
4447 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 goto utf8Error;
4449 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004450 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004451 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4452 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004454 /* If the string is flexible or we have native UCS-4, write
4455 directly.. */
4456 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4457 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004459 else {
4460 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004462 /* translate from 10000..10FFFF to 0..FFFF */
4463 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004465 /* high surrogate = top 10 bits added to D800 */
4466 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4467 (Py_UNICODE)(0xD800 + (ch >> 10)));
4468
4469 /* low surrogate = bottom 10 bits added to DC00 */
4470 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4471 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4472 }
4473#if SIZEOF_WCHAR_T == 2
4474 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004475#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004477 }
4478 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004479 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004480
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004482 /* If this is not yet a resizable string, make it one.. */
4483 if (kind != PyUnicode_WCHAR_KIND) {
4484 const Py_UNICODE *u;
4485 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4486 if (!new_unicode)
4487 goto onError;
4488 u = PyUnicode_AsUnicode((PyObject *)unicode);
4489 if (!u)
4490 goto onError;
4491#if SIZEOF_WCHAR_T == 2
4492 i += wchar_offset;
4493#endif
4494 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4495 Py_DECREF(unicode);
4496 unicode = new_unicode;
4497 kind = 0;
4498 data = PyUnicode_AS_UNICODE(new_unicode);
4499 assert(data != NULL);
4500 }
4501 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004502 if (unicode_decode_call_errorhandler(
4503 errors, &errorHandler,
4504 "utf8", errmsg,
4505 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004506 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004507 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 /* Update data because unicode_decode_call_errorhandler might have
4509 re-created or resized the unicode object. */
4510 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004513 /* Ensure the unicode_size calculation above was correct: */
4514 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4515
Walter Dörwald69652032004-09-07 20:24:22 +00004516 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004517 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004519 /* Adjust length and ready string when it contained errors and
4520 is of the old resizable kind. */
4521 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004522 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004523 goto onError;
4524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004525
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004526 Py_XDECREF(errorHandler);
4527 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004528#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004529 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004530 Py_DECREF(unicode);
4531 return NULL;
4532 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004533#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004534 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535 return (PyObject *)unicode;
4536
Benjamin Peterson29060642009-01-31 22:14:21 +00004537 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004538 Py_XDECREF(errorHandler);
4539 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004540 Py_DECREF(unicode);
4541 return NULL;
4542}
4543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004544#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004545
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004546#ifdef __APPLE__
4547
4548/* Simplified UTF-8 decoder using surrogateescape error handler,
4549 used to decode the command line arguments on Mac OS X. */
4550
4551wchar_t*
4552_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4553{
4554 int n;
4555 const char *e;
4556 wchar_t *unicode, *p;
4557
4558 /* Note: size will always be longer than the resulting Unicode
4559 character count */
4560 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4561 PyErr_NoMemory();
4562 return NULL;
4563 }
4564 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4565 if (!unicode)
4566 return NULL;
4567
4568 /* Unpack UTF-8 encoded data */
4569 p = unicode;
4570 e = s + size;
4571 while (s < e) {
4572 Py_UCS4 ch = (unsigned char)*s;
4573
4574 if (ch < 0x80) {
4575 *p++ = (wchar_t)ch;
4576 s++;
4577 continue;
4578 }
4579
4580 n = utf8_code_length[ch];
4581 if (s + n > e) {
4582 goto surrogateescape;
4583 }
4584
4585 switch (n) {
4586 case 0:
4587 case 1:
4588 goto surrogateescape;
4589
4590 case 2:
4591 if ((s[1] & 0xc0) != 0x80)
4592 goto surrogateescape;
4593 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4594 assert ((ch > 0x007F) && (ch <= 0x07FF));
4595 *p++ = (wchar_t)ch;
4596 break;
4597
4598 case 3:
4599 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4600 will result in surrogates in range d800-dfff. Surrogates are
4601 not valid UTF-8 so they are rejected.
4602 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4603 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4604 if ((s[1] & 0xc0) != 0x80 ||
4605 (s[2] & 0xc0) != 0x80 ||
4606 ((unsigned char)s[0] == 0xE0 &&
4607 (unsigned char)s[1] < 0xA0) ||
4608 ((unsigned char)s[0] == 0xED &&
4609 (unsigned char)s[1] > 0x9F)) {
4610
4611 goto surrogateescape;
4612 }
4613 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4614 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004615 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004616 break;
4617
4618 case 4:
4619 if ((s[1] & 0xc0) != 0x80 ||
4620 (s[2] & 0xc0) != 0x80 ||
4621 (s[3] & 0xc0) != 0x80 ||
4622 ((unsigned char)s[0] == 0xF0 &&
4623 (unsigned char)s[1] < 0x90) ||
4624 ((unsigned char)s[0] == 0xF4 &&
4625 (unsigned char)s[1] > 0x8F)) {
4626 goto surrogateescape;
4627 }
4628 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4629 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4630 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4631
4632#if SIZEOF_WCHAR_T == 4
4633 *p++ = (wchar_t)ch;
4634#else
4635 /* compute and append the two surrogates: */
4636
4637 /* translate from 10000..10FFFF to 0..FFFF */
4638 ch -= 0x10000;
4639
4640 /* high surrogate = top 10 bits added to D800 */
4641 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4642
4643 /* low surrogate = bottom 10 bits added to DC00 */
4644 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4645#endif
4646 break;
4647 }
4648 s += n;
4649 continue;
4650
4651 surrogateescape:
4652 *p++ = 0xDC00 + ch;
4653 s++;
4654 }
4655 *p = L'\0';
4656 return unicode;
4657}
4658
4659#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004661/* Primary internal function which creates utf8 encoded bytes objects.
4662
4663 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004664 and allocate exactly as much space needed at the end. Else allocate the
4665 maximum possible needed (4 result bytes per Unicode character), and return
4666 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004667*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004668PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004669_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004670{
Tim Peters602f7402002-04-27 18:03:26 +00004671#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004672
Guido van Rossum98297ee2007-11-06 21:34:58 +00004673 Py_ssize_t i; /* index into s of next input byte */
4674 PyObject *result; /* result string object */
4675 char *p; /* next free byte in output buffer */
4676 Py_ssize_t nallocated; /* number of result bytes allocated */
4677 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004678 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004679 PyObject *errorHandler = NULL;
4680 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004681 int kind;
4682 void *data;
4683 Py_ssize_t size;
4684 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4685#if SIZEOF_WCHAR_T == 2
4686 Py_ssize_t wchar_offset = 0;
4687#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004689 if (!PyUnicode_Check(unicode)) {
4690 PyErr_BadArgument();
4691 return NULL;
4692 }
4693
4694 if (PyUnicode_READY(unicode) == -1)
4695 return NULL;
4696
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004697 if (PyUnicode_UTF8(unicode))
4698 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4699 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004700
4701 kind = PyUnicode_KIND(unicode);
4702 data = PyUnicode_DATA(unicode);
4703 size = PyUnicode_GET_LENGTH(unicode);
4704
Tim Peters602f7402002-04-27 18:03:26 +00004705 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004706
Tim Peters602f7402002-04-27 18:03:26 +00004707 if (size <= MAX_SHORT_UNICHARS) {
4708 /* Write into the stack buffer; nallocated can't overflow.
4709 * At the end, we'll allocate exactly as much heap space as it
4710 * turns out we need.
4711 */
4712 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004713 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004714 p = stackbuf;
4715 }
4716 else {
4717 /* Overallocate on the heap, and give the excess back at the end. */
4718 nallocated = size * 4;
4719 if (nallocated / 4 != size) /* overflow! */
4720 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004721 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004722 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004723 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004724 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004725 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004726
Tim Peters602f7402002-04-27 18:03:26 +00004727 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004728 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004729
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004730 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004731 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004732 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004733
Guido van Rossumd57fd912000-03-10 22:53:23 +00004734 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004735 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004736 *p++ = (char)(0xc0 | (ch >> 6));
4737 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004738 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 Py_ssize_t newpos;
4740 PyObject *rep;
4741 Py_ssize_t repsize, k, startpos;
4742 startpos = i-1;
4743#if SIZEOF_WCHAR_T == 2
4744 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004745#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004746 rep = unicode_encode_call_errorhandler(
4747 errors, &errorHandler, "utf-8", "surrogates not allowed",
Martin v. Löwis23e275b2011-11-02 18:02:51 +01004748 obj, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004749 if (!rep)
4750 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004752 if (PyBytes_Check(rep))
4753 repsize = PyBytes_GET_SIZE(rep);
4754 else
4755 repsize = PyUnicode_GET_SIZE(rep);
4756
4757 if (repsize > 4) {
4758 Py_ssize_t offset;
4759
4760 if (result == NULL)
4761 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004762 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004763 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004765 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4766 /* integer overflow */
4767 PyErr_NoMemory();
4768 goto error;
4769 }
4770 nallocated += repsize - 4;
4771 if (result != NULL) {
4772 if (_PyBytes_Resize(&result, nallocated) < 0)
4773 goto error;
4774 } else {
4775 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004776 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 goto error;
4778 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4779 }
4780 p = PyBytes_AS_STRING(result) + offset;
4781 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 if (PyBytes_Check(rep)) {
4784 char *prep = PyBytes_AS_STRING(rep);
4785 for(k = repsize; k > 0; k--)
4786 *p++ = *prep++;
4787 } else /* rep is unicode */ {
4788 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4789 Py_UNICODE c;
4790
4791 for(k=0; k<repsize; k++) {
4792 c = prep[k];
4793 if (0x80 <= c) {
Martin v. Löwis9e816682011-11-02 12:45:42 +01004794 raise_encode_exception_obj(&exc, "utf-8",
4795 (PyObject*)unicode,
4796 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004798 goto error;
4799 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004800 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004801 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004802 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004803 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004804 } else if (ch < 0x10000) {
4805 *p++ = (char)(0xe0 | (ch >> 12));
4806 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4807 *p++ = (char)(0x80 | (ch & 0x3f));
4808 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004809 /* Encode UCS4 Unicode ordinals */
4810 *p++ = (char)(0xf0 | (ch >> 18));
4811 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4812 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4813 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004814#if SIZEOF_WCHAR_T == 2
4815 wchar_offset++;
4816#endif
Tim Peters602f7402002-04-27 18:03:26 +00004817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004818 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004819
Guido van Rossum98297ee2007-11-06 21:34:58 +00004820 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004821 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004822 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004823 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004824 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004825 }
4826 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004827 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004828 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004829 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004830 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004832
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004833 Py_XDECREF(errorHandler);
4834 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004835 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004836 error:
4837 Py_XDECREF(errorHandler);
4838 Py_XDECREF(exc);
4839 Py_XDECREF(result);
4840 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004841
Tim Peters602f7402002-04-27 18:03:26 +00004842#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004843}
4844
Alexander Belopolsky40018472011-02-26 01:02:56 +00004845PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004846PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4847 Py_ssize_t size,
4848 const char *errors)
4849{
4850 PyObject *v, *unicode;
4851
4852 unicode = PyUnicode_FromUnicode(s, size);
4853 if (unicode == NULL)
4854 return NULL;
4855 v = _PyUnicode_AsUTF8String(unicode, errors);
4856 Py_DECREF(unicode);
4857 return v;
4858}
4859
4860PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004861PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004863 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004864}
4865
Walter Dörwald41980ca2007-08-16 21:55:45 +00004866/* --- UTF-32 Codec ------------------------------------------------------- */
4867
4868PyObject *
4869PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004870 Py_ssize_t size,
4871 const char *errors,
4872 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004873{
4874 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4875}
4876
4877PyObject *
4878PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004879 Py_ssize_t size,
4880 const char *errors,
4881 int *byteorder,
4882 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004883{
4884 const char *starts = s;
4885 Py_ssize_t startinpos;
4886 Py_ssize_t endinpos;
4887 Py_ssize_t outpos;
4888 PyUnicodeObject *unicode;
4889 Py_UNICODE *p;
4890#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004891 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004892 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004893#else
4894 const int pairs = 0;
4895#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004896 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004897 int bo = 0; /* assume native ordering by default */
4898 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004899 /* Offsets from q for retrieving bytes in the right order. */
4900#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4901 int iorder[] = {0, 1, 2, 3};
4902#else
4903 int iorder[] = {3, 2, 1, 0};
4904#endif
4905 PyObject *errorHandler = NULL;
4906 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004907
Walter Dörwald41980ca2007-08-16 21:55:45 +00004908 q = (unsigned char *)s;
4909 e = q + size;
4910
4911 if (byteorder)
4912 bo = *byteorder;
4913
4914 /* Check for BOM marks (U+FEFF) in the input and adjust current
4915 byte order setting accordingly. In native mode, the leading BOM
4916 mark is skipped, in all other modes, it is copied to the output
4917 stream as-is (giving a ZWNBSP character). */
4918 if (bo == 0) {
4919 if (size >= 4) {
4920 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004921 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004922#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004923 if (bom == 0x0000FEFF) {
4924 q += 4;
4925 bo = -1;
4926 }
4927 else if (bom == 0xFFFE0000) {
4928 q += 4;
4929 bo = 1;
4930 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004932 if (bom == 0x0000FEFF) {
4933 q += 4;
4934 bo = 1;
4935 }
4936 else if (bom == 0xFFFE0000) {
4937 q += 4;
4938 bo = -1;
4939 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004940#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004941 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942 }
4943
4944 if (bo == -1) {
4945 /* force LE */
4946 iorder[0] = 0;
4947 iorder[1] = 1;
4948 iorder[2] = 2;
4949 iorder[3] = 3;
4950 }
4951 else if (bo == 1) {
4952 /* force BE */
4953 iorder[0] = 3;
4954 iorder[1] = 2;
4955 iorder[2] = 1;
4956 iorder[3] = 0;
4957 }
4958
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004959 /* On narrow builds we split characters outside the BMP into two
4960 codepoints => count how much extra space we need. */
4961#ifndef Py_UNICODE_WIDE
4962 for (qq = q; qq < e; qq += 4)
4963 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4964 pairs++;
4965#endif
4966
4967 /* This might be one to much, because of a BOM */
4968 unicode = _PyUnicode_New((size+3)/4+pairs);
4969 if (!unicode)
4970 return NULL;
4971 if (size == 0)
4972 return (PyObject *)unicode;
4973
4974 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004975 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004976
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004978 Py_UCS4 ch;
4979 /* remaining bytes at the end? (size should be divisible by 4) */
4980 if (e-q<4) {
4981 if (consumed)
4982 break;
4983 errmsg = "truncated data";
4984 startinpos = ((const char *)q)-starts;
4985 endinpos = ((const char *)e)-starts;
4986 goto utf32Error;
4987 /* The remaining input chars are ignored if the callback
4988 chooses to skip the input */
4989 }
4990 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4991 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992
Benjamin Peterson29060642009-01-31 22:14:21 +00004993 if (ch >= 0x110000)
4994 {
4995 errmsg = "codepoint not in range(0x110000)";
4996 startinpos = ((const char *)q)-starts;
4997 endinpos = startinpos+4;
4998 goto utf32Error;
4999 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 if (ch >= 0x10000)
5002 {
5003 *p++ = 0xD800 | ((ch-0x10000) >> 10);
5004 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
5005 }
5006 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00005007#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 *p++ = ch;
5009 q += 4;
5010 continue;
5011 utf32Error:
5012 outpos = p-PyUnicode_AS_UNICODE(unicode);
5013 if (unicode_decode_call_errorhandler(
5014 errors, &errorHandler,
5015 "utf32", errmsg,
5016 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5017 &unicode, &outpos, &p))
5018 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019 }
5020
5021 if (byteorder)
5022 *byteorder = bo;
5023
5024 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005026
5027 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005028 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005029 goto onError;
5030
5031 Py_XDECREF(errorHandler);
5032 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005033#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005034 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005035 Py_DECREF(unicode);
5036 return NULL;
5037 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005038#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005039 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005040 return (PyObject *)unicode;
5041
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043 Py_DECREF(unicode);
5044 Py_XDECREF(errorHandler);
5045 Py_XDECREF(exc);
5046 return NULL;
5047}
5048
5049PyObject *
5050PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 Py_ssize_t size,
5052 const char *errors,
5053 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005055 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005057 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005058#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005059 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060#else
5061 const int pairs = 0;
5062#endif
5063 /* Offsets from p for storing byte pairs in the right order. */
5064#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5065 int iorder[] = {0, 1, 2, 3};
5066#else
5067 int iorder[] = {3, 2, 1, 0};
5068#endif
5069
Benjamin Peterson29060642009-01-31 22:14:21 +00005070#define STORECHAR(CH) \
5071 do { \
5072 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5073 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5074 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5075 p[iorder[0]] = (CH) & 0xff; \
5076 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 } while(0)
5078
5079 /* In narrow builds we can output surrogate pairs as one codepoint,
5080 so we need less space. */
5081#ifndef Py_UNICODE_WIDE
5082 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005083 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5084 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5085 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005087 nsize = (size - pairs + (byteorder == 0));
5088 bytesize = nsize * 4;
5089 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005090 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005091 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092 if (v == NULL)
5093 return NULL;
5094
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005095 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005097 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005099 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100
5101 if (byteorder == -1) {
5102 /* force LE */
5103 iorder[0] = 0;
5104 iorder[1] = 1;
5105 iorder[2] = 2;
5106 iorder[3] = 3;
5107 }
5108 else if (byteorder == 1) {
5109 /* force BE */
5110 iorder[0] = 3;
5111 iorder[1] = 2;
5112 iorder[2] = 1;
5113 iorder[3] = 0;
5114 }
5115
5116 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005118#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005119 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5120 Py_UCS4 ch2 = *s;
5121 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5122 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5123 s++;
5124 size--;
5125 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005126 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005127#endif
5128 STORECHAR(ch);
5129 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005130
5131 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005132 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005133#undef STORECHAR
5134}
5135
Alexander Belopolsky40018472011-02-26 01:02:56 +00005136PyObject *
5137PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138{
5139 if (!PyUnicode_Check(unicode)) {
5140 PyErr_BadArgument();
5141 return NULL;
5142 }
5143 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005144 PyUnicode_GET_SIZE(unicode),
5145 NULL,
5146 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147}
5148
Guido van Rossumd57fd912000-03-10 22:53:23 +00005149/* --- UTF-16 Codec ------------------------------------------------------- */
5150
Tim Peters772747b2001-08-09 22:21:55 +00005151PyObject *
5152PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005153 Py_ssize_t size,
5154 const char *errors,
5155 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005156{
Walter Dörwald69652032004-09-07 20:24:22 +00005157 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5158}
5159
Antoine Pitrouab868312009-01-10 15:40:25 +00005160/* Two masks for fast checking of whether a C 'long' may contain
5161 UTF16-encoded surrogate characters. This is an efficient heuristic,
5162 assuming that non-surrogate characters with a code point >= 0x8000 are
5163 rare in most input.
5164 FAST_CHAR_MASK is used when the input is in native byte ordering,
5165 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005166*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005167#if (SIZEOF_LONG == 8)
5168# define FAST_CHAR_MASK 0x8000800080008000L
5169# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5170#elif (SIZEOF_LONG == 4)
5171# define FAST_CHAR_MASK 0x80008000L
5172# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5173#else
5174# error C 'long' size should be either 4 or 8!
5175#endif
5176
Walter Dörwald69652032004-09-07 20:24:22 +00005177PyObject *
5178PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005179 Py_ssize_t size,
5180 const char *errors,
5181 int *byteorder,
5182 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005183{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005184 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005185 Py_ssize_t startinpos;
5186 Py_ssize_t endinpos;
5187 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005188 PyUnicodeObject *unicode;
5189 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005190 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005191 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005192 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005193 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005194 /* Offsets from q for retrieving byte pairs in the right order. */
5195#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5196 int ihi = 1, ilo = 0;
5197#else
5198 int ihi = 0, ilo = 1;
5199#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005200 PyObject *errorHandler = NULL;
5201 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005202
5203 /* Note: size will always be longer than the resulting Unicode
5204 character count */
5205 unicode = _PyUnicode_New(size);
5206 if (!unicode)
5207 return NULL;
5208 if (size == 0)
5209 return (PyObject *)unicode;
5210
5211 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005212 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005213 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005214 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
5216 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005217 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005219 /* Check for BOM marks (U+FEFF) in the input and adjust current
5220 byte order setting accordingly. In native mode, the leading BOM
5221 mark is skipped, in all other modes, it is copied to the output
5222 stream as-is (giving a ZWNBSP character). */
5223 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005224 if (size >= 2) {
5225 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005226#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005227 if (bom == 0xFEFF) {
5228 q += 2;
5229 bo = -1;
5230 }
5231 else if (bom == 0xFFFE) {
5232 q += 2;
5233 bo = 1;
5234 }
Tim Petersced69f82003-09-16 20:30:58 +00005235#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 if (bom == 0xFEFF) {
5237 q += 2;
5238 bo = 1;
5239 }
5240 else if (bom == 0xFFFE) {
5241 q += 2;
5242 bo = -1;
5243 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005244#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005246 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005247
Tim Peters772747b2001-08-09 22:21:55 +00005248 if (bo == -1) {
5249 /* force LE */
5250 ihi = 1;
5251 ilo = 0;
5252 }
5253 else if (bo == 1) {
5254 /* force BE */
5255 ihi = 0;
5256 ilo = 1;
5257 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005258#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5259 native_ordering = ilo < ihi;
5260#else
5261 native_ordering = ilo > ihi;
5262#endif
Tim Peters772747b2001-08-09 22:21:55 +00005263
Antoine Pitrouab868312009-01-10 15:40:25 +00005264 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005265 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005266 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005267 /* First check for possible aligned read of a C 'long'. Unaligned
5268 reads are more expensive, better to defer to another iteration. */
5269 if (!((size_t) q & LONG_PTR_MASK)) {
5270 /* Fast path for runs of non-surrogate chars. */
5271 register const unsigned char *_q = q;
5272 Py_UNICODE *_p = p;
5273 if (native_ordering) {
5274 /* Native ordering is simple: as long as the input cannot
5275 possibly contain a surrogate char, do an unrolled copy
5276 of several 16-bit code points to the target object.
5277 The non-surrogate check is done on several input bytes
5278 at a time (as many as a C 'long' can contain). */
5279 while (_q < aligned_end) {
5280 unsigned long data = * (unsigned long *) _q;
5281 if (data & FAST_CHAR_MASK)
5282 break;
5283 _p[0] = ((unsigned short *) _q)[0];
5284 _p[1] = ((unsigned short *) _q)[1];
5285#if (SIZEOF_LONG == 8)
5286 _p[2] = ((unsigned short *) _q)[2];
5287 _p[3] = ((unsigned short *) _q)[3];
5288#endif
5289 _q += SIZEOF_LONG;
5290 _p += SIZEOF_LONG / 2;
5291 }
5292 }
5293 else {
5294 /* Byteswapped ordering is similar, but we must decompose
5295 the copy bytewise, and take care of zero'ing out the
5296 upper bytes if the target object is in 32-bit units
5297 (that is, in UCS-4 builds). */
5298 while (_q < aligned_end) {
5299 unsigned long data = * (unsigned long *) _q;
5300 if (data & SWAPPED_FAST_CHAR_MASK)
5301 break;
5302 /* Zero upper bytes in UCS-4 builds */
5303#if (Py_UNICODE_SIZE > 2)
5304 _p[0] = 0;
5305 _p[1] = 0;
5306#if (SIZEOF_LONG == 8)
5307 _p[2] = 0;
5308 _p[3] = 0;
5309#endif
5310#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005311 /* Issue #4916; UCS-4 builds on big endian machines must
5312 fill the two last bytes of each 4-byte unit. */
5313#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5314# define OFF 2
5315#else
5316# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005317#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005318 ((unsigned char *) _p)[OFF + 1] = _q[0];
5319 ((unsigned char *) _p)[OFF + 0] = _q[1];
5320 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5321 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5322#if (SIZEOF_LONG == 8)
5323 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5324 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5325 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5326 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5327#endif
5328#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005329 _q += SIZEOF_LONG;
5330 _p += SIZEOF_LONG / 2;
5331 }
5332 }
5333 p = _p;
5334 q = _q;
5335 if (q >= e)
5336 break;
5337 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005339
Benjamin Peterson14339b62009-01-31 16:36:08 +00005340 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005341
5342 if (ch < 0xD800 || ch > 0xDFFF) {
5343 *p++ = ch;
5344 continue;
5345 }
5346
5347 /* UTF-16 code pair: */
5348 if (q > e) {
5349 errmsg = "unexpected end of data";
5350 startinpos = (((const char *)q) - 2) - starts;
5351 endinpos = ((const char *)e) + 1 - starts;
5352 goto utf16Error;
5353 }
5354 if (0xD800 <= ch && ch <= 0xDBFF) {
5355 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5356 q += 2;
5357 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005358#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 *p++ = ch;
5360 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005361#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005362 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005363#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 continue;
5365 }
5366 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005367 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005368 startinpos = (((const char *)q)-4)-starts;
5369 endinpos = startinpos+2;
5370 goto utf16Error;
5371 }
5372
Benjamin Peterson14339b62009-01-31 16:36:08 +00005373 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 errmsg = "illegal encoding";
5375 startinpos = (((const char *)q)-2)-starts;
5376 endinpos = startinpos+2;
5377 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005378
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 utf16Error:
5380 outpos = p - PyUnicode_AS_UNICODE(unicode);
5381 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005382 errors,
5383 &errorHandler,
5384 "utf16", errmsg,
5385 &starts,
5386 (const char **)&e,
5387 &startinpos,
5388 &endinpos,
5389 &exc,
5390 (const char **)&q,
5391 &unicode,
5392 &outpos,
5393 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005394 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005396 /* remaining byte at the end? (size should be even) */
5397 if (e == q) {
5398 if (!consumed) {
5399 errmsg = "truncated data";
5400 startinpos = ((const char *)q) - starts;
5401 endinpos = ((const char *)e) + 1 - starts;
5402 outpos = p - PyUnicode_AS_UNICODE(unicode);
5403 if (unicode_decode_call_errorhandler(
5404 errors,
5405 &errorHandler,
5406 "utf16", errmsg,
5407 &starts,
5408 (const char **)&e,
5409 &startinpos,
5410 &endinpos,
5411 &exc,
5412 (const char **)&q,
5413 &unicode,
5414 &outpos,
5415 &p))
5416 goto onError;
5417 /* The remaining input chars are ignored if the callback
5418 chooses to skip the input */
5419 }
5420 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421
5422 if (byteorder)
5423 *byteorder = bo;
5424
Walter Dörwald69652032004-09-07 20:24:22 +00005425 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005426 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005427
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005429 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430 goto onError;
5431
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005432 Py_XDECREF(errorHandler);
5433 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005434#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005435 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005436 Py_DECREF(unicode);
5437 return NULL;
5438 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005439#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005440 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441 return (PyObject *)unicode;
5442
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005445 Py_XDECREF(errorHandler);
5446 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005447 return NULL;
5448}
5449
Antoine Pitrouab868312009-01-10 15:40:25 +00005450#undef FAST_CHAR_MASK
5451#undef SWAPPED_FAST_CHAR_MASK
5452
Tim Peters772747b2001-08-09 22:21:55 +00005453PyObject *
5454PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005455 Py_ssize_t size,
5456 const char *errors,
5457 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005458{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005459 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005460 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005461 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005462#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005463 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005464#else
5465 const int pairs = 0;
5466#endif
Tim Peters772747b2001-08-09 22:21:55 +00005467 /* Offsets from p for storing byte pairs in the right order. */
5468#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5469 int ihi = 1, ilo = 0;
5470#else
5471 int ihi = 0, ilo = 1;
5472#endif
5473
Benjamin Peterson29060642009-01-31 22:14:21 +00005474#define STORECHAR(CH) \
5475 do { \
5476 p[ihi] = ((CH) >> 8) & 0xff; \
5477 p[ilo] = (CH) & 0xff; \
5478 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005479 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005481#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005482 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 if (s[i] >= 0x10000)
5484 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005485#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005486 /* 2 * (size + pairs + (byteorder == 0)) */
5487 if (size > PY_SSIZE_T_MAX ||
5488 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005490 nsize = size + pairs + (byteorder == 0);
5491 bytesize = nsize * 2;
5492 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005493 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005494 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495 if (v == NULL)
5496 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005498 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005500 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005501 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005502 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005503
5504 if (byteorder == -1) {
5505 /* force LE */
5506 ihi = 1;
5507 ilo = 0;
5508 }
5509 else if (byteorder == 1) {
5510 /* force BE */
5511 ihi = 0;
5512 ilo = 1;
5513 }
5514
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005515 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005516 Py_UNICODE ch = *s++;
5517 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005518#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005519 if (ch >= 0x10000) {
5520 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5521 ch = 0xD800 | ((ch-0x10000) >> 10);
5522 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005523#endif
Tim Peters772747b2001-08-09 22:21:55 +00005524 STORECHAR(ch);
5525 if (ch2)
5526 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005527 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005528
5529 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005530 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005531#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005532}
5533
Alexander Belopolsky40018472011-02-26 01:02:56 +00005534PyObject *
5535PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536{
5537 if (!PyUnicode_Check(unicode)) {
5538 PyErr_BadArgument();
5539 return NULL;
5540 }
5541 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005542 PyUnicode_GET_SIZE(unicode),
5543 NULL,
5544 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545}
5546
5547/* --- Unicode Escape Codec ----------------------------------------------- */
5548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005549/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5550 if all the escapes in the string make it still a valid ASCII string.
5551 Returns -1 if any escapes were found which cause the string to
5552 pop out of ASCII range. Otherwise returns the length of the
5553 required buffer to hold the string.
5554 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005555static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005556length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5557{
5558 const unsigned char *p = (const unsigned char *)s;
5559 const unsigned char *end = p + size;
5560 Py_ssize_t length = 0;
5561
5562 if (size < 0)
5563 return -1;
5564
5565 for (; p < end; ++p) {
5566 if (*p > 127) {
5567 /* Non-ASCII */
5568 return -1;
5569 }
5570 else if (*p != '\\') {
5571 /* Normal character */
5572 ++length;
5573 }
5574 else {
5575 /* Backslash-escape, check next char */
5576 ++p;
5577 /* Escape sequence reaches till end of string or
5578 non-ASCII follow-up. */
5579 if (p >= end || *p > 127)
5580 return -1;
5581 switch (*p) {
5582 case '\n':
5583 /* backslash + \n result in zero characters */
5584 break;
5585 case '\\': case '\'': case '\"':
5586 case 'b': case 'f': case 't':
5587 case 'n': case 'r': case 'v': case 'a':
5588 ++length;
5589 break;
5590 case '0': case '1': case '2': case '3':
5591 case '4': case '5': case '6': case '7':
5592 case 'x': case 'u': case 'U': case 'N':
5593 /* these do not guarantee ASCII characters */
5594 return -1;
5595 default:
5596 /* count the backslash + the other character */
5597 length += 2;
5598 }
5599 }
5600 }
5601 return length;
5602}
5603
5604/* Similar to PyUnicode_WRITE but either write into wstr field
5605 or treat string as ASCII. */
5606#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5607 do { \
5608 if ((kind) != PyUnicode_WCHAR_KIND) \
5609 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5610 else \
5611 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5612 } while (0)
5613
5614#define WRITE_WSTR(buf, index, value) \
5615 assert(kind == PyUnicode_WCHAR_KIND), \
5616 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5617
5618
Fredrik Lundh06d12682001-01-24 07:59:11 +00005619static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005620
Alexander Belopolsky40018472011-02-26 01:02:56 +00005621PyObject *
5622PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005623 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005624 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005626 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005627 Py_ssize_t startinpos;
5628 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005629 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005633 char* message;
5634 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 PyObject *errorHandler = NULL;
5636 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005637 Py_ssize_t ascii_length;
5638 Py_ssize_t i;
5639 int kind;
5640 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642 ascii_length = length_of_escaped_ascii_string(s, size);
5643
5644 /* After length_of_escaped_ascii_string() there are two alternatives,
5645 either the string is pure ASCII with named escapes like \n, etc.
5646 and we determined it's exact size (common case)
5647 or it contains \x, \u, ... escape sequences. then we create a
5648 legacy wchar string and resize it at the end of this function. */
5649 if (ascii_length >= 0) {
5650 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5651 if (!v)
5652 goto onError;
5653 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5654 kind = PyUnicode_1BYTE_KIND;
5655 data = PyUnicode_DATA(v);
5656 }
5657 else {
5658 /* Escaped strings will always be longer than the resulting
5659 Unicode string, so we start with size here and then reduce the
5660 length after conversion to the true value.
5661 (but if the error callback returns a long replacement string
5662 we'll have to allocate more space) */
5663 v = _PyUnicode_New(size);
5664 if (!v)
5665 goto onError;
5666 kind = PyUnicode_WCHAR_KIND;
5667 data = PyUnicode_AS_UNICODE(v);
5668 }
5669
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 if (size == 0)
5671 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005672 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005674
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 while (s < end) {
5676 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005677 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680 if (kind == PyUnicode_WCHAR_KIND) {
5681 assert(i < _PyUnicode_WSTR_LENGTH(v));
5682 }
5683 else {
5684 /* The only case in which i == ascii_length is a backslash
5685 followed by a newline. */
5686 assert(i <= ascii_length);
5687 }
5688
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689 /* Non-escape characters are interpreted as Unicode ordinals */
5690 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005691 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 continue;
5693 }
5694
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005695 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 /* \ - Escapes */
5697 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005698 c = *s++;
5699 if (s > end)
5700 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005701
5702 if (kind == PyUnicode_WCHAR_KIND) {
5703 assert(i < _PyUnicode_WSTR_LENGTH(v));
5704 }
5705 else {
5706 /* The only case in which i == ascii_length is a backslash
5707 followed by a newline. */
5708 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5709 }
5710
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005711 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005712
Benjamin Peterson29060642009-01-31 22:14:21 +00005713 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005714 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005715 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5716 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5717 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5718 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5719 /* FF */
5720 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5721 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5722 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5723 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5724 /* VT */
5725 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5726 /* BEL, not classic C */
5727 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728
Benjamin Peterson29060642009-01-31 22:14:21 +00005729 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 case '0': case '1': case '2': case '3':
5731 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005732 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005733 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005734 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005735 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005736 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 break;
5740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 /* hex escapes */
5742 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005743 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005744 digits = 2;
5745 message = "truncated \\xXX escape";
5746 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005750 digits = 4;
5751 message = "truncated \\uXXXX escape";
5752 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005755 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005756 digits = 8;
5757 message = "truncated \\UXXXXXXXX escape";
5758 hexescape:
5759 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005761 if (s+digits>end) {
5762 endinpos = size;
5763 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005764 errors, &errorHandler,
5765 "unicodeescape", "end of string in escape sequence",
5766 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005770 goto nextByte;
5771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005772 for (j = 0; j < digits; ++j) {
5773 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005774 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005775 endinpos = (s+j+1)-starts;
5776 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005777 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005778 errors, &errorHandler,
5779 "unicodeescape", message,
5780 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005781 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005782 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005783 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005784 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005785 }
5786 chr = (chr<<4) & ~0xF;
5787 if (c >= '0' && c <= '9')
5788 chr += c - '0';
5789 else if (c >= 'a' && c <= 'f')
5790 chr += 10 + c - 'a';
5791 else
5792 chr += 10 + c - 'A';
5793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005794 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005795 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 /* _decoding_error will have already written into the
5797 target buffer. */
5798 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005800 /* when we get here, chr is a 32-bit unicode character */
5801 if (chr <= 0xffff)
5802 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005803 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005804 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005805 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005806 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005807#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005808 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005809#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005810 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5812 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005813#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005814 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005815 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005816 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005817 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005818 errors, &errorHandler,
5819 "unicodeescape", "illegal Unicode character",
5820 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005822 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005823 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005824 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005825 break;
5826
Benjamin Peterson29060642009-01-31 22:14:21 +00005827 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005828 case 'N':
5829 message = "malformed \\N character escape";
5830 if (ucnhash_CAPI == NULL) {
5831 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5833 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 if (ucnhash_CAPI == NULL)
5835 goto ucnhashError;
5836 }
5837 if (*s == '{') {
5838 const char *start = s+1;
5839 /* look for the closing brace */
5840 while (*s != '}' && s < end)
5841 s++;
5842 if (s > start && s < end && *s == '}') {
5843 /* found a name. look it up in the unicode database */
5844 message = "unknown Unicode character name";
5845 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005847 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005848 goto store;
5849 }
5850 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005851 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005854 errors, &errorHandler,
5855 "unicodeescape", message,
5856 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005858 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860 break;
5861
5862 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005863 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005864 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 message = "\\ at end of string";
5866 s--;
5867 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005868 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005870 errors, &errorHandler,
5871 "unicodeescape", message,
5872 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005873 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005876 }
5877 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005878 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5879 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005880 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005881 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005883 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005884 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886 /* Ensure the length prediction worked in case of ASCII strings */
5887 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5888
Victor Stinnerfe226c02011-10-03 03:52:20 +02005889 if (kind == PyUnicode_WCHAR_KIND)
5890 {
5891 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5892 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005893 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005894 Py_XDECREF(errorHandler);
5895 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005896#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005897 if (_PyUnicode_READY_REPLACE(&v)) {
5898 Py_DECREF(v);
5899 return NULL;
5900 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005901#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005902 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005904
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005906 PyErr_SetString(
5907 PyExc_UnicodeError,
5908 "\\N escapes not supported (can't load unicodedata module)"
5909 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005910 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 Py_XDECREF(errorHandler);
5912 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005913 return NULL;
5914
Benjamin Peterson29060642009-01-31 22:14:21 +00005915 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 Py_XDECREF(errorHandler);
5918 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 return NULL;
5920}
5921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005922#undef WRITE_ASCII_OR_WSTR
5923#undef WRITE_WSTR
5924
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925/* Return a Unicode-Escape string version of the Unicode object.
5926
5927 If quotes is true, the string is enclosed in u"" or u'' quotes as
5928 appropriate.
5929
5930*/
5931
Alexander Belopolsky40018472011-02-26 01:02:56 +00005932PyObject *
5933PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005934 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005936 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005939#ifdef Py_UNICODE_WIDE
5940 const Py_ssize_t expandsize = 10;
5941#else
5942 const Py_ssize_t expandsize = 6;
5943#endif
5944
Thomas Wouters89f507f2006-12-13 04:49:30 +00005945 /* XXX(nnorwitz): rather than over-allocating, it would be
5946 better to choose a different scheme. Perhaps scan the
5947 first N-chars of the string and allocate based on that size.
5948 */
5949 /* Initial allocation is based on the longest-possible unichr
5950 escape.
5951
5952 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5953 unichr, so in this case it's the longest unichr escape. In
5954 narrow (UTF-16) builds this is five chars per source unichr
5955 since there are two unichrs in the surrogate pair, so in narrow
5956 (UTF-16) builds it's not the longest unichr escape.
5957
5958 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5959 so in the narrow (UTF-16) build case it's the longest unichr
5960 escape.
5961 */
5962
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005963 if (size == 0)
5964 return PyBytes_FromStringAndSize(NULL, 0);
5965
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005966 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005967 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005968
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005969 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005970 2
5971 + expandsize*size
5972 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 if (repr == NULL)
5974 return NULL;
5975
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005976 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 while (size-- > 0) {
5979 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005980
Walter Dörwald79e913e2007-05-12 11:08:06 +00005981 /* Escape backslashes */
5982 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 *p++ = '\\';
5984 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005985 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005986 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005987
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005988#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005989 /* Map 21-bit characters to '\U00xxxxxx' */
5990 else if (ch >= 0x10000) {
5991 *p++ = '\\';
5992 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005993 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5994 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5995 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5996 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5997 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5998 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5999 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6000 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006001 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006002 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006003#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6005 else if (ch >= 0xD800 && ch < 0xDC00) {
6006 Py_UNICODE ch2;
6007 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00006008
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 ch2 = *s++;
6010 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006011 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6013 *p++ = '\\';
6014 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006015 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
6016 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
6017 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
6018 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
6019 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
6020 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
6021 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
6022 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006023 continue;
6024 }
6025 /* Fall through: isolated surrogates are copied as-is */
6026 s--;
6027 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006028 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006029#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006030
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006032 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 *p++ = '\\';
6034 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006035 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6036 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6037 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6038 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006040
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006041 /* Map special whitespace to '\t', \n', '\r' */
6042 else if (ch == '\t') {
6043 *p++ = '\\';
6044 *p++ = 't';
6045 }
6046 else if (ch == '\n') {
6047 *p++ = '\\';
6048 *p++ = 'n';
6049 }
6050 else if (ch == '\r') {
6051 *p++ = '\\';
6052 *p++ = 'r';
6053 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006054
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006055 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006056 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006058 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006059 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6060 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006061 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006062
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 /* Copy everything else as-is */
6064 else
6065 *p++ = (char) ch;
6066 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006068 assert(p - PyBytes_AS_STRING(repr) > 0);
6069 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6070 return NULL;
6071 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072}
6073
Alexander Belopolsky40018472011-02-26 01:02:56 +00006074PyObject *
6075PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006077 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078 if (!PyUnicode_Check(unicode)) {
6079 PyErr_BadArgument();
6080 return NULL;
6081 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006082 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6083 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006084 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085}
6086
6087/* --- Raw Unicode Escape Codec ------------------------------------------- */
6088
Alexander Belopolsky40018472011-02-26 01:02:56 +00006089PyObject *
6090PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006091 Py_ssize_t size,
6092 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006094 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006095 Py_ssize_t startinpos;
6096 Py_ssize_t endinpos;
6097 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006099 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006100 const char *end;
6101 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006102 PyObject *errorHandler = NULL;
6103 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006104
Guido van Rossumd57fd912000-03-10 22:53:23 +00006105 /* Escaped strings will always be longer than the resulting
6106 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006107 length after conversion to the true value. (But decoding error
6108 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109 v = _PyUnicode_New(size);
6110 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006113 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006114 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115 end = s + size;
6116 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006117 unsigned char c;
6118 Py_UCS4 x;
6119 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006120 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 /* Non-escape characters are interpreted as Unicode ordinals */
6123 if (*s != '\\') {
6124 *p++ = (unsigned char)*s++;
6125 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006126 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 startinpos = s-starts;
6128
6129 /* \u-escapes are only interpreted iff the number of leading
6130 backslashes if odd */
6131 bs = s;
6132 for (;s < end;) {
6133 if (*s != '\\')
6134 break;
6135 *p++ = (unsigned char)*s++;
6136 }
6137 if (((s - bs) & 1) == 0 ||
6138 s >= end ||
6139 (*s != 'u' && *s != 'U')) {
6140 continue;
6141 }
6142 p--;
6143 count = *s=='u' ? 4 : 8;
6144 s++;
6145
6146 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6147 outpos = p-PyUnicode_AS_UNICODE(v);
6148 for (x = 0, i = 0; i < count; ++i, ++s) {
6149 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006150 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 endinpos = s-starts;
6152 if (unicode_decode_call_errorhandler(
6153 errors, &errorHandler,
6154 "rawunicodeescape", "truncated \\uXXXX",
6155 &starts, &end, &startinpos, &endinpos, &exc, &s,
6156 &v, &outpos, &p))
6157 goto onError;
6158 goto nextByte;
6159 }
6160 x = (x<<4) & ~0xF;
6161 if (c >= '0' && c <= '9')
6162 x += c - '0';
6163 else if (c >= 'a' && c <= 'f')
6164 x += 10 + c - 'a';
6165 else
6166 x += 10 + c - 'A';
6167 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006168 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 /* UCS-2 character */
6170 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006171 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 /* UCS-4 character. Either store directly, or as
6173 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006174#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006175 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006176#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006177 x -= 0x10000L;
6178 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6179 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006180#endif
6181 } else {
6182 endinpos = s-starts;
6183 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006184 if (unicode_decode_call_errorhandler(
6185 errors, &errorHandler,
6186 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 &starts, &end, &startinpos, &endinpos, &exc, &s,
6188 &v, &outpos, &p))
6189 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006190 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 nextByte:
6192 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006194 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006196 Py_XDECREF(errorHandler);
6197 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006198#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006199 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006200 Py_DECREF(v);
6201 return NULL;
6202 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006203#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006204 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006205 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006206
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006209 Py_XDECREF(errorHandler);
6210 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211 return NULL;
6212}
6213
Alexander Belopolsky40018472011-02-26 01:02:56 +00006214PyObject *
6215PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006216 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006218 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219 char *p;
6220 char *q;
6221
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006222#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006223 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006224#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006225 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006226#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006227
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006228 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006229 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006230
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006231 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 if (repr == NULL)
6233 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006234 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006235 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006237 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 while (size-- > 0) {
6239 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006240#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006241 /* Map 32-bit characters to '\Uxxxxxxxx' */
6242 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006243 *p++ = '\\';
6244 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006245 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6246 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6247 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6248 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6249 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6250 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6251 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6252 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006253 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006254 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006255#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6257 if (ch >= 0xD800 && ch < 0xDC00) {
6258 Py_UNICODE ch2;
6259 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006260
Benjamin Peterson29060642009-01-31 22:14:21 +00006261 ch2 = *s++;
6262 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006263 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6265 *p++ = '\\';
6266 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006267 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6268 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6269 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6270 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6271 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6272 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6273 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6274 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006275 continue;
6276 }
6277 /* Fall through: isolated surrogates are copied as-is */
6278 s--;
6279 size++;
6280 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006281#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 /* Map 16-bit characters to '\uxxxx' */
6283 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284 *p++ = '\\';
6285 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006286 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6287 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6288 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6289 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006290 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 /* Copy everything else as-is */
6292 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293 *p++ = (char) ch;
6294 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006295 size = p - q;
6296
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006297 assert(size > 0);
6298 if (_PyBytes_Resize(&repr, size) < 0)
6299 return NULL;
6300 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301}
6302
Alexander Belopolsky40018472011-02-26 01:02:56 +00006303PyObject *
6304PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006306 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006308 PyErr_BadArgument();
6309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006311 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6312 PyUnicode_GET_SIZE(unicode));
6313
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006314 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006315}
6316
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006317/* --- Unicode Internal Codec ------------------------------------------- */
6318
Alexander Belopolsky40018472011-02-26 01:02:56 +00006319PyObject *
6320_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006321 Py_ssize_t size,
6322 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323{
6324 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006325 Py_ssize_t startinpos;
6326 Py_ssize_t endinpos;
6327 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328 PyUnicodeObject *v;
6329 Py_UNICODE *p;
6330 const char *end;
6331 const char *reason;
6332 PyObject *errorHandler = NULL;
6333 PyObject *exc = NULL;
6334
Neal Norwitzd43069c2006-01-08 01:12:10 +00006335#ifdef Py_UNICODE_WIDE
6336 Py_UNICODE unimax = PyUnicode_GetMax();
6337#endif
6338
Thomas Wouters89f507f2006-12-13 04:49:30 +00006339 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006340 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6341 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006343 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6344 as string was created with the old API. */
6345 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006346 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006347 p = PyUnicode_AS_UNICODE(v);
6348 end = s + size;
6349
6350 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006351 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006352 /* We have to sanity check the raw data, otherwise doom looms for
6353 some malformed UCS-4 data. */
6354 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006355#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006356 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006357#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006358 end-s < Py_UNICODE_SIZE
6359 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006361 startinpos = s - starts;
6362 if (end-s < Py_UNICODE_SIZE) {
6363 endinpos = end-starts;
6364 reason = "truncated input";
6365 }
6366 else {
6367 endinpos = s - starts + Py_UNICODE_SIZE;
6368 reason = "illegal code point (> 0x10FFFF)";
6369 }
6370 outpos = p - PyUnicode_AS_UNICODE(v);
6371 if (unicode_decode_call_errorhandler(
6372 errors, &errorHandler,
6373 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006374 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006375 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006376 goto onError;
6377 }
6378 }
6379 else {
6380 p++;
6381 s += Py_UNICODE_SIZE;
6382 }
6383 }
6384
Victor Stinnerfe226c02011-10-03 03:52:20 +02006385 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006386 goto onError;
6387 Py_XDECREF(errorHandler);
6388 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006389#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006390 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006391 Py_DECREF(v);
6392 return NULL;
6393 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006394#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006395 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006396 return (PyObject *)v;
6397
Benjamin Peterson29060642009-01-31 22:14:21 +00006398 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006399 Py_XDECREF(v);
6400 Py_XDECREF(errorHandler);
6401 Py_XDECREF(exc);
6402 return NULL;
6403}
6404
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405/* --- Latin-1 Codec ------------------------------------------------------ */
6406
Alexander Belopolsky40018472011-02-26 01:02:56 +00006407PyObject *
6408PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006409 Py_ssize_t size,
6410 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006412 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006413 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414}
6415
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006417static void
6418make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006419 const char *encoding,
6420 const Py_UNICODE *unicode, Py_ssize_t size,
6421 Py_ssize_t startpos, Py_ssize_t endpos,
6422 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006423{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 *exceptionObject = PyUnicodeEncodeError_Create(
6426 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 }
6428 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6430 goto onError;
6431 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6432 goto onError;
6433 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6434 goto onError;
6435 return;
6436 onError:
6437 Py_DECREF(*exceptionObject);
6438 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439 }
6440}
6441
Martin v. Löwis9e816682011-11-02 12:45:42 +01006442/* This is ultimately going t replace above function. */
6443static void
6444make_encode_exception_obj(PyObject **exceptionObject,
6445 const char *encoding,
6446 PyObject *unicode,
6447 Py_ssize_t startpos, Py_ssize_t endpos,
6448 const char *reason)
6449{
6450 if (*exceptionObject == NULL) {
6451 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006452 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006453 encoding, unicode, startpos, endpos, reason);
6454 }
6455 else {
6456 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6457 goto onError;
6458 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6459 goto onError;
6460 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6461 goto onError;
6462 return;
6463 onError:
6464 Py_DECREF(*exceptionObject);
6465 *exceptionObject = NULL;
6466 }
6467}
6468
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006470static void
6471raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006472 const char *encoding,
6473 const Py_UNICODE *unicode, Py_ssize_t size,
6474 Py_ssize_t startpos, Py_ssize_t endpos,
6475 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476{
6477 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006479 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006480 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006481}
Martin v. Löwis9e816682011-11-02 12:45:42 +01006482/* This is ultimately going to replace above function. */
6483static void
6484raise_encode_exception_obj(PyObject **exceptionObject,
6485 const char *encoding,
6486 PyObject *unicode,
6487 Py_ssize_t startpos, Py_ssize_t endpos,
6488 const char *reason)
6489{
6490 make_encode_exception_obj(exceptionObject,
6491 encoding, unicode, startpos, endpos, reason);
6492 if (*exceptionObject != NULL)
6493 PyCodec_StrictErrors(*exceptionObject);
6494}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006495
6496/* error handling callback helper:
6497 build arguments, call the callback and check the arguments,
6498 put the result into newpos and return the replacement string, which
6499 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006500static PyObject *
6501unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006502 PyObject **errorHandler,
6503 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006505 Py_ssize_t startpos, Py_ssize_t endpos,
6506 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006507{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006508 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006509 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006510 PyObject *restuple;
6511 PyObject *resunicode;
6512
6513 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006516 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006517 }
6518
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006519 if (PyUnicode_READY(unicode) < 0)
6520 return NULL;
6521 len = PyUnicode_GET_LENGTH(unicode);
6522
6523 make_encode_exception_obj(exceptionObject,
6524 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006525 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006527
6528 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006530 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006532 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006533 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 Py_DECREF(restuple);
6535 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006536 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006537 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 &resunicode, newpos)) {
6539 Py_DECREF(restuple);
6540 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006541 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006542 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6543 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6544 Py_DECREF(restuple);
6545 return NULL;
6546 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006547 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 *newpos = len + *newpos;
6549 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6551 Py_DECREF(restuple);
6552 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006553 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006554 Py_INCREF(resunicode);
6555 Py_DECREF(restuple);
6556 return resunicode;
6557}
6558
Alexander Belopolsky40018472011-02-26 01:02:56 +00006559static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006560unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006561 const char *errors,
6562 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006563{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 /* input state */
6565 Py_ssize_t pos=0, size;
6566 int kind;
6567 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006568 /* output object */
6569 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 /* pointer into the output */
6571 char *str;
6572 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006573 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006574 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6575 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576 PyObject *errorHandler = NULL;
6577 PyObject *exc = NULL;
6578 /* the following variable is used for caching string comparisons
6579 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6580 int known_errorHandler = -1;
6581
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006582 if (PyUnicode_READY(unicode) < 0)
6583 return NULL;
6584 size = PyUnicode_GET_LENGTH(unicode);
6585 kind = PyUnicode_KIND(unicode);
6586 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587 /* allocate enough for a simple encoding without
6588 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006589 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006590 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006591 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006592 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006593 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006594 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006595 ressize = size;
6596
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006597 while (pos < size) {
6598 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 /* can we encode this? */
6601 if (c<limit) {
6602 /* no overflow check, because we know that the space is enough */
6603 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006604 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006605 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 Py_ssize_t requiredsize;
6608 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006609 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 Py_ssize_t collstart = pos;
6612 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 ++collend;
6616 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6617 if (known_errorHandler==-1) {
6618 if ((errors==NULL) || (!strcmp(errors, "strict")))
6619 known_errorHandler = 1;
6620 else if (!strcmp(errors, "replace"))
6621 known_errorHandler = 2;
6622 else if (!strcmp(errors, "ignore"))
6623 known_errorHandler = 3;
6624 else if (!strcmp(errors, "xmlcharrefreplace"))
6625 known_errorHandler = 4;
6626 else
6627 known_errorHandler = 0;
6628 }
6629 switch (known_errorHandler) {
6630 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631 raise_encode_exception_obj(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006632 goto onError;
6633 case 2: /* replace */
6634 while (collstart++<collend)
6635 *str++ = '?'; /* fall through */
6636 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 break;
6639 case 4: /* xmlcharrefreplace */
6640 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006641 /* determine replacement size */
6642 for (i = collstart, repsize = 0; i < collend; ++i) {
6643 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6644 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006648 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006649 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006650 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006652#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 else
6654 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006655#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006659 repsize += 2+6+1;
6660 else
6661 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006662#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006663 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006664 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 if (requiredsize > ressize) {
6666 if (requiredsize<2*ressize)
6667 requiredsize = 2*ressize;
6668 if (_PyBytes_Resize(&res, requiredsize))
6669 goto onError;
6670 str = PyBytes_AS_STRING(res) + respos;
6671 ressize = requiredsize;
6672 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673 /* generate replacement */
6674 for (i = collstart; i < collend; ++i) {
6675 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 break;
6679 default:
6680 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006681 encoding, reason, unicode, &exc,
6682 collstart, collend, &newpos);
6683 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6684 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006685 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006686 if (PyBytes_Check(repunicode)) {
6687 /* Directly copy bytes result to output. */
6688 repsize = PyBytes_Size(repunicode);
6689 if (repsize > 1) {
6690 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006691 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006692 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6693 Py_DECREF(repunicode);
6694 goto onError;
6695 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006696 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006697 ressize += repsize-1;
6698 }
6699 memcpy(str, PyBytes_AsString(repunicode), repsize);
6700 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006701 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006702 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006703 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006704 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 /* need more space? (at least enough for what we
6706 have+the replacement+the rest of the string, so
6707 we won't have to check space for encodable characters) */
6708 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006709 repsize = PyUnicode_GET_LENGTH(repunicode);
6710 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 if (requiredsize > ressize) {
6712 if (requiredsize<2*ressize)
6713 requiredsize = 2*ressize;
6714 if (_PyBytes_Resize(&res, requiredsize)) {
6715 Py_DECREF(repunicode);
6716 goto onError;
6717 }
6718 str = PyBytes_AS_STRING(res) + respos;
6719 ressize = requiredsize;
6720 }
6721 /* check if there is anything unencodable in the replacement
6722 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006723 for (i = 0; repsize-->0; ++i, ++str) {
6724 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 if (c >= limit) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006726 raise_encode_exception_obj(&exc, encoding, unicode,
6727 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 Py_DECREF(repunicode);
6729 goto onError;
6730 }
6731 *str = (char)c;
6732 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006733 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006734 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006735 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006736 }
6737 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006738 /* Resize if we allocated to much */
6739 size = str - PyBytes_AS_STRING(res);
6740 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006741 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006742 if (_PyBytes_Resize(&res, size) < 0)
6743 goto onError;
6744 }
6745
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746 Py_XDECREF(errorHandler);
6747 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006748 return res;
6749
6750 onError:
6751 Py_XDECREF(res);
6752 Py_XDECREF(errorHandler);
6753 Py_XDECREF(exc);
6754 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006755}
6756
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006757/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006758PyObject *
6759PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006760 Py_ssize_t size,
6761 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006762{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006763 PyObject *result;
6764 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6765 if (unicode == NULL)
6766 return NULL;
6767 result = unicode_encode_ucs1(unicode, errors, 256);
6768 Py_DECREF(unicode);
6769 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006770}
6771
Alexander Belopolsky40018472011-02-26 01:02:56 +00006772PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006773_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006774{
6775 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 PyErr_BadArgument();
6777 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006779 if (PyUnicode_READY(unicode) == -1)
6780 return NULL;
6781 /* Fast path: if it is a one-byte string, construct
6782 bytes object directly. */
6783 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6784 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6785 PyUnicode_GET_LENGTH(unicode));
6786 /* Non-Latin-1 characters present. Defer to above function to
6787 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006788 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006789}
6790
6791PyObject*
6792PyUnicode_AsLatin1String(PyObject *unicode)
6793{
6794 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006795}
6796
6797/* --- 7-bit ASCII Codec -------------------------------------------------- */
6798
Alexander Belopolsky40018472011-02-26 01:02:56 +00006799PyObject *
6800PyUnicode_DecodeASCII(const char *s,
6801 Py_ssize_t size,
6802 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006803{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006804 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006806 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006807 Py_ssize_t startinpos;
6808 Py_ssize_t endinpos;
6809 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006810 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006811 int has_error;
6812 const unsigned char *p = (const unsigned char *)s;
6813 const unsigned char *end = p + size;
6814 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006815 PyObject *errorHandler = NULL;
6816 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006817
Guido van Rossumd57fd912000-03-10 22:53:23 +00006818 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006819 if (size == 1 && (unsigned char)s[0] < 128)
6820 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006821
Victor Stinner702c7342011-10-05 13:50:52 +02006822 has_error = 0;
6823 while (p < end && !has_error) {
6824 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6825 an explanation. */
6826 if (!((size_t) p & LONG_PTR_MASK)) {
6827 /* Help register allocation */
6828 register const unsigned char *_p = p;
6829 while (_p < aligned_end) {
6830 unsigned long value = *(unsigned long *) _p;
6831 if (value & ASCII_CHAR_MASK) {
6832 has_error = 1;
6833 break;
6834 }
6835 _p += SIZEOF_LONG;
6836 }
6837 if (_p == end)
6838 break;
6839 if (has_error)
6840 break;
6841 p = _p;
6842 }
6843 if (*p & 0x80) {
6844 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006845 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006846 }
6847 else {
6848 ++p;
6849 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006850 }
Victor Stinner702c7342011-10-05 13:50:52 +02006851 if (!has_error)
6852 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006853
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854 v = _PyUnicode_New(size);
6855 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006857 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006859 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006860 e = s + size;
6861 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 register unsigned char c = (unsigned char)*s;
6863 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006864 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 ++s;
6866 }
6867 else {
6868 startinpos = s-starts;
6869 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006870 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 if (unicode_decode_call_errorhandler(
6872 errors, &errorHandler,
6873 "ascii", "ordinal not in range(128)",
6874 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006875 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006876 goto onError;
6877 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006878 }
Victor Stinner702c7342011-10-05 13:50:52 +02006879 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6880 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882 Py_XDECREF(errorHandler);
6883 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006884#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006885 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006886 Py_DECREF(v);
6887 return NULL;
6888 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006889#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006890 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006891 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006892
Benjamin Peterson29060642009-01-31 22:14:21 +00006893 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006895 Py_XDECREF(errorHandler);
6896 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006897 return NULL;
6898}
6899
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006900/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006901PyObject *
6902PyUnicode_EncodeASCII(const Py_UNICODE *p,
6903 Py_ssize_t size,
6904 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006906 PyObject *result;
6907 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6908 if (unicode == NULL)
6909 return NULL;
6910 result = unicode_encode_ucs1(unicode, errors, 128);
6911 Py_DECREF(unicode);
6912 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006913}
6914
Alexander Belopolsky40018472011-02-26 01:02:56 +00006915PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006916_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006917{
6918 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 PyErr_BadArgument();
6920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006922 if (PyUnicode_READY(unicode) == -1)
6923 return NULL;
6924 /* Fast path: if it is an ASCII-only string, construct bytes object
6925 directly. Else defer to above function to raise the exception. */
6926 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6927 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6928 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006929 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006930}
6931
6932PyObject *
6933PyUnicode_AsASCIIString(PyObject *unicode)
6934{
6935 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936}
6937
Victor Stinner99b95382011-07-04 14:23:54 +02006938#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006939
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006940/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006941
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006942#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006943#define NEED_RETRY
6944#endif
6945
Victor Stinner3a50e702011-10-18 21:21:00 +02006946#ifndef WC_ERR_INVALID_CHARS
6947# define WC_ERR_INVALID_CHARS 0x0080
6948#endif
6949
6950static char*
6951code_page_name(UINT code_page, PyObject **obj)
6952{
6953 *obj = NULL;
6954 if (code_page == CP_ACP)
6955 return "mbcs";
6956 if (code_page == CP_UTF7)
6957 return "CP_UTF7";
6958 if (code_page == CP_UTF8)
6959 return "CP_UTF8";
6960
6961 *obj = PyBytes_FromFormat("cp%u", code_page);
6962 if (*obj == NULL)
6963 return NULL;
6964 return PyBytes_AS_STRING(*obj);
6965}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006966
Alexander Belopolsky40018472011-02-26 01:02:56 +00006967static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006968is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006969{
6970 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006972
Victor Stinner3a50e702011-10-18 21:21:00 +02006973 if (!IsDBCSLeadByteEx(code_page, *curr))
6974 return 0;
6975
6976 prev = CharPrevExA(code_page, s, curr, 0);
6977 if (prev == curr)
6978 return 1;
6979 /* FIXME: This code is limited to "true" double-byte encodings,
6980 as it assumes an incomplete character consists of a single
6981 byte. */
6982 if (curr - prev == 2)
6983 return 1;
6984 if (!IsDBCSLeadByteEx(code_page, *prev))
6985 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006986 return 0;
6987}
6988
Victor Stinner3a50e702011-10-18 21:21:00 +02006989static DWORD
6990decode_code_page_flags(UINT code_page)
6991{
6992 if (code_page == CP_UTF7) {
6993 /* The CP_UTF7 decoder only supports flags=0 */
6994 return 0;
6995 }
6996 else
6997 return MB_ERR_INVALID_CHARS;
6998}
6999
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007000/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007001 * Decode a byte string from a Windows code page into unicode object in strict
7002 * mode.
7003 *
7004 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7005 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007006 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007007static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007008decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007009 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02007010 const char *in,
7011 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007012{
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 const DWORD flags = decode_code_page_flags(code_page);
7014 Py_UNICODE *out;
7015 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007016
7017 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007018 assert(insize > 0);
7019 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7020 if (outsize <= 0)
7021 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007022
7023 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007024 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01007025 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007026 if (*v == NULL)
7027 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029 }
7030 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007031 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01007033 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007034 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036 }
7037
7038 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7040 if (outsize <= 0)
7041 goto error;
7042 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007043
Victor Stinner3a50e702011-10-18 21:21:00 +02007044error:
7045 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7046 return -2;
7047 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007048 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049}
7050
Victor Stinner3a50e702011-10-18 21:21:00 +02007051/*
7052 * Decode a byte string from a code page into unicode object with an error
7053 * handler.
7054 *
7055 * Returns consumed size if succeed, or raise a WindowsError or
7056 * UnicodeDecodeError exception and returns -1 on error.
7057 */
7058static int
7059decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007060 PyObject **v,
7061 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007062 const char *errors)
7063{
7064 const char *startin = in;
7065 const char *endin = in + size;
7066 const DWORD flags = decode_code_page_flags(code_page);
7067 /* Ideally, we should get reason from FormatMessage. This is the Windows
7068 2000 English version of the message. */
7069 const char *reason = "No mapping for the Unicode character exists "
7070 "in the target code page.";
7071 /* each step cannot decode more than 1 character, but a character can be
7072 represented as a surrogate pair */
7073 wchar_t buffer[2], *startout, *out;
7074 int insize, outsize;
7075 PyObject *errorHandler = NULL;
7076 PyObject *exc = NULL;
7077 PyObject *encoding_obj = NULL;
7078 char *encoding;
7079 DWORD err;
7080 int ret = -1;
7081
7082 assert(size > 0);
7083
7084 encoding = code_page_name(code_page, &encoding_obj);
7085 if (encoding == NULL)
7086 return -1;
7087
7088 if (errors == NULL || strcmp(errors, "strict") == 0) {
7089 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7090 UnicodeDecodeError. */
7091 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7092 if (exc != NULL) {
7093 PyCodec_StrictErrors(exc);
7094 Py_CLEAR(exc);
7095 }
7096 goto error;
7097 }
7098
7099 if (*v == NULL) {
7100 /* Create unicode object */
7101 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7102 PyErr_NoMemory();
7103 goto error;
7104 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007105 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007106 if (*v == NULL)
7107 goto error;
7108 startout = PyUnicode_AS_UNICODE(*v);
7109 }
7110 else {
7111 /* Extend unicode object */
7112 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7113 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7114 PyErr_NoMemory();
7115 goto error;
7116 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007117 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007118 goto error;
7119 startout = PyUnicode_AS_UNICODE(*v) + n;
7120 }
7121
7122 /* Decode the byte string character per character */
7123 out = startout;
7124 while (in < endin)
7125 {
7126 /* Decode a character */
7127 insize = 1;
7128 do
7129 {
7130 outsize = MultiByteToWideChar(code_page, flags,
7131 in, insize,
7132 buffer, Py_ARRAY_LENGTH(buffer));
7133 if (outsize > 0)
7134 break;
7135 err = GetLastError();
7136 if (err != ERROR_NO_UNICODE_TRANSLATION
7137 && err != ERROR_INSUFFICIENT_BUFFER)
7138 {
7139 PyErr_SetFromWindowsErr(0);
7140 goto error;
7141 }
7142 insize++;
7143 }
7144 /* 4=maximum length of a UTF-8 sequence */
7145 while (insize <= 4 && (in + insize) <= endin);
7146
7147 if (outsize <= 0) {
7148 Py_ssize_t startinpos, endinpos, outpos;
7149
7150 startinpos = in - startin;
7151 endinpos = startinpos + 1;
7152 outpos = out - PyUnicode_AS_UNICODE(*v);
7153 if (unicode_decode_call_errorhandler(
7154 errors, &errorHandler,
7155 encoding, reason,
7156 &startin, &endin, &startinpos, &endinpos, &exc, &in,
7157 v, &outpos, &out))
7158 {
7159 goto error;
7160 }
7161 }
7162 else {
7163 in += insize;
7164 memcpy(out, buffer, outsize * sizeof(wchar_t));
7165 out += outsize;
7166 }
7167 }
7168
7169 /* write a NUL character at the end */
7170 *out = 0;
7171
7172 /* Extend unicode object */
7173 outsize = out - startout;
7174 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007175 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007176 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007177 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007178
7179error:
7180 Py_XDECREF(encoding_obj);
7181 Py_XDECREF(errorHandler);
7182 Py_XDECREF(exc);
7183 return ret;
7184}
7185
Victor Stinner3a50e702011-10-18 21:21:00 +02007186static PyObject *
7187decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007188 const char *s, Py_ssize_t size,
7189 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190{
Victor Stinner76a31a62011-11-04 00:05:13 +01007191 PyObject *v = NULL;
7192 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007193
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 if (code_page < 0) {
7195 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7196 return NULL;
7197 }
7198
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007199 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007200 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007201
Victor Stinner76a31a62011-11-04 00:05:13 +01007202 do
7203 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007204#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007205 if (size > INT_MAX) {
7206 chunk_size = INT_MAX;
7207 final = 0;
7208 done = 0;
7209 }
7210 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007212 {
7213 chunk_size = (int)size;
7214 final = (consumed == NULL);
7215 done = 1;
7216 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007217
Victor Stinner76a31a62011-11-04 00:05:13 +01007218 /* Skip trailing lead-byte unless 'final' is set */
7219 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7220 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007221
Victor Stinner76a31a62011-11-04 00:05:13 +01007222 if (chunk_size == 0 && done) {
7223 if (v != NULL)
7224 break;
7225 Py_INCREF(unicode_empty);
7226 return unicode_empty;
7227 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007228
Victor Stinner76a31a62011-11-04 00:05:13 +01007229
7230 converted = decode_code_page_strict(code_page, &v,
7231 s, chunk_size);
7232 if (converted == -2)
7233 converted = decode_code_page_errors(code_page, &v,
7234 s, chunk_size,
7235 errors);
7236 assert(converted != 0);
7237
7238 if (converted < 0) {
7239 Py_XDECREF(v);
7240 return NULL;
7241 }
7242
7243 if (consumed)
7244 *consumed += converted;
7245
7246 s += converted;
7247 size -= converted;
7248 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007249
Victor Stinner17efeed2011-10-04 20:05:46 +02007250#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007251 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007252 Py_DECREF(v);
7253 return NULL;
7254 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007255#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007256 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007257 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007258}
7259
Alexander Belopolsky40018472011-02-26 01:02:56 +00007260PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007261PyUnicode_DecodeCodePageStateful(int code_page,
7262 const char *s,
7263 Py_ssize_t size,
7264 const char *errors,
7265 Py_ssize_t *consumed)
7266{
7267 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7268}
7269
7270PyObject *
7271PyUnicode_DecodeMBCSStateful(const char *s,
7272 Py_ssize_t size,
7273 const char *errors,
7274 Py_ssize_t *consumed)
7275{
7276 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7277}
7278
7279PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007280PyUnicode_DecodeMBCS(const char *s,
7281 Py_ssize_t size,
7282 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007283{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007284 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7285}
7286
Victor Stinner3a50e702011-10-18 21:21:00 +02007287static DWORD
7288encode_code_page_flags(UINT code_page, const char *errors)
7289{
7290 if (code_page == CP_UTF8) {
7291 if (winver.dwMajorVersion >= 6)
7292 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7293 and later */
7294 return WC_ERR_INVALID_CHARS;
7295 else
7296 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7297 return 0;
7298 }
7299 else if (code_page == CP_UTF7) {
7300 /* CP_UTF7 only supports flags=0 */
7301 return 0;
7302 }
7303 else {
7304 if (errors != NULL && strcmp(errors, "replace") == 0)
7305 return 0;
7306 else
7307 return WC_NO_BEST_FIT_CHARS;
7308 }
7309}
7310
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007311/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 * Encode a Unicode string to a Windows code page into a byte string in strict
7313 * mode.
7314 *
7315 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7316 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007317 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007318static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007319encode_code_page_strict(UINT code_page, PyObject **outbytes,
7320 const Py_UNICODE *p, const int size,
7321 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007322{
Victor Stinner554f3f02010-06-16 23:33:54 +00007323 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007324 BOOL *pusedDefaultChar = &usedDefaultChar;
7325 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007326 PyObject *exc = NULL;
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 const DWORD flags = encode_code_page_flags(code_page, NULL);
7328 char *out;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007329
Victor Stinner3a50e702011-10-18 21:21:00 +02007330 assert(size > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007331
Victor Stinner3a50e702011-10-18 21:21:00 +02007332 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007333 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007334 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007335 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007336
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007337 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 outsize = WideCharToMultiByte(code_page, flags,
7339 p, size,
7340 NULL, 0,
7341 NULL, pusedDefaultChar);
7342 if (outsize <= 0)
7343 goto error;
7344 /* If we used a default char, then we failed! */
7345 if (pusedDefaultChar && *pusedDefaultChar)
7346 return -2;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007347
Victor Stinner3a50e702011-10-18 21:21:00 +02007348 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007349 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007350 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7351 if (*outbytes == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007352 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007354 }
7355 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007356 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007357 const Py_ssize_t n = PyBytes_Size(*outbytes);
7358 if (outsize > PY_SSIZE_T_MAX - n) {
7359 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007360 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007361 }
7362 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7363 return -1;
7364 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007365 }
7366
7367 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007368 outsize = WideCharToMultiByte(code_page, flags,
7369 p, size,
7370 out, outsize,
7371 NULL, pusedDefaultChar);
7372 if (outsize <= 0)
7373 goto error;
7374 if (pusedDefaultChar && *pusedDefaultChar)
7375 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007376 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007377
Victor Stinner3a50e702011-10-18 21:21:00 +02007378error:
7379 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7380 return -2;
7381 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007382 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007383}
7384
Victor Stinner3a50e702011-10-18 21:21:00 +02007385/*
7386 * Encode a Unicode string to a Windows code page into a byte string using a
7387 * error handler.
7388 *
7389 * Returns consumed characters if succeed, or raise a WindowsError and returns
7390 * -1 on other error.
7391 */
7392static int
7393encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007394 PyObject *unicode, Py_ssize_t unicode_offset,
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 const Py_UNICODE *in, const int insize,
7396 const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007397{
Victor Stinner3a50e702011-10-18 21:21:00 +02007398 const DWORD flags = encode_code_page_flags(code_page, errors);
7399 const Py_UNICODE *startin = in;
7400 const Py_UNICODE *endin = in + insize;
7401 /* Ideally, we should get reason from FormatMessage. This is the Windows
7402 2000 English version of the message. */
7403 const char *reason = "invalid character";
7404 /* 4=maximum length of a UTF-8 sequence */
7405 char buffer[4];
7406 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7407 Py_ssize_t outsize;
7408 char *out;
7409 int charsize;
7410 PyObject *errorHandler = NULL;
7411 PyObject *exc = NULL;
7412 PyObject *encoding_obj = NULL;
7413 char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007414 Py_ssize_t startpos, newpos, newoutsize;
7415 PyObject *rep;
7416 int ret = -1;
7417
7418 assert(insize > 0);
7419
7420 encoding = code_page_name(code_page, &encoding_obj);
7421 if (encoding == NULL)
7422 return -1;
7423
7424 if (errors == NULL || strcmp(errors, "strict") == 0) {
7425 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7426 then we raise a UnicodeEncodeError. */
7427 make_encode_exception(&exc, encoding, in, insize, 0, 0, reason);
7428 if (exc != NULL) {
7429 PyCodec_StrictErrors(exc);
7430 Py_DECREF(exc);
7431 }
7432 Py_XDECREF(encoding_obj);
7433 return -1;
7434 }
7435
7436 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7437 pusedDefaultChar = &usedDefaultChar;
7438 else
7439 pusedDefaultChar = NULL;
7440
7441 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7442 PyErr_NoMemory();
7443 goto error;
7444 }
7445 outsize = insize * Py_ARRAY_LENGTH(buffer);
7446
7447 if (*outbytes == NULL) {
7448 /* Create string object */
7449 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7450 if (*outbytes == NULL)
7451 goto error;
7452 out = PyBytes_AS_STRING(*outbytes);
7453 }
7454 else {
7455 /* Extend string object */
7456 Py_ssize_t n = PyBytes_Size(*outbytes);
7457 if (n > PY_SSIZE_T_MAX - outsize) {
7458 PyErr_NoMemory();
7459 goto error;
7460 }
7461 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7462 goto error;
7463 out = PyBytes_AS_STRING(*outbytes) + n;
7464 }
7465
7466 /* Encode the string character per character */
7467 while (in < endin)
7468 {
7469 if ((in + 2) <= endin
7470 && 0xD800 <= in[0] && in[0] <= 0xDBFF
7471 && 0xDC00 <= in[1] && in[1] <= 0xDFFF)
7472 charsize = 2;
7473 else
7474 charsize = 1;
7475
7476 outsize = WideCharToMultiByte(code_page, flags,
7477 in, charsize,
7478 buffer, Py_ARRAY_LENGTH(buffer),
7479 NULL, pusedDefaultChar);
7480 if (outsize > 0) {
7481 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7482 {
7483 in += charsize;
7484 memcpy(out, buffer, outsize);
7485 out += outsize;
7486 continue;
7487 }
7488 }
7489 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7490 PyErr_SetFromWindowsErr(0);
7491 goto error;
7492 }
7493
7494 charsize = Py_MAX(charsize - 1, 1);
Victor Stinner7581cef2011-11-03 22:32:33 +01007495 startpos = unicode_offset + in - startin;
Victor Stinner3a50e702011-10-18 21:21:00 +02007496 rep = unicode_encode_call_errorhandler(
7497 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007498 unicode, &exc,
Victor Stinner3a50e702011-10-18 21:21:00 +02007499 startpos, startpos + charsize, &newpos);
7500 if (rep == NULL)
7501 goto error;
Victor Stinner7581cef2011-11-03 22:32:33 +01007502 in += (newpos - startpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007503
7504 if (PyBytes_Check(rep)) {
7505 outsize = PyBytes_GET_SIZE(rep);
7506 if (outsize != 1) {
7507 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7508 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7509 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7510 Py_DECREF(rep);
7511 goto error;
7512 }
7513 out = PyBytes_AS_STRING(*outbytes) + offset;
7514 }
7515 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7516 out += outsize;
7517 }
7518 else {
7519 Py_ssize_t i;
7520 enum PyUnicode_Kind kind;
7521 void *data;
7522
7523 if (PyUnicode_READY(rep) < 0) {
7524 Py_DECREF(rep);
7525 goto error;
7526 }
7527
7528 outsize = PyUnicode_GET_LENGTH(rep);
7529 if (outsize != 1) {
7530 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7531 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7532 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7533 Py_DECREF(rep);
7534 goto error;
7535 }
7536 out = PyBytes_AS_STRING(*outbytes) + offset;
7537 }
7538 kind = PyUnicode_KIND(rep);
7539 data = PyUnicode_DATA(rep);
7540 for (i=0; i < outsize; i++) {
7541 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7542 if (ch > 127) {
7543 raise_encode_exception(&exc,
7544 encoding,
7545 startin, insize,
7546 startpos, startpos + charsize,
7547 "unable to encode error handler result to ASCII");
7548 Py_DECREF(rep);
7549 goto error;
7550 }
7551 *out = (unsigned char)ch;
7552 out++;
7553 }
7554 }
7555 Py_DECREF(rep);
7556 }
7557 /* write a NUL byte */
7558 *out = 0;
7559 outsize = out - PyBytes_AS_STRING(*outbytes);
7560 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7561 if (_PyBytes_Resize(outbytes, outsize) < 0)
7562 goto error;
7563 ret = 0;
7564
7565error:
7566 Py_XDECREF(encoding_obj);
7567 Py_XDECREF(errorHandler);
7568 Py_XDECREF(exc);
7569 return ret;
7570}
7571
Victor Stinner3a50e702011-10-18 21:21:00 +02007572static PyObject *
7573encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007574 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 const char *errors)
7576{
Victor Stinner7581cef2011-11-03 22:32:33 +01007577 const Py_UNICODE *p;
7578 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007579 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007580 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007581 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007582
7583 p = PyUnicode_AsUnicodeAndSize(unicode, &size);
7584 if (p == NULL)
7585 return NULL;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007586
Victor Stinner3a50e702011-10-18 21:21:00 +02007587 if (code_page < 0) {
7588 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7589 return NULL;
7590 }
7591
Victor Stinner76a31a62011-11-04 00:05:13 +01007592 if (size == 0)
7593 return PyBytes_FromStringAndSize(NULL, 0);
7594
Victor Stinner7581cef2011-11-03 22:32:33 +01007595 offset = 0;
7596 do
7597 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007598#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007599 if (size > INT_MAX) {
Victor Stinner7581cef2011-11-03 22:32:33 +01007600 chunk_len = INT_MAX;
Victor Stinner76a31a62011-11-04 00:05:13 +01007601 done = 0;
7602 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007603 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007604#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007605 {
Victor Stinner7581cef2011-11-03 22:32:33 +01007606 chunk_len = (int)size;
Victor Stinner76a31a62011-11-04 00:05:13 +01007607 done = 1;
7608 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007609
Victor Stinner76a31a62011-11-04 00:05:13 +01007610 ret = encode_code_page_strict(code_page, &outbytes,
7611 p, chunk_len,
7612 errors);
7613 if (ret == -2)
7614 ret = encode_code_page_errors(code_page, &outbytes,
7615 unicode, offset,
7616 p, chunk_len,
7617 errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007618 if (ret < 0) {
7619 Py_XDECREF(outbytes);
7620 return NULL;
7621 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007622
Victor Stinner7581cef2011-11-03 22:32:33 +01007623 p += chunk_len;
7624 offset += chunk_len;
7625 size -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007626 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007627
Victor Stinner3a50e702011-10-18 21:21:00 +02007628 return outbytes;
7629}
7630
7631PyObject *
7632PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7633 Py_ssize_t size,
7634 const char *errors)
7635{
Victor Stinner7581cef2011-11-03 22:32:33 +01007636 PyObject *unicode, *res;
7637 unicode = PyUnicode_FromUnicode(p, size);
7638 if (unicode == NULL)
7639 return NULL;
7640 res = encode_code_page(CP_ACP, unicode, errors);
7641 Py_DECREF(unicode);
7642 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007643}
7644
7645PyObject *
7646PyUnicode_EncodeCodePage(int code_page,
7647 PyObject *unicode,
7648 const char *errors)
7649{
Victor Stinner7581cef2011-11-03 22:32:33 +01007650 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007651}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007652
Alexander Belopolsky40018472011-02-26 01:02:56 +00007653PyObject *
7654PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007655{
7656 if (!PyUnicode_Check(unicode)) {
7657 PyErr_BadArgument();
7658 return NULL;
7659 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007660 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007661}
7662
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007663#undef NEED_RETRY
7664
Victor Stinner99b95382011-07-04 14:23:54 +02007665#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007666
Guido van Rossumd57fd912000-03-10 22:53:23 +00007667/* --- Character Mapping Codec -------------------------------------------- */
7668
Alexander Belopolsky40018472011-02-26 01:02:56 +00007669PyObject *
7670PyUnicode_DecodeCharmap(const char *s,
7671 Py_ssize_t size,
7672 PyObject *mapping,
7673 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007674{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007675 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007676 Py_ssize_t startinpos;
7677 Py_ssize_t endinpos;
7678 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007679 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007680 PyUnicodeObject *v;
7681 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007682 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007683 PyObject *errorHandler = NULL;
7684 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007685 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007686 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007687
Guido van Rossumd57fd912000-03-10 22:53:23 +00007688 /* Default to Latin-1 */
7689 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007690 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007691
7692 v = _PyUnicode_New(size);
7693 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007695 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007696 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007697 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007698 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007699 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007700 mapstring = PyUnicode_AS_UNICODE(mapping);
7701 maplen = PyUnicode_GET_SIZE(mapping);
7702 while (s < e) {
7703 unsigned char ch = *s;
7704 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007705
Benjamin Peterson29060642009-01-31 22:14:21 +00007706 if (ch < maplen)
7707 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007708
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 if (x == 0xfffe) {
7710 /* undefined mapping */
7711 outpos = p-PyUnicode_AS_UNICODE(v);
7712 startinpos = s-starts;
7713 endinpos = startinpos+1;
7714 if (unicode_decode_call_errorhandler(
7715 errors, &errorHandler,
7716 "charmap", "character maps to <undefined>",
7717 &starts, &e, &startinpos, &endinpos, &exc, &s,
7718 &v, &outpos, &p)) {
7719 goto onError;
7720 }
7721 continue;
7722 }
7723 *p++ = x;
7724 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007725 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007726 }
7727 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007728 while (s < e) {
7729 unsigned char ch = *s;
7730 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007731
Benjamin Peterson29060642009-01-31 22:14:21 +00007732 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7733 w = PyLong_FromLong((long)ch);
7734 if (w == NULL)
7735 goto onError;
7736 x = PyObject_GetItem(mapping, w);
7737 Py_DECREF(w);
7738 if (x == NULL) {
7739 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7740 /* No mapping found means: mapping is undefined. */
7741 PyErr_Clear();
7742 x = Py_None;
7743 Py_INCREF(x);
7744 } else
7745 goto onError;
7746 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007747
Benjamin Peterson29060642009-01-31 22:14:21 +00007748 /* Apply mapping */
7749 if (PyLong_Check(x)) {
7750 long value = PyLong_AS_LONG(x);
7751 if (value < 0 || value > 65535) {
7752 PyErr_SetString(PyExc_TypeError,
7753 "character mapping must be in range(65536)");
7754 Py_DECREF(x);
7755 goto onError;
7756 }
7757 *p++ = (Py_UNICODE)value;
7758 }
7759 else if (x == Py_None) {
7760 /* undefined mapping */
7761 outpos = p-PyUnicode_AS_UNICODE(v);
7762 startinpos = s-starts;
7763 endinpos = startinpos+1;
7764 if (unicode_decode_call_errorhandler(
7765 errors, &errorHandler,
7766 "charmap", "character maps to <undefined>",
7767 &starts, &e, &startinpos, &endinpos, &exc, &s,
7768 &v, &outpos, &p)) {
7769 Py_DECREF(x);
7770 goto onError;
7771 }
7772 Py_DECREF(x);
7773 continue;
7774 }
7775 else if (PyUnicode_Check(x)) {
7776 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007777
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 if (targetsize == 1)
7779 /* 1-1 mapping */
7780 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007781
Benjamin Peterson29060642009-01-31 22:14:21 +00007782 else if (targetsize > 1) {
7783 /* 1-n mapping */
7784 if (targetsize > extrachars) {
7785 /* resize first */
7786 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7787 Py_ssize_t needed = (targetsize - extrachars) + \
7788 (targetsize << 2);
7789 extrachars += needed;
7790 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007791 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007792 PyUnicode_GET_SIZE(v) + needed) < 0) {
7793 Py_DECREF(x);
7794 goto onError;
7795 }
7796 p = PyUnicode_AS_UNICODE(v) + oldpos;
7797 }
7798 Py_UNICODE_COPY(p,
7799 PyUnicode_AS_UNICODE(x),
7800 targetsize);
7801 p += targetsize;
7802 extrachars -= targetsize;
7803 }
7804 /* 1-0 mapping: skip the character */
7805 }
7806 else {
7807 /* wrong return value */
7808 PyErr_SetString(PyExc_TypeError,
7809 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007810 Py_DECREF(x);
7811 goto onError;
7812 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007813 Py_DECREF(x);
7814 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007815 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007816 }
7817 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007818 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007819 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007820 Py_XDECREF(errorHandler);
7821 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007822#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007823 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007824 Py_DECREF(v);
7825 return NULL;
7826 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007827#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007828 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007829 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007830
Benjamin Peterson29060642009-01-31 22:14:21 +00007831 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007832 Py_XDECREF(errorHandler);
7833 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007834 Py_XDECREF(v);
7835 return NULL;
7836}
7837
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838/* Charmap encoding: the lookup table */
7839
Alexander Belopolsky40018472011-02-26 01:02:56 +00007840struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007841 PyObject_HEAD
7842 unsigned char level1[32];
7843 int count2, count3;
7844 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007845};
7846
7847static PyObject*
7848encoding_map_size(PyObject *obj, PyObject* args)
7849{
7850 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007851 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007852 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853}
7854
7855static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007856 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007857 PyDoc_STR("Return the size (in bytes) of this object") },
7858 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007859};
7860
7861static void
7862encoding_map_dealloc(PyObject* o)
7863{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007864 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007865}
7866
7867static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007868 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007869 "EncodingMap", /*tp_name*/
7870 sizeof(struct encoding_map), /*tp_basicsize*/
7871 0, /*tp_itemsize*/
7872 /* methods */
7873 encoding_map_dealloc, /*tp_dealloc*/
7874 0, /*tp_print*/
7875 0, /*tp_getattr*/
7876 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007877 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007878 0, /*tp_repr*/
7879 0, /*tp_as_number*/
7880 0, /*tp_as_sequence*/
7881 0, /*tp_as_mapping*/
7882 0, /*tp_hash*/
7883 0, /*tp_call*/
7884 0, /*tp_str*/
7885 0, /*tp_getattro*/
7886 0, /*tp_setattro*/
7887 0, /*tp_as_buffer*/
7888 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7889 0, /*tp_doc*/
7890 0, /*tp_traverse*/
7891 0, /*tp_clear*/
7892 0, /*tp_richcompare*/
7893 0, /*tp_weaklistoffset*/
7894 0, /*tp_iter*/
7895 0, /*tp_iternext*/
7896 encoding_map_methods, /*tp_methods*/
7897 0, /*tp_members*/
7898 0, /*tp_getset*/
7899 0, /*tp_base*/
7900 0, /*tp_dict*/
7901 0, /*tp_descr_get*/
7902 0, /*tp_descr_set*/
7903 0, /*tp_dictoffset*/
7904 0, /*tp_init*/
7905 0, /*tp_alloc*/
7906 0, /*tp_new*/
7907 0, /*tp_free*/
7908 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007909};
7910
7911PyObject*
7912PyUnicode_BuildEncodingMap(PyObject* string)
7913{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007914 PyObject *result;
7915 struct encoding_map *mresult;
7916 int i;
7917 int need_dict = 0;
7918 unsigned char level1[32];
7919 unsigned char level2[512];
7920 unsigned char *mlevel1, *mlevel2, *mlevel3;
7921 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007922 int kind;
7923 void *data;
7924 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007926 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007927 PyErr_BadArgument();
7928 return NULL;
7929 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007930 kind = PyUnicode_KIND(string);
7931 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007932 memset(level1, 0xFF, sizeof level1);
7933 memset(level2, 0xFF, sizeof level2);
7934
7935 /* If there isn't a one-to-one mapping of NULL to \0,
7936 or if there are non-BMP characters, we need to use
7937 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007938 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007939 need_dict = 1;
7940 for (i = 1; i < 256; i++) {
7941 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007942 ch = PyUnicode_READ(kind, data, i);
7943 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007944 need_dict = 1;
7945 break;
7946 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007947 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007948 /* unmapped character */
7949 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007950 l1 = ch >> 11;
7951 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 if (level1[l1] == 0xFF)
7953 level1[l1] = count2++;
7954 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007955 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007956 }
7957
7958 if (count2 >= 0xFF || count3 >= 0xFF)
7959 need_dict = 1;
7960
7961 if (need_dict) {
7962 PyObject *result = PyDict_New();
7963 PyObject *key, *value;
7964 if (!result)
7965 return NULL;
7966 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007967 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007968 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969 if (!key || !value)
7970 goto failed1;
7971 if (PyDict_SetItem(result, key, value) == -1)
7972 goto failed1;
7973 Py_DECREF(key);
7974 Py_DECREF(value);
7975 }
7976 return result;
7977 failed1:
7978 Py_XDECREF(key);
7979 Py_XDECREF(value);
7980 Py_DECREF(result);
7981 return NULL;
7982 }
7983
7984 /* Create a three-level trie */
7985 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7986 16*count2 + 128*count3 - 1);
7987 if (!result)
7988 return PyErr_NoMemory();
7989 PyObject_Init(result, &EncodingMapType);
7990 mresult = (struct encoding_map*)result;
7991 mresult->count2 = count2;
7992 mresult->count3 = count3;
7993 mlevel1 = mresult->level1;
7994 mlevel2 = mresult->level23;
7995 mlevel3 = mresult->level23 + 16*count2;
7996 memcpy(mlevel1, level1, 32);
7997 memset(mlevel2, 0xFF, 16*count2);
7998 memset(mlevel3, 0, 128*count3);
7999 count3 = 0;
8000 for (i = 1; i < 256; i++) {
8001 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008002 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008003 /* unmapped character */
8004 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008005 o1 = PyUnicode_READ(kind, data, i)>>11;
8006 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008007 i2 = 16*mlevel1[o1] + o2;
8008 if (mlevel2[i2] == 0xFF)
8009 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008010 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008011 i3 = 128*mlevel2[i2] + o3;
8012 mlevel3[i3] = i;
8013 }
8014 return result;
8015}
8016
8017static int
8018encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
8019{
8020 struct encoding_map *map = (struct encoding_map*)mapping;
8021 int l1 = c>>11;
8022 int l2 = (c>>7) & 0xF;
8023 int l3 = c & 0x7F;
8024 int i;
8025
8026#ifdef Py_UNICODE_WIDE
8027 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008028 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029 }
8030#endif
8031 if (c == 0)
8032 return 0;
8033 /* level 1*/
8034 i = map->level1[l1];
8035 if (i == 0xFF) {
8036 return -1;
8037 }
8038 /* level 2*/
8039 i = map->level23[16*i+l2];
8040 if (i == 0xFF) {
8041 return -1;
8042 }
8043 /* level 3 */
8044 i = map->level23[16*map->count2 + 128*i + l3];
8045 if (i == 0) {
8046 return -1;
8047 }
8048 return i;
8049}
8050
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008051/* Lookup the character ch in the mapping. If the character
8052 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008053 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008054static PyObject *
8055charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008056{
Christian Heimes217cfd12007-12-02 14:31:20 +00008057 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008058 PyObject *x;
8059
8060 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008061 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008062 x = PyObject_GetItem(mapping, w);
8063 Py_DECREF(w);
8064 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008065 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8066 /* No mapping found means: mapping is undefined. */
8067 PyErr_Clear();
8068 x = Py_None;
8069 Py_INCREF(x);
8070 return x;
8071 } else
8072 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008073 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008074 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008075 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008076 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008077 long value = PyLong_AS_LONG(x);
8078 if (value < 0 || value > 255) {
8079 PyErr_SetString(PyExc_TypeError,
8080 "character mapping must be in range(256)");
8081 Py_DECREF(x);
8082 return NULL;
8083 }
8084 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008085 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008086 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008087 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008088 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 /* wrong return value */
8090 PyErr_Format(PyExc_TypeError,
8091 "character mapping must return integer, bytes or None, not %.400s",
8092 x->ob_type->tp_name);
8093 Py_DECREF(x);
8094 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008095 }
8096}
8097
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008099charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008100{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008101 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8102 /* exponentially overallocate to minimize reallocations */
8103 if (requiredsize < 2*outsize)
8104 requiredsize = 2*outsize;
8105 if (_PyBytes_Resize(outobj, requiredsize))
8106 return -1;
8107 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008108}
8109
Benjamin Peterson14339b62009-01-31 16:36:08 +00008110typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008112} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008113/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008114 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008115 space is available. Return a new reference to the object that
8116 was put in the output buffer, or Py_None, if the mapping was undefined
8117 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008118 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008119static charmapencode_result
8120charmapencode_output(Py_UNICODE c, PyObject *mapping,
8121 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008122{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008123 PyObject *rep;
8124 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008125 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008126
Christian Heimes90aa7642007-12-19 02:45:37 +00008127 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008129 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 if (res == -1)
8131 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008132 if (outsize<requiredsize)
8133 if (charmapencode_resize(outobj, outpos, requiredsize))
8134 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008135 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008136 outstart[(*outpos)++] = (char)res;
8137 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008138 }
8139
8140 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008141 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008144 Py_DECREF(rep);
8145 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008146 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 if (PyLong_Check(rep)) {
8148 Py_ssize_t requiredsize = *outpos+1;
8149 if (outsize<requiredsize)
8150 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8151 Py_DECREF(rep);
8152 return enc_EXCEPTION;
8153 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008154 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008155 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 else {
8158 const char *repchars = PyBytes_AS_STRING(rep);
8159 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8160 Py_ssize_t requiredsize = *outpos+repsize;
8161 if (outsize<requiredsize)
8162 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8163 Py_DECREF(rep);
8164 return enc_EXCEPTION;
8165 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008166 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 memcpy(outstart + *outpos, repchars, repsize);
8168 *outpos += repsize;
8169 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008170 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008171 Py_DECREF(rep);
8172 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008173}
8174
8175/* handle an error in PyUnicode_EncodeCharmap
8176 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008177static int
8178charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008179 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008180 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008181 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008182 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008183{
8184 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008185 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008186 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008187 Py_UNICODE *uni2;
8188 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008189 Py_ssize_t collstartpos = *inpos;
8190 Py_ssize_t collendpos = *inpos+1;
8191 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008192 char *encoding = "charmap";
8193 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008194 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008195 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008196 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 if (PyUnicode_READY(unicode) < 0)
8199 return -1;
8200 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008201 /* find all unencodable characters */
8202 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008203 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008204 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008205 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008206 val = encoding_map_lookup(ch, mapping);
8207 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008208 break;
8209 ++collendpos;
8210 continue;
8211 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008212
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008213 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8214 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008215 if (rep==NULL)
8216 return -1;
8217 else if (rep!=Py_None) {
8218 Py_DECREF(rep);
8219 break;
8220 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008221 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008222 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 }
8224 /* cache callback name lookup
8225 * (if not done yet, i.e. it's the first error) */
8226 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008227 if ((errors==NULL) || (!strcmp(errors, "strict")))
8228 *known_errorHandler = 1;
8229 else if (!strcmp(errors, "replace"))
8230 *known_errorHandler = 2;
8231 else if (!strcmp(errors, "ignore"))
8232 *known_errorHandler = 3;
8233 else if (!strcmp(errors, "xmlcharrefreplace"))
8234 *known_errorHandler = 4;
8235 else
8236 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 }
8238 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008239 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008240 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008241 return -1;
8242 case 2: /* replace */
8243 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 x = charmapencode_output('?', mapping, res, respos);
8245 if (x==enc_EXCEPTION) {
8246 return -1;
8247 }
8248 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008249 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 return -1;
8251 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252 }
8253 /* fall through */
8254 case 3: /* ignore */
8255 *inpos = collendpos;
8256 break;
8257 case 4: /* xmlcharrefreplace */
8258 /* generate replacement (temporarily (mis)uses p) */
8259 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008260 char buffer[2+29+1+1];
8261 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008262 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 for (cp = buffer; *cp; ++cp) {
8264 x = charmapencode_output(*cp, mapping, res, respos);
8265 if (x==enc_EXCEPTION)
8266 return -1;
8267 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008268 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 return -1;
8270 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008271 }
8272 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008273 *inpos = collendpos;
8274 break;
8275 default:
8276 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008277 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008279 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008281 if (PyBytes_Check(repunicode)) {
8282 /* Directly copy bytes result to output. */
8283 Py_ssize_t outsize = PyBytes_Size(*res);
8284 Py_ssize_t requiredsize;
8285 repsize = PyBytes_Size(repunicode);
8286 requiredsize = *respos + repsize;
8287 if (requiredsize > outsize)
8288 /* Make room for all additional bytes. */
8289 if (charmapencode_resize(res, respos, requiredsize)) {
8290 Py_DECREF(repunicode);
8291 return -1;
8292 }
8293 memcpy(PyBytes_AsString(*res) + *respos,
8294 PyBytes_AsString(repunicode), repsize);
8295 *respos += repsize;
8296 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008297 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008298 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008299 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008300 /* generate replacement */
8301 repsize = PyUnicode_GET_SIZE(repunicode);
8302 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 x = charmapencode_output(*uni2, mapping, res, respos);
8304 if (x==enc_EXCEPTION) {
8305 return -1;
8306 }
8307 else if (x==enc_FAILED) {
8308 Py_DECREF(repunicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008309 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008310 return -1;
8311 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008312 }
8313 *inpos = newpos;
8314 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315 }
8316 return 0;
8317}
8318
Alexander Belopolsky40018472011-02-26 01:02:56 +00008319PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008320_PyUnicode_EncodeCharmap(PyObject *unicode,
8321 PyObject *mapping,
8322 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008323{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324 /* output object */
8325 PyObject *res = NULL;
8326 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008327 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008328 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008330 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 PyObject *errorHandler = NULL;
8332 PyObject *exc = NULL;
8333 /* the following variable is used for caching string comparisons
8334 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8335 * 3=ignore, 4=xmlcharrefreplace */
8336 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008337
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008338 if (PyUnicode_READY(unicode) < 0)
8339 return NULL;
8340 size = PyUnicode_GET_LENGTH(unicode);
8341
Guido van Rossumd57fd912000-03-10 22:53:23 +00008342 /* Default to Latin-1 */
8343 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008344 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008345
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008346 /* allocate enough for a simple encoding without
8347 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008348 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349 if (res == NULL)
8350 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008351 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008353
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008354 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008355 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008357 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 if (x==enc_EXCEPTION) /* error */
8359 goto onError;
8360 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008361 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 &exc,
8363 &known_errorHandler, &errorHandler, errors,
8364 &res, &respos)) {
8365 goto onError;
8366 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 else
8369 /* done with this character => adjust input position */
8370 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008371 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008372
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008374 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008375 if (_PyBytes_Resize(&res, respos) < 0)
8376 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008377
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 Py_XDECREF(exc);
8379 Py_XDECREF(errorHandler);
8380 return res;
8381
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008383 Py_XDECREF(res);
8384 Py_XDECREF(exc);
8385 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008386 return NULL;
8387}
8388
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008389/* Deprecated */
8390PyObject *
8391PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8392 Py_ssize_t size,
8393 PyObject *mapping,
8394 const char *errors)
8395{
8396 PyObject *result;
8397 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8398 if (unicode == NULL)
8399 return NULL;
8400 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8401 Py_DECREF(unicode);
8402 return NULL;
8403}
8404
Alexander Belopolsky40018472011-02-26 01:02:56 +00008405PyObject *
8406PyUnicode_AsCharmapString(PyObject *unicode,
8407 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008408{
8409 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 PyErr_BadArgument();
8411 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008412 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008413 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008414}
8415
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008417static void
8418make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008419 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008420 Py_ssize_t startpos, Py_ssize_t endpos,
8421 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008422{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008423 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008424 *exceptionObject = _PyUnicodeTranslateError_Create(
8425 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008426 }
8427 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8429 goto onError;
8430 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8431 goto onError;
8432 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8433 goto onError;
8434 return;
8435 onError:
8436 Py_DECREF(*exceptionObject);
8437 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008438 }
8439}
8440
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008442static void
8443raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008444 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008445 Py_ssize_t startpos, Py_ssize_t endpos,
8446 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008447{
8448 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008451 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452}
8453
8454/* error handling callback helper:
8455 build arguments, call the callback and check the arguments,
8456 put the result into newpos and return the replacement string, which
8457 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008458static PyObject *
8459unicode_translate_call_errorhandler(const char *errors,
8460 PyObject **errorHandler,
8461 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008463 Py_ssize_t startpos, Py_ssize_t endpos,
8464 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008466 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008468 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469 PyObject *restuple;
8470 PyObject *resunicode;
8471
8472 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008475 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008476 }
8477
8478 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008479 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482
8483 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008484 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008488 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 Py_DECREF(restuple);
8490 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008491 }
8492 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 &resunicode, &i_newpos)) {
8494 Py_DECREF(restuple);
8495 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008497 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008499 else
8500 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008501 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8503 Py_DECREF(restuple);
8504 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008505 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 Py_INCREF(resunicode);
8507 Py_DECREF(restuple);
8508 return resunicode;
8509}
8510
8511/* Lookup the character ch in the mapping and put the result in result,
8512 which must be decrefed by the caller.
8513 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008514static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516{
Christian Heimes217cfd12007-12-02 14:31:20 +00008517 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 PyObject *x;
8519
8520 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008521 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008522 x = PyObject_GetItem(mapping, w);
8523 Py_DECREF(w);
8524 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8526 /* No mapping found means: use 1:1 mapping. */
8527 PyErr_Clear();
8528 *result = NULL;
8529 return 0;
8530 } else
8531 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 }
8533 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 *result = x;
8535 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008537 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 long value = PyLong_AS_LONG(x);
8539 long max = PyUnicode_GetMax();
8540 if (value < 0 || value > max) {
8541 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008542 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008543 Py_DECREF(x);
8544 return -1;
8545 }
8546 *result = x;
8547 return 0;
8548 }
8549 else if (PyUnicode_Check(x)) {
8550 *result = x;
8551 return 0;
8552 }
8553 else {
8554 /* wrong return value */
8555 PyErr_SetString(PyExc_TypeError,
8556 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008557 Py_DECREF(x);
8558 return -1;
8559 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560}
8561/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 if not reallocate and adjust various state variables.
8563 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008564static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008565charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008566 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008567{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008568 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008569 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 /* exponentially overallocate to minimize reallocations */
8571 if (requiredsize < 2 * oldsize)
8572 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008573 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8574 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008576 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008577 }
8578 return 0;
8579}
8580/* lookup the character, put the result in the output string and adjust
8581 various state variables. Return a new reference to the object that
8582 was put in the output buffer in *result, or Py_None, if the mapping was
8583 undefined (in which case no character was written).
8584 The called must decref result.
8585 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008586static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8588 PyObject *mapping, Py_UCS4 **output,
8589 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008590 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008591{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8593 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008595 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008596 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008597 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008598 }
8599 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008600 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008601 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008603 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008604 }
8605 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606 Py_ssize_t repsize;
8607 if (PyUnicode_READY(*res) == -1)
8608 return -1;
8609 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 if (repsize==1) {
8611 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 }
8614 else if (repsize!=0) {
8615 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 Py_ssize_t requiredsize = *opos +
8617 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008618 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 Py_ssize_t i;
8620 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 for(i = 0; i < repsize; i++)
8623 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008625 }
8626 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008628 return 0;
8629}
8630
Alexander Belopolsky40018472011-02-26 01:02:56 +00008631PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632_PyUnicode_TranslateCharmap(PyObject *input,
8633 PyObject *mapping,
8634 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008635{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 /* input object */
8637 char *idata;
8638 Py_ssize_t size, i;
8639 int kind;
8640 /* output buffer */
8641 Py_UCS4 *output = NULL;
8642 Py_ssize_t osize;
8643 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008646 char *reason = "character maps to <undefined>";
8647 PyObject *errorHandler = NULL;
8648 PyObject *exc = NULL;
8649 /* the following variable is used for caching string comparisons
8650 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8651 * 3=ignore, 4=xmlcharrefreplace */
8652 int known_errorHandler = -1;
8653
Guido van Rossumd57fd912000-03-10 22:53:23 +00008654 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 PyErr_BadArgument();
8656 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008657 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008658
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008659 if (PyUnicode_READY(input) == -1)
8660 return NULL;
8661 idata = (char*)PyUnicode_DATA(input);
8662 kind = PyUnicode_KIND(input);
8663 size = PyUnicode_GET_LENGTH(input);
8664 i = 0;
8665
8666 if (size == 0) {
8667 Py_INCREF(input);
8668 return input;
8669 }
8670
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671 /* allocate enough for a simple 1:1 translation without
8672 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 osize = size;
8674 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8675 opos = 0;
8676 if (output == NULL) {
8677 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008678 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008680
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 /* try to encode it */
8683 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 if (charmaptranslate_output(input, i, mapping,
8685 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 Py_XDECREF(x);
8687 goto onError;
8688 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008689 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008690 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008691 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 else { /* untranslatable character */
8693 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8694 Py_ssize_t repsize;
8695 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008696 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 Py_ssize_t collstart = i;
8699 Py_ssize_t collend = i+1;
8700 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008701
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 while (collend < size) {
8704 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 goto onError;
8706 Py_XDECREF(x);
8707 if (x!=Py_None)
8708 break;
8709 ++collend;
8710 }
8711 /* cache callback name lookup
8712 * (if not done yet, i.e. it's the first error) */
8713 if (known_errorHandler==-1) {
8714 if ((errors==NULL) || (!strcmp(errors, "strict")))
8715 known_errorHandler = 1;
8716 else if (!strcmp(errors, "replace"))
8717 known_errorHandler = 2;
8718 else if (!strcmp(errors, "ignore"))
8719 known_errorHandler = 3;
8720 else if (!strcmp(errors, "xmlcharrefreplace"))
8721 known_errorHandler = 4;
8722 else
8723 known_errorHandler = 0;
8724 }
8725 switch (known_errorHandler) {
8726 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 raise_translate_exception(&exc, input, collstart,
8728 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008729 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008730 case 2: /* replace */
8731 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 for (coll = collstart; coll<collend; coll++)
8733 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008734 /* fall through */
8735 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008736 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008737 break;
8738 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739 /* generate replacement (temporarily (mis)uses i) */
8740 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 char buffer[2+29+1+1];
8742 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008743 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8744 if (charmaptranslate_makespace(&output, &osize,
8745 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008746 goto onError;
8747 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008748 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008750 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008751 break;
8752 default:
8753 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008754 reason, input, &exc,
8755 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008756 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 goto onError;
8758 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 repsize = PyUnicode_GET_LENGTH(repunicode);
8760 if (charmaptranslate_makespace(&output, &osize,
8761 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 Py_DECREF(repunicode);
8763 goto onError;
8764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 for (uni2 = 0; repsize-->0; ++uni2)
8766 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8767 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008769 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008770 }
8771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8773 if (!res)
8774 goto onError;
8775 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008776 Py_XDECREF(exc);
8777 Py_XDECREF(errorHandler);
8778 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008779
Benjamin Peterson29060642009-01-31 22:14:21 +00008780 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008781 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008782 Py_XDECREF(exc);
8783 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008784 return NULL;
8785}
8786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008787/* Deprecated. Use PyUnicode_Translate instead. */
8788PyObject *
8789PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8790 Py_ssize_t size,
8791 PyObject *mapping,
8792 const char *errors)
8793{
8794 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8795 if (!unicode)
8796 return NULL;
8797 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8798}
8799
Alexander Belopolsky40018472011-02-26 01:02:56 +00008800PyObject *
8801PyUnicode_Translate(PyObject *str,
8802 PyObject *mapping,
8803 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008804{
8805 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008806
Guido van Rossumd57fd912000-03-10 22:53:23 +00008807 str = PyUnicode_FromObject(str);
8808 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008809 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008810 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008811 Py_DECREF(str);
8812 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008813
Benjamin Peterson29060642009-01-31 22:14:21 +00008814 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008815 Py_XDECREF(str);
8816 return NULL;
8817}
Tim Petersced69f82003-09-16 20:30:58 +00008818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008819static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008820fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008821{
8822 /* No need to call PyUnicode_READY(self) because this function is only
8823 called as a callback from fixup() which does it already. */
8824 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8825 const int kind = PyUnicode_KIND(self);
8826 void *data = PyUnicode_DATA(self);
8827 Py_UCS4 maxchar = 0, ch, fixed;
8828 Py_ssize_t i;
8829
8830 for (i = 0; i < len; ++i) {
8831 ch = PyUnicode_READ(kind, data, i);
8832 fixed = 0;
8833 if (ch > 127) {
8834 if (Py_UNICODE_ISSPACE(ch))
8835 fixed = ' ';
8836 else {
8837 const int decimal = Py_UNICODE_TODECIMAL(ch);
8838 if (decimal >= 0)
8839 fixed = '0' + decimal;
8840 }
8841 if (fixed != 0) {
8842 if (fixed > maxchar)
8843 maxchar = fixed;
8844 PyUnicode_WRITE(kind, data, i, fixed);
8845 }
8846 else if (ch > maxchar)
8847 maxchar = ch;
8848 }
8849 else if (ch > maxchar)
8850 maxchar = ch;
8851 }
8852
8853 return maxchar;
8854}
8855
8856PyObject *
8857_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8858{
8859 if (!PyUnicode_Check(unicode)) {
8860 PyErr_BadInternalCall();
8861 return NULL;
8862 }
8863 if (PyUnicode_READY(unicode) == -1)
8864 return NULL;
8865 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8866 /* If the string is already ASCII, just return the same string */
8867 Py_INCREF(unicode);
8868 return unicode;
8869 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008870 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008871}
8872
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008873PyObject *
8874PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8875 Py_ssize_t length)
8876{
8877 PyObject *result;
8878 Py_UNICODE *p; /* write pointer into result */
8879 Py_ssize_t i;
8880 /* Copy to a new string */
8881 result = (PyObject *)_PyUnicode_New(length);
8882 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8883 if (result == NULL)
8884 return result;
8885 p = PyUnicode_AS_UNICODE(result);
8886 /* Iterate over code points */
8887 for (i = 0; i < length; i++) {
8888 Py_UNICODE ch =s[i];
8889 if (ch > 127) {
8890 int decimal = Py_UNICODE_TODECIMAL(ch);
8891 if (decimal >= 0)
8892 p[i] = '0' + decimal;
8893 }
8894 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008895#ifndef DONT_MAKE_RESULT_READY
8896 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008897 Py_DECREF(result);
8898 return NULL;
8899 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008900#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008901 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008902 return result;
8903}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008904/* --- Decimal Encoder ---------------------------------------------------- */
8905
Alexander Belopolsky40018472011-02-26 01:02:56 +00008906int
8907PyUnicode_EncodeDecimal(Py_UNICODE *s,
8908 Py_ssize_t length,
8909 char *output,
8910 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008911{
8912 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008913 PyObject *errorHandler = NULL;
8914 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008915 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008916 const char *encoding = "decimal";
8917 const char *reason = "invalid decimal Unicode string";
8918 /* the following variable is used for caching string comparisons
8919 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8920 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008921
8922 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008923 PyErr_BadArgument();
8924 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008925 }
8926
8927 p = s;
8928 end = s + length;
8929 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008930 register Py_UNICODE ch = *p;
8931 int decimal;
8932 PyObject *repunicode;
8933 Py_ssize_t repsize;
8934 Py_ssize_t newpos;
8935 Py_UNICODE *uni2;
8936 Py_UNICODE *collstart;
8937 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008938
Benjamin Peterson29060642009-01-31 22:14:21 +00008939 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008940 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 ++p;
8942 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008943 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008944 decimal = Py_UNICODE_TODECIMAL(ch);
8945 if (decimal >= 0) {
8946 *output++ = '0' + decimal;
8947 ++p;
8948 continue;
8949 }
8950 if (0 < ch && ch < 256) {
8951 *output++ = (char)ch;
8952 ++p;
8953 continue;
8954 }
8955 /* All other characters are considered unencodable */
8956 collstart = p;
8957 collend = p+1;
8958 while (collend < end) {
8959 if ((0 < *collend && *collend < 256) ||
8960 !Py_UNICODE_ISSPACE(*collend) ||
8961 Py_UNICODE_TODECIMAL(*collend))
8962 break;
8963 }
8964 /* cache callback name lookup
8965 * (if not done yet, i.e. it's the first error) */
8966 if (known_errorHandler==-1) {
8967 if ((errors==NULL) || (!strcmp(errors, "strict")))
8968 known_errorHandler = 1;
8969 else if (!strcmp(errors, "replace"))
8970 known_errorHandler = 2;
8971 else if (!strcmp(errors, "ignore"))
8972 known_errorHandler = 3;
8973 else if (!strcmp(errors, "xmlcharrefreplace"))
8974 known_errorHandler = 4;
8975 else
8976 known_errorHandler = 0;
8977 }
8978 switch (known_errorHandler) {
8979 case 1: /* strict */
8980 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8981 goto onError;
8982 case 2: /* replace */
8983 for (p = collstart; p < collend; ++p)
8984 *output++ = '?';
8985 /* fall through */
8986 case 3: /* ignore */
8987 p = collend;
8988 break;
8989 case 4: /* xmlcharrefreplace */
8990 /* generate replacement (temporarily (mis)uses p) */
8991 for (p = collstart; p < collend; ++p)
8992 output += sprintf(output, "&#%d;", (int)*p);
8993 p = collend;
8994 break;
8995 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008996 unicode = PyUnicode_FromUnicode(s, length);
8997 if (unicode == NULL)
8998 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008999 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009000 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009001 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009002 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00009003 if (repunicode == NULL)
9004 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009005 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00009006 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009007 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
9008 Py_DECREF(repunicode);
9009 goto onError;
9010 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009011 /* generate replacement */
9012 repsize = PyUnicode_GET_SIZE(repunicode);
9013 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
9014 Py_UNICODE ch = *uni2;
9015 if (Py_UNICODE_ISSPACE(ch))
9016 *output++ = ' ';
9017 else {
9018 decimal = Py_UNICODE_TODECIMAL(ch);
9019 if (decimal >= 0)
9020 *output++ = '0' + decimal;
9021 else if (0 < ch && ch < 256)
9022 *output++ = (char)ch;
9023 else {
9024 Py_DECREF(repunicode);
9025 raise_encode_exception(&exc, encoding,
9026 s, length, collstart-s, collend-s, reason);
9027 goto onError;
9028 }
9029 }
9030 }
9031 p = s + newpos;
9032 Py_DECREF(repunicode);
9033 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00009034 }
9035 /* 0-terminate the output string */
9036 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009037 Py_XDECREF(exc);
9038 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009039 return 0;
9040
Benjamin Peterson29060642009-01-31 22:14:21 +00009041 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009042 Py_XDECREF(exc);
9043 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009044 return -1;
9045}
9046
Guido van Rossumd57fd912000-03-10 22:53:23 +00009047/* --- Helpers ------------------------------------------------------------ */
9048
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009049static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009050any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 Py_ssize_t start,
9052 Py_ssize_t end)
9053{
9054 int kind1, kind2, kind;
9055 void *buf1, *buf2;
9056 Py_ssize_t len1, len2, result;
9057
9058 kind1 = PyUnicode_KIND(s1);
9059 kind2 = PyUnicode_KIND(s2);
9060 kind = kind1 > kind2 ? kind1 : kind2;
9061 buf1 = PyUnicode_DATA(s1);
9062 buf2 = PyUnicode_DATA(s2);
9063 if (kind1 != kind)
9064 buf1 = _PyUnicode_AsKind(s1, kind);
9065 if (!buf1)
9066 return -2;
9067 if (kind2 != kind)
9068 buf2 = _PyUnicode_AsKind(s2, kind);
9069 if (!buf2) {
9070 if (kind1 != kind) PyMem_Free(buf1);
9071 return -2;
9072 }
9073 len1 = PyUnicode_GET_LENGTH(s1);
9074 len2 = PyUnicode_GET_LENGTH(s2);
9075
Victor Stinner794d5672011-10-10 03:21:36 +02009076 if (direction > 0) {
9077 switch(kind) {
9078 case PyUnicode_1BYTE_KIND:
9079 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9080 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9081 else
9082 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9083 break;
9084 case PyUnicode_2BYTE_KIND:
9085 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9086 break;
9087 case PyUnicode_4BYTE_KIND:
9088 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9089 break;
9090 default:
9091 assert(0); result = -2;
9092 }
9093 }
9094 else {
9095 switch(kind) {
9096 case PyUnicode_1BYTE_KIND:
9097 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9098 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9099 else
9100 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9101 break;
9102 case PyUnicode_2BYTE_KIND:
9103 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9104 break;
9105 case PyUnicode_4BYTE_KIND:
9106 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9107 break;
9108 default:
9109 assert(0); result = -2;
9110 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111 }
9112
9113 if (kind1 != kind)
9114 PyMem_Free(buf1);
9115 if (kind2 != kind)
9116 PyMem_Free(buf2);
9117
9118 return result;
9119}
9120
9121Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009122_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009123 Py_ssize_t n_buffer,
9124 void *digits, Py_ssize_t n_digits,
9125 Py_ssize_t min_width,
9126 const char *grouping,
9127 const char *thousands_sep)
9128{
9129 switch(kind) {
9130 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009131 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9132 return _PyUnicode_ascii_InsertThousandsGrouping(
9133 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9134 min_width, grouping, thousands_sep);
9135 else
9136 return _PyUnicode_ucs1_InsertThousandsGrouping(
9137 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9138 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009139 case PyUnicode_2BYTE_KIND:
9140 return _PyUnicode_ucs2_InsertThousandsGrouping(
9141 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9142 min_width, grouping, thousands_sep);
9143 case PyUnicode_4BYTE_KIND:
9144 return _PyUnicode_ucs4_InsertThousandsGrouping(
9145 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9146 min_width, grouping, thousands_sep);
9147 }
9148 assert(0);
9149 return -1;
9150}
9151
9152
Thomas Wouters477c8d52006-05-27 19:21:47 +00009153/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009154#define ADJUST_INDICES(start, end, len) \
9155 if (end > len) \
9156 end = len; \
9157 else if (end < 0) { \
9158 end += len; \
9159 if (end < 0) \
9160 end = 0; \
9161 } \
9162 if (start < 0) { \
9163 start += len; \
9164 if (start < 0) \
9165 start = 0; \
9166 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009167
Alexander Belopolsky40018472011-02-26 01:02:56 +00009168Py_ssize_t
9169PyUnicode_Count(PyObject *str,
9170 PyObject *substr,
9171 Py_ssize_t start,
9172 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009174 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009175 PyObject* str_obj;
9176 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009177 int kind1, kind2, kind;
9178 void *buf1 = NULL, *buf2 = NULL;
9179 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009180
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009181 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009182 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009183 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009184 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009185 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009186 Py_DECREF(str_obj);
9187 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009188 }
Tim Petersced69f82003-09-16 20:30:58 +00009189
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 kind1 = PyUnicode_KIND(str_obj);
9191 kind2 = PyUnicode_KIND(sub_obj);
9192 kind = kind1 > kind2 ? kind1 : kind2;
9193 buf1 = PyUnicode_DATA(str_obj);
9194 if (kind1 != kind)
9195 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
9196 if (!buf1)
9197 goto onError;
9198 buf2 = PyUnicode_DATA(sub_obj);
9199 if (kind2 != kind)
9200 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
9201 if (!buf2)
9202 goto onError;
9203 len1 = PyUnicode_GET_LENGTH(str_obj);
9204 len2 = PyUnicode_GET_LENGTH(sub_obj);
9205
9206 ADJUST_INDICES(start, end, len1);
9207 switch(kind) {
9208 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009209 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9210 result = asciilib_count(
9211 ((Py_UCS1*)buf1) + start, end - start,
9212 buf2, len2, PY_SSIZE_T_MAX
9213 );
9214 else
9215 result = ucs1lib_count(
9216 ((Py_UCS1*)buf1) + start, end - start,
9217 buf2, len2, PY_SSIZE_T_MAX
9218 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 break;
9220 case PyUnicode_2BYTE_KIND:
9221 result = ucs2lib_count(
9222 ((Py_UCS2*)buf1) + start, end - start,
9223 buf2, len2, PY_SSIZE_T_MAX
9224 );
9225 break;
9226 case PyUnicode_4BYTE_KIND:
9227 result = ucs4lib_count(
9228 ((Py_UCS4*)buf1) + start, end - start,
9229 buf2, len2, PY_SSIZE_T_MAX
9230 );
9231 break;
9232 default:
9233 assert(0); result = 0;
9234 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009235
9236 Py_DECREF(sub_obj);
9237 Py_DECREF(str_obj);
9238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 if (kind1 != kind)
9240 PyMem_Free(buf1);
9241 if (kind2 != kind)
9242 PyMem_Free(buf2);
9243
Guido van Rossumd57fd912000-03-10 22:53:23 +00009244 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245 onError:
9246 Py_DECREF(sub_obj);
9247 Py_DECREF(str_obj);
9248 if (kind1 != kind && buf1)
9249 PyMem_Free(buf1);
9250 if (kind2 != kind && buf2)
9251 PyMem_Free(buf2);
9252 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009253}
9254
Alexander Belopolsky40018472011-02-26 01:02:56 +00009255Py_ssize_t
9256PyUnicode_Find(PyObject *str,
9257 PyObject *sub,
9258 Py_ssize_t start,
9259 Py_ssize_t end,
9260 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009262 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009263
Guido van Rossumd57fd912000-03-10 22:53:23 +00009264 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009266 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009267 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009269 Py_DECREF(str);
9270 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 }
Tim Petersced69f82003-09-16 20:30:58 +00009272
Victor Stinner794d5672011-10-10 03:21:36 +02009273 result = any_find_slice(direction,
9274 str, sub, start, end
9275 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009276
Guido van Rossumd57fd912000-03-10 22:53:23 +00009277 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009278 Py_DECREF(sub);
9279
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280 return result;
9281}
9282
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283Py_ssize_t
9284PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9285 Py_ssize_t start, Py_ssize_t end,
9286 int direction)
9287{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009289 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009290 if (PyUnicode_READY(str) == -1)
9291 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009292 if (start < 0 || end < 0) {
9293 PyErr_SetString(PyExc_IndexError, "string index out of range");
9294 return -2;
9295 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296 if (end > PyUnicode_GET_LENGTH(str))
9297 end = PyUnicode_GET_LENGTH(str);
9298 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009299 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9300 kind, end-start, ch, direction);
9301 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009303 else
9304 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009305}
9306
Alexander Belopolsky40018472011-02-26 01:02:56 +00009307static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009308tailmatch(PyObject *self,
9309 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009310 Py_ssize_t start,
9311 Py_ssize_t end,
9312 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009314 int kind_self;
9315 int kind_sub;
9316 void *data_self;
9317 void *data_sub;
9318 Py_ssize_t offset;
9319 Py_ssize_t i;
9320 Py_ssize_t end_sub;
9321
9322 if (PyUnicode_READY(self) == -1 ||
9323 PyUnicode_READY(substring) == -1)
9324 return 0;
9325
9326 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009327 return 1;
9328
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009329 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9330 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009331 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009332 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 kind_self = PyUnicode_KIND(self);
9335 data_self = PyUnicode_DATA(self);
9336 kind_sub = PyUnicode_KIND(substring);
9337 data_sub = PyUnicode_DATA(substring);
9338 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9339
9340 if (direction > 0)
9341 offset = end;
9342 else
9343 offset = start;
9344
9345 if (PyUnicode_READ(kind_self, data_self, offset) ==
9346 PyUnicode_READ(kind_sub, data_sub, 0) &&
9347 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9348 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9349 /* If both are of the same kind, memcmp is sufficient */
9350 if (kind_self == kind_sub) {
9351 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009352 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 data_sub,
9354 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009355 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 }
9357 /* otherwise we have to compare each character by first accesing it */
9358 else {
9359 /* We do not need to compare 0 and len(substring)-1 because
9360 the if statement above ensured already that they are equal
9361 when we end up here. */
9362 // TODO: honor direction and do a forward or backwards search
9363 for (i = 1; i < end_sub; ++i) {
9364 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9365 PyUnicode_READ(kind_sub, data_sub, i))
9366 return 0;
9367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009370 }
9371
9372 return 0;
9373}
9374
Alexander Belopolsky40018472011-02-26 01:02:56 +00009375Py_ssize_t
9376PyUnicode_Tailmatch(PyObject *str,
9377 PyObject *substr,
9378 Py_ssize_t start,
9379 Py_ssize_t end,
9380 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009381{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009382 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009383
Guido van Rossumd57fd912000-03-10 22:53:23 +00009384 str = PyUnicode_FromObject(str);
9385 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009386 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387 substr = PyUnicode_FromObject(substr);
9388 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009389 Py_DECREF(str);
9390 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009391 }
Tim Petersced69f82003-09-16 20:30:58 +00009392
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009393 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009394 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009395 Py_DECREF(str);
9396 Py_DECREF(substr);
9397 return result;
9398}
9399
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400/* Apply fixfct filter to the Unicode object self and return a
9401 reference to the modified object */
9402
Alexander Belopolsky40018472011-02-26 01:02:56 +00009403static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009404fixup(PyObject *self,
9405 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 PyObject *u;
9408 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009410 if (PyUnicode_READY(self) == -1)
9411 return NULL;
9412 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9413 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9414 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009416 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009418 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009419 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421 /* fix functions return the new maximum character in a string,
9422 if the kind of the resulting unicode object does not change,
9423 everything is fine. Otherwise we need to change the string kind
9424 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009425 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 if (maxchar_new == 0)
9427 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9428 else if (maxchar_new <= 127)
9429 maxchar_new = 127;
9430 else if (maxchar_new <= 255)
9431 maxchar_new = 255;
9432 else if (maxchar_new <= 65535)
9433 maxchar_new = 65535;
9434 else
9435 maxchar_new = 1114111; /* 0x10ffff */
9436
9437 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009438 /* fixfct should return TRUE if it modified the buffer. If
9439 FALSE, return a reference to the original buffer instead
9440 (to save space, not time) */
9441 Py_INCREF(self);
9442 Py_DECREF(u);
9443 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009444 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 else if (maxchar_new == maxchar_old) {
9446 return u;
9447 }
9448 else {
9449 /* In case the maximum character changed, we need to
9450 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009451 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 if (v == NULL) {
9453 Py_DECREF(u);
9454 return NULL;
9455 }
9456 if (maxchar_new > maxchar_old) {
9457 /* If the maxchar increased so that the kind changed, not all
9458 characters are representable anymore and we need to fix the
9459 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009460 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009461 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9463 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009464 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009465 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009466 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009467
9468 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009469 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009470 return v;
9471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009472}
9473
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009475fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009477 /* No need to call PyUnicode_READY(self) because this function is only
9478 called as a callback from fixup() which does it already. */
9479 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9480 const int kind = PyUnicode_KIND(self);
9481 void *data = PyUnicode_DATA(self);
9482 int touched = 0;
9483 Py_UCS4 maxchar = 0;
9484 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486 for (i = 0; i < len; ++i) {
9487 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9488 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9489 if (up != ch) {
9490 if (up > maxchar)
9491 maxchar = up;
9492 PyUnicode_WRITE(kind, data, i, up);
9493 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009494 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 else if (ch > maxchar)
9496 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 }
9498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 if (touched)
9500 return maxchar;
9501 else
9502 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503}
9504
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009506fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009507{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9509 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9510 const int kind = PyUnicode_KIND(self);
9511 void *data = PyUnicode_DATA(self);
9512 int touched = 0;
9513 Py_UCS4 maxchar = 0;
9514 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 for(i = 0; i < len; ++i) {
9517 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9518 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9519 if (lo != ch) {
9520 if (lo > maxchar)
9521 maxchar = lo;
9522 PyUnicode_WRITE(kind, data, i, lo);
9523 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009524 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 else if (ch > maxchar)
9526 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527 }
9528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 if (touched)
9530 return maxchar;
9531 else
9532 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009533}
9534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009536fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009537{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9539 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9540 const int kind = PyUnicode_KIND(self);
9541 void *data = PyUnicode_DATA(self);
9542 int touched = 0;
9543 Py_UCS4 maxchar = 0;
9544 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 for(i = 0; i < len; ++i) {
9547 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9548 Py_UCS4 nu = 0;
9549
9550 if (Py_UNICODE_ISUPPER(ch))
9551 nu = Py_UNICODE_TOLOWER(ch);
9552 else if (Py_UNICODE_ISLOWER(ch))
9553 nu = Py_UNICODE_TOUPPER(ch);
9554
9555 if (nu != 0) {
9556 if (nu > maxchar)
9557 maxchar = nu;
9558 PyUnicode_WRITE(kind, data, i, nu);
9559 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 else if (ch > maxchar)
9562 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563 }
9564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 if (touched)
9566 return maxchar;
9567 else
9568 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009569}
9570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009572fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009573{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9575 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9576 const int kind = PyUnicode_KIND(self);
9577 void *data = PyUnicode_DATA(self);
9578 int touched = 0;
9579 Py_UCS4 maxchar = 0;
9580 Py_ssize_t i = 0;
9581 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009582
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009583 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009584 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585
9586 ch = PyUnicode_READ(kind, data, i);
9587 if (!Py_UNICODE_ISUPPER(ch)) {
9588 maxchar = Py_UNICODE_TOUPPER(ch);
9589 PyUnicode_WRITE(kind, data, i, maxchar);
9590 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009592 ++i;
9593 for(; i < len; ++i) {
9594 ch = PyUnicode_READ(kind, data, i);
9595 if (!Py_UNICODE_ISLOWER(ch)) {
9596 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9597 if (lo > maxchar)
9598 maxchar = lo;
9599 PyUnicode_WRITE(kind, data, i, lo);
9600 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009601 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009602 else if (ch > maxchar)
9603 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605
9606 if (touched)
9607 return maxchar;
9608 else
9609 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009610}
9611
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009612static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009613fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9616 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9617 const int kind = PyUnicode_KIND(self);
9618 void *data = PyUnicode_DATA(self);
9619 Py_UCS4 maxchar = 0;
9620 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009621 int previous_is_cased;
9622
9623 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624 if (len == 1) {
9625 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9626 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9627 if (ti != ch) {
9628 PyUnicode_WRITE(kind, data, i, ti);
9629 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009630 }
9631 else
9632 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009635 for(; i < len; ++i) {
9636 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9637 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009638
Benjamin Peterson29060642009-01-31 22:14:21 +00009639 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009640 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009641 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009642 nu = Py_UNICODE_TOTITLE(ch);
9643
9644 if (nu > maxchar)
9645 maxchar = nu;
9646 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009647
Benjamin Peterson29060642009-01-31 22:14:21 +00009648 if (Py_UNICODE_ISLOWER(ch) ||
9649 Py_UNICODE_ISUPPER(ch) ||
9650 Py_UNICODE_ISTITLE(ch))
9651 previous_is_cased = 1;
9652 else
9653 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009655 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009656}
9657
Tim Peters8ce9f162004-08-27 01:49:32 +00009658PyObject *
9659PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009660{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009662 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009663 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009664 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009665 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9666 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009667 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009669 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009670 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009671 int use_memcpy;
9672 unsigned char *res_data = NULL, *sep_data = NULL;
9673 PyObject *last_obj;
9674 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009675
Tim Peters05eba1f2004-08-27 21:32:02 +00009676 fseq = PySequence_Fast(seq, "");
9677 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009678 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009679 }
9680
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009681 /* NOTE: the following code can't call back into Python code,
9682 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009683 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009684
Tim Peters05eba1f2004-08-27 21:32:02 +00009685 seqlen = PySequence_Fast_GET_SIZE(fseq);
9686 /* If empty sequence, return u"". */
9687 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009688 Py_DECREF(fseq);
9689 Py_INCREF(unicode_empty);
9690 res = unicode_empty;
9691 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009692 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009693
Tim Peters05eba1f2004-08-27 21:32:02 +00009694 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009695 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009696 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009697 if (seqlen == 1) {
9698 if (PyUnicode_CheckExact(items[0])) {
9699 res = items[0];
9700 Py_INCREF(res);
9701 Py_DECREF(fseq);
9702 return res;
9703 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009704 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009705 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009706 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009707 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009708 /* Set up sep and seplen */
9709 if (separator == NULL) {
9710 /* fall back to a blank space separator */
9711 sep = PyUnicode_FromOrdinal(' ');
9712 if (!sep)
9713 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009714 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009715 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009716 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009717 else {
9718 if (!PyUnicode_Check(separator)) {
9719 PyErr_Format(PyExc_TypeError,
9720 "separator: expected str instance,"
9721 " %.80s found",
9722 Py_TYPE(separator)->tp_name);
9723 goto onError;
9724 }
9725 if (PyUnicode_READY(separator))
9726 goto onError;
9727 sep = separator;
9728 seplen = PyUnicode_GET_LENGTH(separator);
9729 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9730 /* inc refcount to keep this code path symmetric with the
9731 above case of a blank separator */
9732 Py_INCREF(sep);
9733 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009734 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009735 }
9736
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009737 /* There are at least two things to join, or else we have a subclass
9738 * of str in the sequence.
9739 * Do a pre-pass to figure out the total amount of space we'll
9740 * need (sz), and see whether all argument are strings.
9741 */
9742 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009743#ifdef Py_DEBUG
9744 use_memcpy = 0;
9745#else
9746 use_memcpy = 1;
9747#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009748 for (i = 0; i < seqlen; i++) {
9749 const Py_ssize_t old_sz = sz;
9750 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009751 if (!PyUnicode_Check(item)) {
9752 PyErr_Format(PyExc_TypeError,
9753 "sequence item %zd: expected str instance,"
9754 " %.80s found",
9755 i, Py_TYPE(item)->tp_name);
9756 goto onError;
9757 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009758 if (PyUnicode_READY(item) == -1)
9759 goto onError;
9760 sz += PyUnicode_GET_LENGTH(item);
9761 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009762 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009763 if (i != 0)
9764 sz += seplen;
9765 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9766 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009767 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009768 goto onError;
9769 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009770 if (use_memcpy && last_obj != NULL) {
9771 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9772 use_memcpy = 0;
9773 }
9774 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009775 }
Tim Petersced69f82003-09-16 20:30:58 +00009776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009778 if (res == NULL)
9779 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009780
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009781 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009782#ifdef Py_DEBUG
9783 use_memcpy = 0;
9784#else
9785 if (use_memcpy) {
9786 res_data = PyUnicode_1BYTE_DATA(res);
9787 kind = PyUnicode_KIND(res);
9788 if (seplen != 0)
9789 sep_data = PyUnicode_1BYTE_DATA(sep);
9790 }
9791#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009792 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009793 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009794 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009795 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009796 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009797 if (use_memcpy) {
9798 Py_MEMCPY(res_data,
9799 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009800 kind * seplen);
9801 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009802 }
9803 else {
9804 copy_characters(res, res_offset, sep, 0, seplen);
9805 res_offset += seplen;
9806 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009807 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009808 itemlen = PyUnicode_GET_LENGTH(item);
9809 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009810 if (use_memcpy) {
9811 Py_MEMCPY(res_data,
9812 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009813 kind * itemlen);
9814 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009815 }
9816 else {
9817 copy_characters(res, res_offset, item, 0, itemlen);
9818 res_offset += itemlen;
9819 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009820 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009821 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009822 if (use_memcpy)
9823 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009824 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009825 else
9826 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009827
Tim Peters05eba1f2004-08-27 21:32:02 +00009828 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009829 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009830 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009831 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009832
Benjamin Peterson29060642009-01-31 22:14:21 +00009833 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009834 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009835 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009836 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009837 return NULL;
9838}
9839
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009840#define FILL(kind, data, value, start, length) \
9841 do { \
9842 Py_ssize_t i_ = 0; \
9843 assert(kind != PyUnicode_WCHAR_KIND); \
9844 switch ((kind)) { \
9845 case PyUnicode_1BYTE_KIND: { \
9846 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9847 memset(to_, (unsigned char)value, length); \
9848 break; \
9849 } \
9850 case PyUnicode_2BYTE_KIND: { \
9851 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9852 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9853 break; \
9854 } \
9855 default: { \
9856 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9857 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9858 break; \
9859 } \
9860 } \
9861 } while (0)
9862
Victor Stinner9310abb2011-10-05 00:59:23 +02009863static PyObject *
9864pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009865 Py_ssize_t left,
9866 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 PyObject *u;
9870 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009871 int kind;
9872 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009873
9874 if (left < 0)
9875 left = 0;
9876 if (right < 0)
9877 right = 0;
9878
Tim Peters7a29bd52001-09-12 03:03:31 +00009879 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880 Py_INCREF(self);
9881 return self;
9882 }
9883
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9885 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009886 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9887 return NULL;
9888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9890 if (fill > maxchar)
9891 maxchar = fill;
9892 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009893 if (!u)
9894 return NULL;
9895
9896 kind = PyUnicode_KIND(u);
9897 data = PyUnicode_DATA(u);
9898 if (left)
9899 FILL(kind, data, fill, 0, left);
9900 if (right)
9901 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009902 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009903 assert(_PyUnicode_CheckConsistency(u, 1));
9904 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009905}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009906#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009907
Alexander Belopolsky40018472011-02-26 01:02:56 +00009908PyObject *
9909PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009910{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009911 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009912
9913 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009915 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 switch(PyUnicode_KIND(string)) {
9918 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009919 if (PyUnicode_IS_ASCII(string))
9920 list = asciilib_splitlines(
9921 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9922 PyUnicode_GET_LENGTH(string), keepends);
9923 else
9924 list = ucs1lib_splitlines(
9925 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9926 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009927 break;
9928 case PyUnicode_2BYTE_KIND:
9929 list = ucs2lib_splitlines(
9930 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9931 PyUnicode_GET_LENGTH(string), keepends);
9932 break;
9933 case PyUnicode_4BYTE_KIND:
9934 list = ucs4lib_splitlines(
9935 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9936 PyUnicode_GET_LENGTH(string), keepends);
9937 break;
9938 default:
9939 assert(0);
9940 list = 0;
9941 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009942 Py_DECREF(string);
9943 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009944}
9945
Alexander Belopolsky40018472011-02-26 01:02:56 +00009946static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009947split(PyObject *self,
9948 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009949 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009950{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 int kind1, kind2, kind;
9952 void *buf1, *buf2;
9953 Py_ssize_t len1, len2;
9954 PyObject* out;
9955
Guido van Rossumd57fd912000-03-10 22:53:23 +00009956 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009957 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009959 if (PyUnicode_READY(self) == -1)
9960 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009962 if (substring == NULL)
9963 switch(PyUnicode_KIND(self)) {
9964 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009965 if (PyUnicode_IS_ASCII(self))
9966 return asciilib_split_whitespace(
9967 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9968 PyUnicode_GET_LENGTH(self), maxcount
9969 );
9970 else
9971 return ucs1lib_split_whitespace(
9972 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9973 PyUnicode_GET_LENGTH(self), maxcount
9974 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009975 case PyUnicode_2BYTE_KIND:
9976 return ucs2lib_split_whitespace(
9977 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9978 PyUnicode_GET_LENGTH(self), maxcount
9979 );
9980 case PyUnicode_4BYTE_KIND:
9981 return ucs4lib_split_whitespace(
9982 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9983 PyUnicode_GET_LENGTH(self), maxcount
9984 );
9985 default:
9986 assert(0);
9987 return NULL;
9988 }
9989
9990 if (PyUnicode_READY(substring) == -1)
9991 return NULL;
9992
9993 kind1 = PyUnicode_KIND(self);
9994 kind2 = PyUnicode_KIND(substring);
9995 kind = kind1 > kind2 ? kind1 : kind2;
9996 buf1 = PyUnicode_DATA(self);
9997 buf2 = PyUnicode_DATA(substring);
9998 if (kind1 != kind)
9999 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10000 if (!buf1)
10001 return NULL;
10002 if (kind2 != kind)
10003 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10004 if (!buf2) {
10005 if (kind1 != kind) PyMem_Free(buf1);
10006 return NULL;
10007 }
10008 len1 = PyUnicode_GET_LENGTH(self);
10009 len2 = PyUnicode_GET_LENGTH(substring);
10010
10011 switch(kind) {
10012 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010013 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10014 out = asciilib_split(
10015 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10016 else
10017 out = ucs1lib_split(
10018 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019 break;
10020 case PyUnicode_2BYTE_KIND:
10021 out = ucs2lib_split(
10022 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10023 break;
10024 case PyUnicode_4BYTE_KIND:
10025 out = ucs4lib_split(
10026 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10027 break;
10028 default:
10029 out = NULL;
10030 }
10031 if (kind1 != kind)
10032 PyMem_Free(buf1);
10033 if (kind2 != kind)
10034 PyMem_Free(buf2);
10035 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010036}
10037
Alexander Belopolsky40018472011-02-26 01:02:56 +000010038static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010039rsplit(PyObject *self,
10040 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010041 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010042{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 int kind1, kind2, kind;
10044 void *buf1, *buf2;
10045 Py_ssize_t len1, len2;
10046 PyObject* out;
10047
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010048 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010049 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010051 if (PyUnicode_READY(self) == -1)
10052 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 if (substring == NULL)
10055 switch(PyUnicode_KIND(self)) {
10056 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010057 if (PyUnicode_IS_ASCII(self))
10058 return asciilib_rsplit_whitespace(
10059 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10060 PyUnicode_GET_LENGTH(self), maxcount
10061 );
10062 else
10063 return ucs1lib_rsplit_whitespace(
10064 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10065 PyUnicode_GET_LENGTH(self), maxcount
10066 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 case PyUnicode_2BYTE_KIND:
10068 return ucs2lib_rsplit_whitespace(
10069 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10070 PyUnicode_GET_LENGTH(self), maxcount
10071 );
10072 case PyUnicode_4BYTE_KIND:
10073 return ucs4lib_rsplit_whitespace(
10074 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10075 PyUnicode_GET_LENGTH(self), maxcount
10076 );
10077 default:
10078 assert(0);
10079 return NULL;
10080 }
10081
10082 if (PyUnicode_READY(substring) == -1)
10083 return NULL;
10084
10085 kind1 = PyUnicode_KIND(self);
10086 kind2 = PyUnicode_KIND(substring);
10087 kind = kind1 > kind2 ? kind1 : kind2;
10088 buf1 = PyUnicode_DATA(self);
10089 buf2 = PyUnicode_DATA(substring);
10090 if (kind1 != kind)
10091 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10092 if (!buf1)
10093 return NULL;
10094 if (kind2 != kind)
10095 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10096 if (!buf2) {
10097 if (kind1 != kind) PyMem_Free(buf1);
10098 return NULL;
10099 }
10100 len1 = PyUnicode_GET_LENGTH(self);
10101 len2 = PyUnicode_GET_LENGTH(substring);
10102
10103 switch(kind) {
10104 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010105 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10106 out = asciilib_rsplit(
10107 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10108 else
10109 out = ucs1lib_rsplit(
10110 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 break;
10112 case PyUnicode_2BYTE_KIND:
10113 out = ucs2lib_rsplit(
10114 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10115 break;
10116 case PyUnicode_4BYTE_KIND:
10117 out = ucs4lib_rsplit(
10118 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10119 break;
10120 default:
10121 out = NULL;
10122 }
10123 if (kind1 != kind)
10124 PyMem_Free(buf1);
10125 if (kind2 != kind)
10126 PyMem_Free(buf2);
10127 return out;
10128}
10129
10130static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010131anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10132 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010133{
10134 switch(kind) {
10135 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010136 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10137 return asciilib_find(buf1, len1, buf2, len2, offset);
10138 else
10139 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010140 case PyUnicode_2BYTE_KIND:
10141 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10142 case PyUnicode_4BYTE_KIND:
10143 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10144 }
10145 assert(0);
10146 return -1;
10147}
10148
10149static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10151 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152{
10153 switch(kind) {
10154 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010155 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10156 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10157 else
10158 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 case PyUnicode_2BYTE_KIND:
10160 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10161 case PyUnicode_4BYTE_KIND:
10162 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10163 }
10164 assert(0);
10165 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010166}
10167
Alexander Belopolsky40018472011-02-26 01:02:56 +000010168static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169replace(PyObject *self, PyObject *str1,
10170 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010171{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 PyObject *u;
10173 char *sbuf = PyUnicode_DATA(self);
10174 char *buf1 = PyUnicode_DATA(str1);
10175 char *buf2 = PyUnicode_DATA(str2);
10176 int srelease = 0, release1 = 0, release2 = 0;
10177 int skind = PyUnicode_KIND(self);
10178 int kind1 = PyUnicode_KIND(str1);
10179 int kind2 = PyUnicode_KIND(str2);
10180 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10181 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10182 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010183 int mayshrink;
10184 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010185
10186 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010187 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010189 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010190
Victor Stinner59de0ee2011-10-07 10:01:28 +020010191 if (str1 == str2)
10192 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 if (skind < kind1)
10194 /* substring too wide to be present */
10195 goto nothing;
10196
Victor Stinner49a0a212011-10-12 23:46:10 +020010197 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10198 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10199 /* Replacing str1 with str2 may cause a maxchar reduction in the
10200 result string. */
10201 mayshrink = (maxchar_str2 < maxchar);
10202 maxchar = Py_MAX(maxchar, maxchar_str2);
10203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010205 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010206 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010208 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010210 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010211 Py_UCS4 u1, u2;
10212 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010214 if (findchar(sbuf, PyUnicode_KIND(self),
10215 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010216 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010219 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010221 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 rkind = PyUnicode_KIND(u);
10223 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10224 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010225 if (--maxcount < 0)
10226 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010228 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010229 }
10230 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 int rkind = skind;
10232 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010233
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010234 if (kind1 < rkind) {
10235 /* widen substring */
10236 buf1 = _PyUnicode_AsKind(str1, rkind);
10237 if (!buf1) goto error;
10238 release1 = 1;
10239 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010240 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010241 if (i < 0)
10242 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 if (rkind > kind2) {
10244 /* widen replacement */
10245 buf2 = _PyUnicode_AsKind(str2, rkind);
10246 if (!buf2) goto error;
10247 release2 = 1;
10248 }
10249 else if (rkind < kind2) {
10250 /* widen self and buf1 */
10251 rkind = kind2;
10252 if (release1) PyMem_Free(buf1);
10253 sbuf = _PyUnicode_AsKind(self, rkind);
10254 if (!sbuf) goto error;
10255 srelease = 1;
10256 buf1 = _PyUnicode_AsKind(str1, rkind);
10257 if (!buf1) goto error;
10258 release1 = 1;
10259 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010260 u = PyUnicode_New(slen, maxchar);
10261 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010263 assert(PyUnicode_KIND(u) == rkind);
10264 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010265
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010266 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010267 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010268 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010270 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010271 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010272
10273 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010274 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010275 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010277 if (i == -1)
10278 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010279 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010281 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010283 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010284 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010285 }
10286 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010287 Py_ssize_t n, i, j, ires;
10288 Py_ssize_t product, new_size;
10289 int rkind = skind;
10290 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010293 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010294 buf1 = _PyUnicode_AsKind(str1, rkind);
10295 if (!buf1) goto error;
10296 release1 = 1;
10297 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010298 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010299 if (n == 0)
10300 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010302 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 buf2 = _PyUnicode_AsKind(str2, rkind);
10304 if (!buf2) goto error;
10305 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010308 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 rkind = kind2;
10310 sbuf = _PyUnicode_AsKind(self, rkind);
10311 if (!sbuf) goto error;
10312 srelease = 1;
10313 if (release1) PyMem_Free(buf1);
10314 buf1 = _PyUnicode_AsKind(str1, rkind);
10315 if (!buf1) goto error;
10316 release1 = 1;
10317 }
10318 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10319 PyUnicode_GET_LENGTH(str1))); */
10320 product = n * (len2-len1);
10321 if ((product / (len2-len1)) != n) {
10322 PyErr_SetString(PyExc_OverflowError,
10323 "replace string is too long");
10324 goto error;
10325 }
10326 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010327 if (new_size == 0) {
10328 Py_INCREF(unicode_empty);
10329 u = unicode_empty;
10330 goto done;
10331 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010332 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10333 PyErr_SetString(PyExc_OverflowError,
10334 "replace string is too long");
10335 goto error;
10336 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010337 u = PyUnicode_New(new_size, maxchar);
10338 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010340 assert(PyUnicode_KIND(u) == rkind);
10341 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 ires = i = 0;
10343 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010344 while (n-- > 0) {
10345 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010346 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010347 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010348 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010349 if (j == -1)
10350 break;
10351 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010352 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010353 memcpy(res + rkind * ires,
10354 sbuf + rkind * i,
10355 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010356 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010357 }
10358 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010360 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010362 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010363 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010364 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010365 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010368 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010369 memcpy(res + rkind * ires,
10370 sbuf + rkind * i,
10371 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010372 }
10373 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010374 /* interleave */
10375 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010376 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010377 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010378 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010380 if (--n <= 0)
10381 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010382 memcpy(res + rkind * ires,
10383 sbuf + rkind * i,
10384 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 ires++;
10386 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010387 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010388 memcpy(res + rkind * ires,
10389 sbuf + rkind * i,
10390 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010391 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010392 }
10393
10394 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010395 unicode_adjust_maxchar(&u);
10396 if (u == NULL)
10397 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010399
10400 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 if (srelease)
10402 PyMem_FREE(sbuf);
10403 if (release1)
10404 PyMem_FREE(buf1);
10405 if (release2)
10406 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010407 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010409
Benjamin Peterson29060642009-01-31 22:14:21 +000010410 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010411 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 if (srelease)
10413 PyMem_FREE(sbuf);
10414 if (release1)
10415 PyMem_FREE(buf1);
10416 if (release2)
10417 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010418 if (PyUnicode_CheckExact(self)) {
10419 Py_INCREF(self);
10420 return (PyObject *) self;
10421 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010422 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010423 error:
10424 if (srelease && sbuf)
10425 PyMem_FREE(sbuf);
10426 if (release1 && buf1)
10427 PyMem_FREE(buf1);
10428 if (release2 && buf2)
10429 PyMem_FREE(buf2);
10430 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010431}
10432
10433/* --- Unicode Object Methods --------------------------------------------- */
10434
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010435PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010436 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010437\n\
10438Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010439characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010440
10441static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010442unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010443{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444 return fixup(self, fixtitle);
10445}
10446
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010447PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010448 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010449\n\
10450Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010451have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010452
10453static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010454unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010455{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010456 return fixup(self, fixcapitalize);
10457}
10458
10459#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010460PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010461 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462\n\
10463Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010464normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010465
10466static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010467unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468{
10469 PyObject *list;
10470 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010471 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472
Guido van Rossumd57fd912000-03-10 22:53:23 +000010473 /* Split into words */
10474 list = split(self, NULL, -1);
10475 if (!list)
10476 return NULL;
10477
10478 /* Capitalize each word */
10479 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010480 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010481 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482 if (item == NULL)
10483 goto onError;
10484 Py_DECREF(PyList_GET_ITEM(list, i));
10485 PyList_SET_ITEM(list, i, item);
10486 }
10487
10488 /* Join the words to form a new string */
10489 item = PyUnicode_Join(NULL, list);
10490
Benjamin Peterson29060642009-01-31 22:14:21 +000010491 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492 Py_DECREF(list);
10493 return (PyObject *)item;
10494}
10495#endif
10496
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010497/* Argument converter. Coerces to a single unicode character */
10498
10499static int
10500convert_uc(PyObject *obj, void *addr)
10501{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010502 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010503 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010504
Benjamin Peterson14339b62009-01-31 16:36:08 +000010505 uniobj = PyUnicode_FromObject(obj);
10506 if (uniobj == NULL) {
10507 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010508 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010509 return 0;
10510 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010512 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010513 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010514 Py_DECREF(uniobj);
10515 return 0;
10516 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010517 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010518 Py_DECREF(uniobj);
10519 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010520}
10521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010522PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010523 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010525Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010526done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010527
10528static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010529unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010530{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010531 Py_ssize_t marg, left;
10532 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010533 Py_UCS4 fillchar = ' ';
10534
Victor Stinnere9a29352011-10-01 02:14:59 +020010535 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537
Victor Stinnere9a29352011-10-01 02:14:59 +020010538 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010539 return NULL;
10540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010542 Py_INCREF(self);
10543 return (PyObject*) self;
10544 }
10545
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547 left = marg / 2 + (marg & width & 1);
10548
Victor Stinner9310abb2011-10-05 00:59:23 +020010549 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550}
10551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552/* This function assumes that str1 and str2 are readied by the caller. */
10553
Marc-André Lemburge5034372000-08-08 08:04:29 +000010554static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010555unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010556{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010557 int kind1, kind2;
10558 void *data1, *data2;
10559 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 kind1 = PyUnicode_KIND(str1);
10562 kind2 = PyUnicode_KIND(str2);
10563 data1 = PyUnicode_DATA(str1);
10564 data2 = PyUnicode_DATA(str2);
10565 len1 = PyUnicode_GET_LENGTH(str1);
10566 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010567
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010568 for (i = 0; i < len1 && i < len2; ++i) {
10569 Py_UCS4 c1, c2;
10570 c1 = PyUnicode_READ(kind1, data1, i);
10571 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010572
10573 if (c1 != c2)
10574 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010575 }
10576
10577 return (len1 < len2) ? -1 : (len1 != len2);
10578}
10579
Alexander Belopolsky40018472011-02-26 01:02:56 +000010580int
10581PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010582{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010583 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10584 if (PyUnicode_READY(left) == -1 ||
10585 PyUnicode_READY(right) == -1)
10586 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010587 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010589 PyErr_Format(PyExc_TypeError,
10590 "Can't compare %.100s and %.100s",
10591 left->ob_type->tp_name,
10592 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010593 return -1;
10594}
10595
Martin v. Löwis5b222132007-06-10 09:51:05 +000010596int
10597PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10598{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010599 Py_ssize_t i;
10600 int kind;
10601 void *data;
10602 Py_UCS4 chr;
10603
Victor Stinner910337b2011-10-03 03:20:16 +020010604 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010605 if (PyUnicode_READY(uni) == -1)
10606 return -1;
10607 kind = PyUnicode_KIND(uni);
10608 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010609 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10611 if (chr != str[i])
10612 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010613 /* This check keeps Python strings that end in '\0' from comparing equal
10614 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010616 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010617 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010618 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010619 return 0;
10620}
10621
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010622
Benjamin Peterson29060642009-01-31 22:14:21 +000010623#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010624 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010625
Alexander Belopolsky40018472011-02-26 01:02:56 +000010626PyObject *
10627PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010628{
10629 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010630
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010631 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10632 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010633 if (PyUnicode_READY(left) == -1 ||
10634 PyUnicode_READY(right) == -1)
10635 return NULL;
10636 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10637 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010638 if (op == Py_EQ) {
10639 Py_INCREF(Py_False);
10640 return Py_False;
10641 }
10642 if (op == Py_NE) {
10643 Py_INCREF(Py_True);
10644 return Py_True;
10645 }
10646 }
10647 if (left == right)
10648 result = 0;
10649 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010650 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010651
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010652 /* Convert the return value to a Boolean */
10653 switch (op) {
10654 case Py_EQ:
10655 v = TEST_COND(result == 0);
10656 break;
10657 case Py_NE:
10658 v = TEST_COND(result != 0);
10659 break;
10660 case Py_LE:
10661 v = TEST_COND(result <= 0);
10662 break;
10663 case Py_GE:
10664 v = TEST_COND(result >= 0);
10665 break;
10666 case Py_LT:
10667 v = TEST_COND(result == -1);
10668 break;
10669 case Py_GT:
10670 v = TEST_COND(result == 1);
10671 break;
10672 default:
10673 PyErr_BadArgument();
10674 return NULL;
10675 }
10676 Py_INCREF(v);
10677 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010678 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010679
Brian Curtindfc80e32011-08-10 20:28:54 -050010680 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010681}
10682
Alexander Belopolsky40018472011-02-26 01:02:56 +000010683int
10684PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010685{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010686 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010687 int kind1, kind2, kind;
10688 void *buf1, *buf2;
10689 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010690 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010691
10692 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010693 sub = PyUnicode_FromObject(element);
10694 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010695 PyErr_Format(PyExc_TypeError,
10696 "'in <string>' requires string as left operand, not %s",
10697 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010698 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 if (PyUnicode_READY(sub) == -1)
10701 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010702
Thomas Wouters477c8d52006-05-27 19:21:47 +000010703 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010704 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010705 Py_DECREF(sub);
10706 return -1;
10707 }
10708
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 kind1 = PyUnicode_KIND(str);
10710 kind2 = PyUnicode_KIND(sub);
10711 kind = kind1 > kind2 ? kind1 : kind2;
10712 buf1 = PyUnicode_DATA(str);
10713 buf2 = PyUnicode_DATA(sub);
10714 if (kind1 != kind)
10715 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10716 if (!buf1) {
10717 Py_DECREF(sub);
10718 return -1;
10719 }
10720 if (kind2 != kind)
10721 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10722 if (!buf2) {
10723 Py_DECREF(sub);
10724 if (kind1 != kind) PyMem_Free(buf1);
10725 return -1;
10726 }
10727 len1 = PyUnicode_GET_LENGTH(str);
10728 len2 = PyUnicode_GET_LENGTH(sub);
10729
10730 switch(kind) {
10731 case PyUnicode_1BYTE_KIND:
10732 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10733 break;
10734 case PyUnicode_2BYTE_KIND:
10735 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10736 break;
10737 case PyUnicode_4BYTE_KIND:
10738 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10739 break;
10740 default:
10741 result = -1;
10742 assert(0);
10743 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010744
10745 Py_DECREF(str);
10746 Py_DECREF(sub);
10747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010748 if (kind1 != kind)
10749 PyMem_Free(buf1);
10750 if (kind2 != kind)
10751 PyMem_Free(buf2);
10752
Guido van Rossum403d68b2000-03-13 15:55:09 +000010753 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010754}
10755
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756/* Concat to string or Unicode object giving a new Unicode object. */
10757
Alexander Belopolsky40018472011-02-26 01:02:56 +000010758PyObject *
10759PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010762 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763
10764 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010765 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010766 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010767 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010768 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010770 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771
10772 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010773 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010774 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010775 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010777 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010778 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010779 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010780 }
10781
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010782 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010783 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10784 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 w = PyUnicode_New(
10788 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10789 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010790 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010791 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010792 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10793 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010794 Py_DECREF(u);
10795 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010796 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010798
Benjamin Peterson29060642009-01-31 22:14:21 +000010799 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800 Py_XDECREF(u);
10801 Py_XDECREF(v);
10802 return NULL;
10803}
10804
Victor Stinnerb0923652011-10-04 01:17:31 +020010805static void
10806unicode_append_inplace(PyObject **p_left, PyObject *right)
10807{
10808 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010809
10810 assert(PyUnicode_IS_READY(*p_left));
10811 assert(PyUnicode_IS_READY(right));
10812
10813 left_len = PyUnicode_GET_LENGTH(*p_left);
10814 right_len = PyUnicode_GET_LENGTH(right);
10815 if (left_len > PY_SSIZE_T_MAX - right_len) {
10816 PyErr_SetString(PyExc_OverflowError,
10817 "strings are too large to concat");
10818 goto error;
10819 }
10820 new_len = left_len + right_len;
10821
10822 /* Now we own the last reference to 'left', so we can resize it
10823 * in-place.
10824 */
10825 if (unicode_resize(p_left, new_len) != 0) {
10826 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10827 * deallocated so it cannot be put back into
10828 * 'variable'. The MemoryError is raised when there
10829 * is no value in 'variable', which might (very
10830 * remotely) be a cause of incompatibilities.
10831 */
10832 goto error;
10833 }
10834 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010835 copy_characters(*p_left, left_len, right, 0, right_len);
10836 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010837 return;
10838
10839error:
10840 Py_DECREF(*p_left);
10841 *p_left = NULL;
10842}
10843
Walter Dörwald1ab83302007-05-18 17:15:44 +000010844void
Victor Stinner23e56682011-10-03 03:54:37 +020010845PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010846{
Victor Stinner23e56682011-10-03 03:54:37 +020010847 PyObject *left, *res;
10848
10849 if (p_left == NULL) {
10850 if (!PyErr_Occurred())
10851 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010852 return;
10853 }
Victor Stinner23e56682011-10-03 03:54:37 +020010854 left = *p_left;
10855 if (right == NULL || !PyUnicode_Check(left)) {
10856 if (!PyErr_Occurred())
10857 PyErr_BadInternalCall();
10858 goto error;
10859 }
10860
Victor Stinnere1335c72011-10-04 20:53:03 +020010861 if (PyUnicode_READY(left))
10862 goto error;
10863 if (PyUnicode_READY(right))
10864 goto error;
10865
Victor Stinner23e56682011-10-03 03:54:37 +020010866 if (PyUnicode_CheckExact(left) && left != unicode_empty
10867 && PyUnicode_CheckExact(right) && right != unicode_empty
10868 && unicode_resizable(left)
10869 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10870 || _PyUnicode_WSTR(left) != NULL))
10871 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010872 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10873 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010874 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010875 not so different than duplicating the string. */
10876 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010877 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010878 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010879 if (p_left != NULL)
10880 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010881 return;
10882 }
10883 }
10884
10885 res = PyUnicode_Concat(left, right);
10886 if (res == NULL)
10887 goto error;
10888 Py_DECREF(left);
10889 *p_left = res;
10890 return;
10891
10892error:
10893 Py_DECREF(*p_left);
10894 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010895}
10896
10897void
10898PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10899{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010900 PyUnicode_Append(pleft, right);
10901 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010902}
10903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010904PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010905 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010906\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010907Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010908string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010909interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910
10911static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010912unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010914 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010915 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010916 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010918 int kind1, kind2, kind;
10919 void *buf1, *buf2;
10920 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010921
Jesus Ceaac451502011-04-20 17:09:23 +020010922 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10923 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010924 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010925
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010926 kind1 = PyUnicode_KIND(self);
10927 kind2 = PyUnicode_KIND(substring);
10928 kind = kind1 > kind2 ? kind1 : kind2;
10929 buf1 = PyUnicode_DATA(self);
10930 buf2 = PyUnicode_DATA(substring);
10931 if (kind1 != kind)
10932 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10933 if (!buf1) {
10934 Py_DECREF(substring);
10935 return NULL;
10936 }
10937 if (kind2 != kind)
10938 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10939 if (!buf2) {
10940 Py_DECREF(substring);
10941 if (kind1 != kind) PyMem_Free(buf1);
10942 return NULL;
10943 }
10944 len1 = PyUnicode_GET_LENGTH(self);
10945 len2 = PyUnicode_GET_LENGTH(substring);
10946
10947 ADJUST_INDICES(start, end, len1);
10948 switch(kind) {
10949 case PyUnicode_1BYTE_KIND:
10950 iresult = ucs1lib_count(
10951 ((Py_UCS1*)buf1) + start, end - start,
10952 buf2, len2, PY_SSIZE_T_MAX
10953 );
10954 break;
10955 case PyUnicode_2BYTE_KIND:
10956 iresult = ucs2lib_count(
10957 ((Py_UCS2*)buf1) + start, end - start,
10958 buf2, len2, PY_SSIZE_T_MAX
10959 );
10960 break;
10961 case PyUnicode_4BYTE_KIND:
10962 iresult = ucs4lib_count(
10963 ((Py_UCS4*)buf1) + start, end - start,
10964 buf2, len2, PY_SSIZE_T_MAX
10965 );
10966 break;
10967 default:
10968 assert(0); iresult = 0;
10969 }
10970
10971 result = PyLong_FromSsize_t(iresult);
10972
10973 if (kind1 != kind)
10974 PyMem_Free(buf1);
10975 if (kind2 != kind)
10976 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977
10978 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010979
Guido van Rossumd57fd912000-03-10 22:53:23 +000010980 return result;
10981}
10982
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010983PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010984 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010986Encode S using the codec registered for encoding. Default encoding\n\
10987is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010988handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010989a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10990'xmlcharrefreplace' as well as any other name registered with\n\
10991codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992
10993static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010994unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010996 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997 char *encoding = NULL;
10998 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010999
Benjamin Peterson308d6372009-09-18 21:42:35 +000011000 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11001 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011002 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011003 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011004}
11005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011006PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011007 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008\n\
11009Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011010If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011
11012static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011013unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011015 Py_ssize_t i, j, line_pos, src_len, incr;
11016 Py_UCS4 ch;
11017 PyObject *u;
11018 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011020 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011021 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022
11023 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011025
Antoine Pitrou22425222011-10-04 19:10:51 +020011026 if (PyUnicode_READY(self) == -1)
11027 return NULL;
11028
Thomas Wouters7e474022000-07-16 12:04:32 +000011029 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011030 src_len = PyUnicode_GET_LENGTH(self);
11031 i = j = line_pos = 0;
11032 kind = PyUnicode_KIND(self);
11033 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011034 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011035 for (; i < src_len; i++) {
11036 ch = PyUnicode_READ(kind, src_data, i);
11037 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011038 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011039 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011040 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011041 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011042 goto overflow;
11043 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011044 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011045 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011046 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011048 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011049 goto overflow;
11050 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011051 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011052 if (ch == '\n' || ch == '\r')
11053 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011055 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011056 if (!found && PyUnicode_CheckExact(self)) {
11057 Py_INCREF((PyObject *) self);
11058 return (PyObject *) self;
11059 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011060
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011062 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063 if (!u)
11064 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011065 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066
Antoine Pitroue71d5742011-10-04 15:55:09 +020011067 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011068
Antoine Pitroue71d5742011-10-04 15:55:09 +020011069 for (; i < src_len; i++) {
11070 ch = PyUnicode_READ(kind, src_data, i);
11071 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011072 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011073 incr = tabsize - (line_pos % tabsize);
11074 line_pos += incr;
11075 while (incr--) {
11076 PyUnicode_WRITE(kind, dest_data, j, ' ');
11077 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011078 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011079 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011080 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011081 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011082 line_pos++;
11083 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011084 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011085 if (ch == '\n' || ch == '\r')
11086 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011088 }
11089 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011090#ifndef DONT_MAKE_RESULT_READY
11091 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011092 Py_DECREF(u);
11093 return NULL;
11094 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011095#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011096 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011098
Antoine Pitroue71d5742011-10-04 15:55:09 +020011099 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011100 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11101 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102}
11103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011104PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011105 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106\n\
11107Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011108such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109arguments start and end are interpreted as in slice notation.\n\
11110\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011111Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112
11113static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011114unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011116 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011117 Py_ssize_t start;
11118 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011119 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011120
Jesus Ceaac451502011-04-20 17:09:23 +020011121 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11122 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011125 if (PyUnicode_READY(self) == -1)
11126 return NULL;
11127 if (PyUnicode_READY(substring) == -1)
11128 return NULL;
11129
Victor Stinner794d5672011-10-10 03:21:36 +020011130 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011131 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011132 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133
11134 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011135
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136 if (result == -2)
11137 return NULL;
11138
Christian Heimes217cfd12007-12-02 14:31:20 +000011139 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140}
11141
11142static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011143unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011145 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11146 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011148 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011149}
11150
Guido van Rossumc2504932007-09-18 19:42:40 +000011151/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011152 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011153static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011154unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155{
Guido van Rossumc2504932007-09-18 19:42:40 +000011156 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011157 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 if (_PyUnicode_HASH(self) != -1)
11160 return _PyUnicode_HASH(self);
11161 if (PyUnicode_READY(self) == -1)
11162 return -1;
11163 len = PyUnicode_GET_LENGTH(self);
11164
11165 /* The hash function as a macro, gets expanded three times below. */
11166#define HASH(P) \
11167 x = (Py_uhash_t)*P << 7; \
11168 while (--len >= 0) \
11169 x = (1000003*x) ^ (Py_uhash_t)*P++;
11170
11171 switch (PyUnicode_KIND(self)) {
11172 case PyUnicode_1BYTE_KIND: {
11173 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11174 HASH(c);
11175 break;
11176 }
11177 case PyUnicode_2BYTE_KIND: {
11178 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11179 HASH(s);
11180 break;
11181 }
11182 default: {
11183 Py_UCS4 *l;
11184 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11185 "Impossible switch case in unicode_hash");
11186 l = PyUnicode_4BYTE_DATA(self);
11187 HASH(l);
11188 break;
11189 }
11190 }
11191 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11192
Guido van Rossumc2504932007-09-18 19:42:40 +000011193 if (x == -1)
11194 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011196 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011199
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011200PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011201 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011202\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011203Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204
11205static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011208 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011209 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011210 Py_ssize_t start;
11211 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212
Jesus Ceaac451502011-04-20 17:09:23 +020011213 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11214 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217 if (PyUnicode_READY(self) == -1)
11218 return NULL;
11219 if (PyUnicode_READY(substring) == -1)
11220 return NULL;
11221
Victor Stinner794d5672011-10-10 03:21:36 +020011222 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011224 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225
11226 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 if (result == -2)
11229 return NULL;
11230
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231 if (result < 0) {
11232 PyErr_SetString(PyExc_ValueError, "substring not found");
11233 return NULL;
11234 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011235
Christian Heimes217cfd12007-12-02 14:31:20 +000011236 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011237}
11238
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011239PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011240 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011242Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011243at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
11245static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011246unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 Py_ssize_t i, length;
11249 int kind;
11250 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 int cased;
11252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 if (PyUnicode_READY(self) == -1)
11254 return NULL;
11255 length = PyUnicode_GET_LENGTH(self);
11256 kind = PyUnicode_KIND(self);
11257 data = PyUnicode_DATA(self);
11258
Guido van Rossumd57fd912000-03-10 22:53:23 +000011259 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011260 if (length == 1)
11261 return PyBool_FromLong(
11262 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011264 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011265 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011266 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011267
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 for (i = 0; i < length; i++) {
11270 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011271
Benjamin Peterson29060642009-01-31 22:14:21 +000011272 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11273 return PyBool_FromLong(0);
11274 else if (!cased && Py_UNICODE_ISLOWER(ch))
11275 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011277 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278}
11279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011280PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011281 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011283Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011284at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285
11286static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011287unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 Py_ssize_t i, length;
11290 int kind;
11291 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292 int cased;
11293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 if (PyUnicode_READY(self) == -1)
11295 return NULL;
11296 length = PyUnicode_GET_LENGTH(self);
11297 kind = PyUnicode_KIND(self);
11298 data = PyUnicode_DATA(self);
11299
Guido van Rossumd57fd912000-03-10 22:53:23 +000011300 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 if (length == 1)
11302 return PyBool_FromLong(
11303 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011305 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011306 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011307 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011308
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310 for (i = 0; i < length; i++) {
11311 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011312
Benjamin Peterson29060642009-01-31 22:14:21 +000011313 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11314 return PyBool_FromLong(0);
11315 else if (!cased && Py_UNICODE_ISUPPER(ch))
11316 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011317 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011318 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319}
11320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011321PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011322 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011324Return True if S is a titlecased string and there is at least one\n\
11325character in S, i.e. upper- and titlecase characters may only\n\
11326follow uncased characters and lowercase characters only cased ones.\n\
11327Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328
11329static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011330unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011331{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 Py_ssize_t i, length;
11333 int kind;
11334 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011335 int cased, previous_is_cased;
11336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 if (PyUnicode_READY(self) == -1)
11338 return NULL;
11339 length = PyUnicode_GET_LENGTH(self);
11340 kind = PyUnicode_KIND(self);
11341 data = PyUnicode_DATA(self);
11342
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 if (length == 1) {
11345 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11346 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11347 (Py_UNICODE_ISUPPER(ch) != 0));
11348 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011349
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011350 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011352 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011353
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354 cased = 0;
11355 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 for (i = 0; i < length; i++) {
11357 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011358
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11360 if (previous_is_cased)
11361 return PyBool_FromLong(0);
11362 previous_is_cased = 1;
11363 cased = 1;
11364 }
11365 else if (Py_UNICODE_ISLOWER(ch)) {
11366 if (!previous_is_cased)
11367 return PyBool_FromLong(0);
11368 previous_is_cased = 1;
11369 cased = 1;
11370 }
11371 else
11372 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011374 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375}
11376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011380Return True if all characters in S are whitespace\n\
11381and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382
11383static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011384unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 Py_ssize_t i, length;
11387 int kind;
11388 void *data;
11389
11390 if (PyUnicode_READY(self) == -1)
11391 return NULL;
11392 length = PyUnicode_GET_LENGTH(self);
11393 kind = PyUnicode_KIND(self);
11394 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011397 if (length == 1)
11398 return PyBool_FromLong(
11399 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011400
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011401 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 for (i = 0; i < length; i++) {
11406 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011407 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011410 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011415\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011416Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011417and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011418
11419static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011420unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 Py_ssize_t i, length;
11423 int kind;
11424 void *data;
11425
11426 if (PyUnicode_READY(self) == -1)
11427 return NULL;
11428 length = PyUnicode_GET_LENGTH(self);
11429 kind = PyUnicode_KIND(self);
11430 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011431
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011432 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 if (length == 1)
11434 return PyBool_FromLong(
11435 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011436
11437 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 for (i = 0; i < length; i++) {
11442 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011443 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011444 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011445 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011446}
11447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011448PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011450\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011451Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011452and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011453
11454static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011455unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011456{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 int kind;
11458 void *data;
11459 Py_ssize_t len, i;
11460
11461 if (PyUnicode_READY(self) == -1)
11462 return NULL;
11463
11464 kind = PyUnicode_KIND(self);
11465 data = PyUnicode_DATA(self);
11466 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011467
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011468 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (len == 1) {
11470 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11471 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11472 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011473
11474 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 for (i = 0; i < len; i++) {
11479 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011480 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011481 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011482 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011483 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011484}
11485
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011486PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011487 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011488\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011489Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011490False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491
11492static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011493unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 Py_ssize_t i, length;
11496 int kind;
11497 void *data;
11498
11499 if (PyUnicode_READY(self) == -1)
11500 return NULL;
11501 length = PyUnicode_GET_LENGTH(self);
11502 kind = PyUnicode_KIND(self);
11503 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011504
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 if (length == 1)
11507 return PyBool_FromLong(
11508 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011509
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011510 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 for (i = 0; i < length; i++) {
11515 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011516 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011517 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011518 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011519}
11520
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011521PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011524Return True if all characters in S are digits\n\
11525and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526
11527static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011528unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 Py_ssize_t i, length;
11531 int kind;
11532 void *data;
11533
11534 if (PyUnicode_READY(self) == -1)
11535 return NULL;
11536 length = PyUnicode_GET_LENGTH(self);
11537 kind = PyUnicode_KIND(self);
11538 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011541 if (length == 1) {
11542 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11543 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11544 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011546 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 for (i = 0; i < length; i++) {
11551 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011554 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555}
11556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011557PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011560Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011561False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562
11563static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011564unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 Py_ssize_t i, length;
11567 int kind;
11568 void *data;
11569
11570 if (PyUnicode_READY(self) == -1)
11571 return NULL;
11572 length = PyUnicode_GET_LENGTH(self);
11573 kind = PyUnicode_KIND(self);
11574 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 if (length == 1)
11578 return PyBool_FromLong(
11579 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011581 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011582 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011583 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 for (i = 0; i < length; i++) {
11586 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011587 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011589 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011590}
11591
Martin v. Löwis47383402007-08-15 07:32:56 +000011592int
11593PyUnicode_IsIdentifier(PyObject *self)
11594{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595 int kind;
11596 void *data;
11597 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011598 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011600 if (PyUnicode_READY(self) == -1) {
11601 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011602 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011603 }
11604
11605 /* Special case for empty strings */
11606 if (PyUnicode_GET_LENGTH(self) == 0)
11607 return 0;
11608 kind = PyUnicode_KIND(self);
11609 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011610
11611 /* PEP 3131 says that the first character must be in
11612 XID_Start and subsequent characters in XID_Continue,
11613 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011614 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011615 letters, digits, underscore). However, given the current
11616 definition of XID_Start and XID_Continue, it is sufficient
11617 to check just for these, except that _ must be allowed
11618 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011620 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011621 return 0;
11622
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011623 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011624 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011625 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011626 return 1;
11627}
11628
11629PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011630 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011631\n\
11632Return True if S is a valid identifier according\n\
11633to the language definition.");
11634
11635static PyObject*
11636unicode_isidentifier(PyObject *self)
11637{
11638 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11639}
11640
Georg Brandl559e5d72008-06-11 18:37:52 +000011641PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011642 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011643\n\
11644Return True if all characters in S are considered\n\
11645printable in repr() or S is empty, False otherwise.");
11646
11647static PyObject*
11648unicode_isprintable(PyObject *self)
11649{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011650 Py_ssize_t i, length;
11651 int kind;
11652 void *data;
11653
11654 if (PyUnicode_READY(self) == -1)
11655 return NULL;
11656 length = PyUnicode_GET_LENGTH(self);
11657 kind = PyUnicode_KIND(self);
11658 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011659
11660 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011661 if (length == 1)
11662 return PyBool_FromLong(
11663 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011664
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011665 for (i = 0; i < length; i++) {
11666 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011667 Py_RETURN_FALSE;
11668 }
11669 }
11670 Py_RETURN_TRUE;
11671}
11672
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011673PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011674 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011675\n\
11676Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011677iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011678
11679static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011680unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011681{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011682 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011683}
11684
Martin v. Löwis18e16552006-02-15 17:27:45 +000011685static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011686unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 if (PyUnicode_READY(self) == -1)
11689 return -1;
11690 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011691}
11692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011693PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011696Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011697done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698
11699static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011700unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011702 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011703 Py_UCS4 fillchar = ' ';
11704
11705 if (PyUnicode_READY(self) == -1)
11706 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011707
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011708 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709 return NULL;
11710
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712 Py_INCREF(self);
11713 return (PyObject*) self;
11714 }
11715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717}
11718
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011719PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011720 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011722Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723
11724static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011725unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727 return fixup(self, fixlower);
11728}
11729
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730#define LEFTSTRIP 0
11731#define RIGHTSTRIP 1
11732#define BOTHSTRIP 2
11733
11734/* Arrays indexed by above */
11735static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11736
11737#define STRIPNAME(i) (stripformat[i]+3)
11738
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739/* externally visible for str.strip(unicode) */
11740PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011741_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011742{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011743 void *data;
11744 int kind;
11745 Py_ssize_t i, j, len;
11746 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011747
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011748 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11749 return NULL;
11750
11751 kind = PyUnicode_KIND(self);
11752 data = PyUnicode_DATA(self);
11753 len = PyUnicode_GET_LENGTH(self);
11754 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11755 PyUnicode_DATA(sepobj),
11756 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011757
Benjamin Peterson14339b62009-01-31 16:36:08 +000011758 i = 0;
11759 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011760 while (i < len &&
11761 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011762 i++;
11763 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011764 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765
Benjamin Peterson14339b62009-01-31 16:36:08 +000011766 j = len;
11767 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011768 do {
11769 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011770 } while (j >= i &&
11771 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011772 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011773 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774
Victor Stinner12bab6d2011-10-01 01:53:49 +020011775 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011776}
11777
11778PyObject*
11779PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11780{
11781 unsigned char *data;
11782 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011783 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784
Victor Stinnerde636f32011-10-01 03:55:54 +020011785 if (PyUnicode_READY(self) == -1)
11786 return NULL;
11787
11788 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11789
Victor Stinner12bab6d2011-10-01 01:53:49 +020011790 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011792 if (PyUnicode_CheckExact(self)) {
11793 Py_INCREF(self);
11794 return self;
11795 }
11796 else
11797 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011798 }
11799
Victor Stinner12bab6d2011-10-01 01:53:49 +020011800 length = end - start;
11801 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011802 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803
Victor Stinnerde636f32011-10-01 03:55:54 +020011804 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011805 PyErr_SetString(PyExc_IndexError, "string index out of range");
11806 return NULL;
11807 }
11808
Victor Stinnerb9275c12011-10-05 14:01:42 +020011809 if (PyUnicode_IS_ASCII(self)) {
11810 kind = PyUnicode_KIND(self);
11811 data = PyUnicode_1BYTE_DATA(self);
11812 return unicode_fromascii(data + start, length);
11813 }
11814 else {
11815 kind = PyUnicode_KIND(self);
11816 data = PyUnicode_1BYTE_DATA(self);
11817 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011818 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011819 length);
11820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011822
11823static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011824do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011826 int kind;
11827 void *data;
11828 Py_ssize_t len, i, j;
11829
11830 if (PyUnicode_READY(self) == -1)
11831 return NULL;
11832
11833 kind = PyUnicode_KIND(self);
11834 data = PyUnicode_DATA(self);
11835 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011836
Benjamin Peterson14339b62009-01-31 16:36:08 +000011837 i = 0;
11838 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011840 i++;
11841 }
11842 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011843
Benjamin Peterson14339b62009-01-31 16:36:08 +000011844 j = len;
11845 if (striptype != LEFTSTRIP) {
11846 do {
11847 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011849 j++;
11850 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011851
Victor Stinner12bab6d2011-10-01 01:53:49 +020011852 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853}
11854
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011855
11856static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011857do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011858{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011859 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011860
Benjamin Peterson14339b62009-01-31 16:36:08 +000011861 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11862 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011863
Benjamin Peterson14339b62009-01-31 16:36:08 +000011864 if (sep != NULL && sep != Py_None) {
11865 if (PyUnicode_Check(sep))
11866 return _PyUnicode_XStrip(self, striptype, sep);
11867 else {
11868 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011869 "%s arg must be None or str",
11870 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011871 return NULL;
11872 }
11873 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011874
Benjamin Peterson14339b62009-01-31 16:36:08 +000011875 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011876}
11877
11878
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011879PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011880 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011881\n\
11882Return a copy of the string S with leading and trailing\n\
11883whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011884If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011885
11886static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011887unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011888{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011889 if (PyTuple_GET_SIZE(args) == 0)
11890 return do_strip(self, BOTHSTRIP); /* Common case */
11891 else
11892 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011893}
11894
11895
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011896PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011898\n\
11899Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011900If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011901
11902static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011903unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011904{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011905 if (PyTuple_GET_SIZE(args) == 0)
11906 return do_strip(self, LEFTSTRIP); /* Common case */
11907 else
11908 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011909}
11910
11911
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011912PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011913 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011914\n\
11915Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011916If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011917
11918static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011919unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011920{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011921 if (PyTuple_GET_SIZE(args) == 0)
11922 return do_strip(self, RIGHTSTRIP); /* Common case */
11923 else
11924 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011925}
11926
11927
Guido van Rossumd57fd912000-03-10 22:53:23 +000011928static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011929unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011931 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933
Georg Brandl222de0f2009-04-12 12:01:50 +000011934 if (len < 1) {
11935 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011936 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011937 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011938
Tim Peters7a29bd52001-09-12 03:03:31 +000011939 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011940 /* no repeat, return original string */
11941 Py_INCREF(str);
11942 return (PyObject*) str;
11943 }
Tim Peters8f422462000-09-09 06:13:41 +000011944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011945 if (PyUnicode_READY(str) == -1)
11946 return NULL;
11947
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011948 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011949 PyErr_SetString(PyExc_OverflowError,
11950 "repeated string is too long");
11951 return NULL;
11952 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011954
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011955 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011956 if (!u)
11957 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011958 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011960 if (PyUnicode_GET_LENGTH(str) == 1) {
11961 const int kind = PyUnicode_KIND(str);
11962 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11963 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011964 if (kind == PyUnicode_1BYTE_KIND)
11965 memset(to, (unsigned char)fill_char, len);
11966 else {
11967 for (n = 0; n < len; ++n)
11968 PyUnicode_WRITE(kind, to, n, fill_char);
11969 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 }
11971 else {
11972 /* number of characters copied this far */
11973 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011974 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011975 char *to = (char *) PyUnicode_DATA(u);
11976 Py_MEMCPY(to, PyUnicode_DATA(str),
11977 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011978 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 n = (done <= nchars-done) ? done : nchars-done;
11980 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011981 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011982 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011983 }
11984
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011985 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011986 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011987}
11988
Alexander Belopolsky40018472011-02-26 01:02:56 +000011989PyObject *
11990PyUnicode_Replace(PyObject *obj,
11991 PyObject *subobj,
11992 PyObject *replobj,
11993 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011994{
11995 PyObject *self;
11996 PyObject *str1;
11997 PyObject *str2;
11998 PyObject *result;
11999
12000 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012001 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012004 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 Py_DECREF(self);
12006 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007 }
12008 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012009 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012010 Py_DECREF(self);
12011 Py_DECREF(str1);
12012 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012015 Py_DECREF(self);
12016 Py_DECREF(str1);
12017 Py_DECREF(str2);
12018 return result;
12019}
12020
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012021PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012022 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023\n\
12024Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012025old replaced by new. If the optional argument count is\n\
12026given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027
12028static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012031 PyObject *str1;
12032 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012033 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012034 PyObject *result;
12035
Martin v. Löwis18e16552006-02-15 17:27:45 +000012036 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012037 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012039 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 str1 = PyUnicode_FromObject(str1);
12041 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12042 return NULL;
12043 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012044 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012045 Py_DECREF(str1);
12046 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012047 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012048
12049 result = replace(self, str1, str2, maxcount);
12050
12051 Py_DECREF(str1);
12052 Py_DECREF(str2);
12053 return result;
12054}
12055
Alexander Belopolsky40018472011-02-26 01:02:56 +000012056static PyObject *
12057unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012058{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012059 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 Py_ssize_t isize;
12061 Py_ssize_t osize, squote, dquote, i, o;
12062 Py_UCS4 max, quote;
12063 int ikind, okind;
12064 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012066 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012067 return NULL;
12068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 isize = PyUnicode_GET_LENGTH(unicode);
12070 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012071
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012072 /* Compute length of output, quote characters, and
12073 maximum character */
12074 osize = 2; /* quotes */
12075 max = 127;
12076 squote = dquote = 0;
12077 ikind = PyUnicode_KIND(unicode);
12078 for (i = 0; i < isize; i++) {
12079 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12080 switch (ch) {
12081 case '\'': squote++; osize++; break;
12082 case '"': dquote++; osize++; break;
12083 case '\\': case '\t': case '\r': case '\n':
12084 osize += 2; break;
12085 default:
12086 /* Fast-path ASCII */
12087 if (ch < ' ' || ch == 0x7f)
12088 osize += 4; /* \xHH */
12089 else if (ch < 0x7f)
12090 osize++;
12091 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12092 osize++;
12093 max = ch > max ? ch : max;
12094 }
12095 else if (ch < 0x100)
12096 osize += 4; /* \xHH */
12097 else if (ch < 0x10000)
12098 osize += 6; /* \uHHHH */
12099 else
12100 osize += 10; /* \uHHHHHHHH */
12101 }
12102 }
12103
12104 quote = '\'';
12105 if (squote) {
12106 if (dquote)
12107 /* Both squote and dquote present. Use squote,
12108 and escape them */
12109 osize += squote;
12110 else
12111 quote = '"';
12112 }
12113
12114 repr = PyUnicode_New(osize, max);
12115 if (repr == NULL)
12116 return NULL;
12117 okind = PyUnicode_KIND(repr);
12118 odata = PyUnicode_DATA(repr);
12119
12120 PyUnicode_WRITE(okind, odata, 0, quote);
12121 PyUnicode_WRITE(okind, odata, osize-1, quote);
12122
12123 for (i = 0, o = 1; i < isize; i++) {
12124 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012125
12126 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012127 if ((ch == quote) || (ch == '\\')) {
12128 PyUnicode_WRITE(okind, odata, o++, '\\');
12129 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012130 continue;
12131 }
12132
Benjamin Peterson29060642009-01-31 22:14:21 +000012133 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012134 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012135 PyUnicode_WRITE(okind, odata, o++, '\\');
12136 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012137 }
12138 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 PyUnicode_WRITE(okind, odata, o++, '\\');
12140 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012141 }
12142 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012143 PyUnicode_WRITE(okind, odata, o++, '\\');
12144 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012145 }
12146
12147 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012148 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149 PyUnicode_WRITE(okind, odata, o++, '\\');
12150 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012151 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12152 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012153 }
12154
Georg Brandl559e5d72008-06-11 18:37:52 +000012155 /* Copy ASCII characters as-is */
12156 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012158 }
12159
Benjamin Peterson29060642009-01-31 22:14:21 +000012160 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012161 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012162 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012163 (categories Z* and C* except ASCII space)
12164 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012165 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012166 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012167 if (ch <= 0xff) {
12168 PyUnicode_WRITE(okind, odata, o++, '\\');
12169 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012170 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12171 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012172 }
12173 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 else if (ch >= 0x10000) {
12175 PyUnicode_WRITE(okind, odata, o++, '\\');
12176 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012177 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12178 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12179 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12180 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12181 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12182 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12183 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12184 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012185 }
12186 /* Map 16-bit characters to '\uxxxx' */
12187 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012188 PyUnicode_WRITE(okind, odata, o++, '\\');
12189 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012190 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12191 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12192 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12193 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012194 }
12195 }
12196 /* Copy characters as-is */
12197 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012199 }
12200 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012201 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012202 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012203 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012204 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205}
12206
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012207PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012208 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209\n\
12210Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012211such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212arguments start and end are interpreted as in slice notation.\n\
12213\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012214Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215
12216static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012219 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012220 Py_ssize_t start;
12221 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012222 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223
Jesus Ceaac451502011-04-20 17:09:23 +020012224 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12225 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012226 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012228 if (PyUnicode_READY(self) == -1)
12229 return NULL;
12230 if (PyUnicode_READY(substring) == -1)
12231 return NULL;
12232
Victor Stinner794d5672011-10-10 03:21:36 +020012233 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012234 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012235 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236
12237 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 if (result == -2)
12240 return NULL;
12241
Christian Heimes217cfd12007-12-02 14:31:20 +000012242 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243}
12244
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012245PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012246 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012248Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012249
12250static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012251unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012252{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012253 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012254 Py_ssize_t start;
12255 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012256 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
Jesus Ceaac451502011-04-20 17:09:23 +020012258 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12259 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012260 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 if (PyUnicode_READY(self) == -1)
12263 return NULL;
12264 if (PyUnicode_READY(substring) == -1)
12265 return NULL;
12266
Victor Stinner794d5672011-10-10 03:21:36 +020012267 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012269 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012270
12271 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012272
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012273 if (result == -2)
12274 return NULL;
12275
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276 if (result < 0) {
12277 PyErr_SetString(PyExc_ValueError, "substring not found");
12278 return NULL;
12279 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012280
Christian Heimes217cfd12007-12-02 14:31:20 +000012281 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012282}
12283
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012284PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012285 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012286\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012287Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012288done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289
12290static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012291unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012292{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012293 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012294 Py_UCS4 fillchar = ' ';
12295
Victor Stinnere9a29352011-10-01 02:14:59 +020012296 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012298
Victor Stinnere9a29352011-10-01 02:14:59 +020012299 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012300 return NULL;
12301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012303 Py_INCREF(self);
12304 return (PyObject*) self;
12305 }
12306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308}
12309
Alexander Belopolsky40018472011-02-26 01:02:56 +000012310PyObject *
12311PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312{
12313 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012314
Guido van Rossumd57fd912000-03-10 22:53:23 +000012315 s = PyUnicode_FromObject(s);
12316 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012317 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012318 if (sep != NULL) {
12319 sep = PyUnicode_FromObject(sep);
12320 if (sep == NULL) {
12321 Py_DECREF(s);
12322 return NULL;
12323 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012324 }
12325
Victor Stinner9310abb2011-10-05 00:59:23 +020012326 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327
12328 Py_DECREF(s);
12329 Py_XDECREF(sep);
12330 return result;
12331}
12332
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012333PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012334 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012335\n\
12336Return a list of the words in S, using sep as the\n\
12337delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012338splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012339whitespace string is a separator and empty strings are\n\
12340removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012341
12342static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012343unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344{
12345 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012346 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012347
Martin v. Löwis18e16552006-02-15 17:27:45 +000012348 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012349 return NULL;
12350
12351 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012352 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012353 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012354 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012355 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012356 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012357}
12358
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359PyObject *
12360PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12361{
12362 PyObject* str_obj;
12363 PyObject* sep_obj;
12364 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 int kind1, kind2, kind;
12366 void *buf1 = NULL, *buf2 = NULL;
12367 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012368
12369 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012370 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012371 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012373 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012374 Py_DECREF(str_obj);
12375 return NULL;
12376 }
12377
Victor Stinner14f8f022011-10-05 20:58:25 +020012378 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012380 kind = Py_MAX(kind1, kind2);
12381 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012383 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 if (!buf1)
12385 goto onError;
12386 buf2 = PyUnicode_DATA(sep_obj);
12387 if (kind2 != kind)
12388 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12389 if (!buf2)
12390 goto onError;
12391 len1 = PyUnicode_GET_LENGTH(str_obj);
12392 len2 = PyUnicode_GET_LENGTH(sep_obj);
12393
Victor Stinner14f8f022011-10-05 20:58:25 +020012394 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012395 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012396 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12397 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12398 else
12399 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 break;
12401 case PyUnicode_2BYTE_KIND:
12402 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12403 break;
12404 case PyUnicode_4BYTE_KIND:
12405 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12406 break;
12407 default:
12408 assert(0);
12409 out = 0;
12410 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012411
12412 Py_DECREF(sep_obj);
12413 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 if (kind1 != kind)
12415 PyMem_Free(buf1);
12416 if (kind2 != kind)
12417 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012418
12419 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 onError:
12421 Py_DECREF(sep_obj);
12422 Py_DECREF(str_obj);
12423 if (kind1 != kind && buf1)
12424 PyMem_Free(buf1);
12425 if (kind2 != kind && buf2)
12426 PyMem_Free(buf2);
12427 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012428}
12429
12430
12431PyObject *
12432PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12433{
12434 PyObject* str_obj;
12435 PyObject* sep_obj;
12436 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012437 int kind1, kind2, kind;
12438 void *buf1 = NULL, *buf2 = NULL;
12439 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012440
12441 str_obj = PyUnicode_FromObject(str_in);
12442 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012443 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012444 sep_obj = PyUnicode_FromObject(sep_in);
12445 if (!sep_obj) {
12446 Py_DECREF(str_obj);
12447 return NULL;
12448 }
12449
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 kind1 = PyUnicode_KIND(str_in);
12451 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012452 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012453 buf1 = PyUnicode_DATA(str_in);
12454 if (kind1 != kind)
12455 buf1 = _PyUnicode_AsKind(str_in, kind);
12456 if (!buf1)
12457 goto onError;
12458 buf2 = PyUnicode_DATA(sep_obj);
12459 if (kind2 != kind)
12460 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12461 if (!buf2)
12462 goto onError;
12463 len1 = PyUnicode_GET_LENGTH(str_obj);
12464 len2 = PyUnicode_GET_LENGTH(sep_obj);
12465
12466 switch(PyUnicode_KIND(str_in)) {
12467 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012468 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12469 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12470 else
12471 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 break;
12473 case PyUnicode_2BYTE_KIND:
12474 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12475 break;
12476 case PyUnicode_4BYTE_KIND:
12477 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12478 break;
12479 default:
12480 assert(0);
12481 out = 0;
12482 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012483
12484 Py_DECREF(sep_obj);
12485 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 if (kind1 != kind)
12487 PyMem_Free(buf1);
12488 if (kind2 != kind)
12489 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012490
12491 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012492 onError:
12493 Py_DECREF(sep_obj);
12494 Py_DECREF(str_obj);
12495 if (kind1 != kind && buf1)
12496 PyMem_Free(buf1);
12497 if (kind2 != kind && buf2)
12498 PyMem_Free(buf2);
12499 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012500}
12501
12502PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012503 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012504\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012505Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012506the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012507found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012508
12509static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012510unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012511{
Victor Stinner9310abb2011-10-05 00:59:23 +020012512 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012513}
12514
12515PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012516 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012517\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012518Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012520separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012521
12522static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012523unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012524{
Victor Stinner9310abb2011-10-05 00:59:23 +020012525 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526}
12527
Alexander Belopolsky40018472011-02-26 01:02:56 +000012528PyObject *
12529PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012530{
12531 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012532
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012533 s = PyUnicode_FromObject(s);
12534 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012535 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012536 if (sep != NULL) {
12537 sep = PyUnicode_FromObject(sep);
12538 if (sep == NULL) {
12539 Py_DECREF(s);
12540 return NULL;
12541 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012542 }
12543
Victor Stinner9310abb2011-10-05 00:59:23 +020012544 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012545
12546 Py_DECREF(s);
12547 Py_XDECREF(sep);
12548 return result;
12549}
12550
12551PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012552 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012553\n\
12554Return a list of the words in S, using sep as the\n\
12555delimiter string, starting at the end of the string and\n\
12556working to the front. If maxsplit is given, at most maxsplit\n\
12557splits are done. If sep is not specified, any whitespace string\n\
12558is a separator.");
12559
12560static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012561unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012562{
12563 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012564 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012565
Martin v. Löwis18e16552006-02-15 17:27:45 +000012566 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012567 return NULL;
12568
12569 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012570 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012571 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012572 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012573 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012574 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012575}
12576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012577PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012578 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012579\n\
12580Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012581Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012582is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012583
12584static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012585unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012587 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012588 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012590 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12591 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012592 return NULL;
12593
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012594 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595}
12596
12597static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012598PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599{
Walter Dörwald346737f2007-05-31 10:44:43 +000012600 if (PyUnicode_CheckExact(self)) {
12601 Py_INCREF(self);
12602 return self;
12603 } else
12604 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012605 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606}
12607
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012608PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012609 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012610\n\
12611Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012612and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012613
12614static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012615unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012616{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617 return fixup(self, fixswapcase);
12618}
12619
Georg Brandlceee0772007-11-27 23:48:05 +000012620PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012621 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012622\n\
12623Return a translation table usable for str.translate().\n\
12624If there is only one argument, it must be a dictionary mapping Unicode\n\
12625ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012626Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012627If there are two arguments, they must be strings of equal length, and\n\
12628in the resulting dictionary, each character in x will be mapped to the\n\
12629character at the same position in y. If there is a third argument, it\n\
12630must be a string, whose characters will be mapped to None in the result.");
12631
12632static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012633unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012634{
12635 PyObject *x, *y = NULL, *z = NULL;
12636 PyObject *new = NULL, *key, *value;
12637 Py_ssize_t i = 0;
12638 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012639
Georg Brandlceee0772007-11-27 23:48:05 +000012640 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12641 return NULL;
12642 new = PyDict_New();
12643 if (!new)
12644 return NULL;
12645 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012646 int x_kind, y_kind, z_kind;
12647 void *x_data, *y_data, *z_data;
12648
Georg Brandlceee0772007-11-27 23:48:05 +000012649 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012650 if (!PyUnicode_Check(x)) {
12651 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12652 "be a string if there is a second argument");
12653 goto err;
12654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012655 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012656 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12657 "arguments must have equal length");
12658 goto err;
12659 }
12660 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 x_kind = PyUnicode_KIND(x);
12662 y_kind = PyUnicode_KIND(y);
12663 x_data = PyUnicode_DATA(x);
12664 y_data = PyUnicode_DATA(y);
12665 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12666 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12667 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012668 if (!key || !value)
12669 goto err;
12670 res = PyDict_SetItem(new, key, value);
12671 Py_DECREF(key);
12672 Py_DECREF(value);
12673 if (res < 0)
12674 goto err;
12675 }
12676 /* create entries for deleting chars in z */
12677 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678 z_kind = PyUnicode_KIND(z);
12679 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012680 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012682 if (!key)
12683 goto err;
12684 res = PyDict_SetItem(new, key, Py_None);
12685 Py_DECREF(key);
12686 if (res < 0)
12687 goto err;
12688 }
12689 }
12690 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 int kind;
12692 void *data;
12693
Georg Brandlceee0772007-11-27 23:48:05 +000012694 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012695 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012696 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12697 "to maketrans it must be a dict");
12698 goto err;
12699 }
12700 /* copy entries into the new dict, converting string keys to int keys */
12701 while (PyDict_Next(x, &i, &key, &value)) {
12702 if (PyUnicode_Check(key)) {
12703 /* convert string keys to integer keys */
12704 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012705 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012706 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12707 "table must be of length 1");
12708 goto err;
12709 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 kind = PyUnicode_KIND(key);
12711 data = PyUnicode_DATA(key);
12712 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012713 if (!newkey)
12714 goto err;
12715 res = PyDict_SetItem(new, newkey, value);
12716 Py_DECREF(newkey);
12717 if (res < 0)
12718 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012719 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012720 /* just keep integer keys */
12721 if (PyDict_SetItem(new, key, value) < 0)
12722 goto err;
12723 } else {
12724 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12725 "be strings or integers");
12726 goto err;
12727 }
12728 }
12729 }
12730 return new;
12731 err:
12732 Py_DECREF(new);
12733 return NULL;
12734}
12735
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012736PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012737 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012738\n\
12739Return a copy of the string S, where all characters have been mapped\n\
12740through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012741Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012742Unmapped characters are left untouched. Characters mapped to None\n\
12743are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012744
12745static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012746unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749}
12750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012751PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012753\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012754Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755
12756static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012757unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759 return fixup(self, fixupper);
12760}
12761
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012762PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012763 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012765Pad a numeric string S with zeros on the left, to fill a field\n\
12766of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767
12768static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012769unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012771 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012772 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012773 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012774 int kind;
12775 void *data;
12776 Py_UCS4 chr;
12777
12778 if (PyUnicode_READY(self) == -1)
12779 return NULL;
12780
Martin v. Löwis18e16552006-02-15 17:27:45 +000012781 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012782 return NULL;
12783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012785 if (PyUnicode_CheckExact(self)) {
12786 Py_INCREF(self);
12787 return (PyObject*) self;
12788 }
12789 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012790 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791 }
12792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794
12795 u = pad(self, fill, 0, '0');
12796
Walter Dörwald068325e2002-04-15 13:36:47 +000012797 if (u == NULL)
12798 return NULL;
12799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012800 kind = PyUnicode_KIND(u);
12801 data = PyUnicode_DATA(u);
12802 chr = PyUnicode_READ(kind, data, fill);
12803
12804 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012806 PyUnicode_WRITE(kind, data, 0, chr);
12807 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808 }
12809
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012810 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012811 return (PyObject*) u;
12812}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813
12814#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012815static PyObject *
12816unicode__decimal2ascii(PyObject *self)
12817{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012818 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012819}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820#endif
12821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012822PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012823 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012825Return True if S starts with the specified prefix, False otherwise.\n\
12826With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012827With optional end, stop comparing S at that position.\n\
12828prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829
12830static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012831unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012832 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012834 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012835 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012836 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012837 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012838 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839
Jesus Ceaac451502011-04-20 17:09:23 +020012840 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012841 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012842 if (PyTuple_Check(subobj)) {
12843 Py_ssize_t i;
12844 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012845 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012846 if (substring == NULL)
12847 return NULL;
12848 result = tailmatch(self, substring, start, end, -1);
12849 Py_DECREF(substring);
12850 if (result) {
12851 Py_RETURN_TRUE;
12852 }
12853 }
12854 /* nothing matched */
12855 Py_RETURN_FALSE;
12856 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012857 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012858 if (substring == NULL) {
12859 if (PyErr_ExceptionMatches(PyExc_TypeError))
12860 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12861 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012862 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012863 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012864 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012866 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012867}
12868
12869
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012870PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012871 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012873Return True if S ends with the specified suffix, False otherwise.\n\
12874With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012875With optional end, stop comparing S at that position.\n\
12876suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877
12878static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012879unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012880 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012881{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012882 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012883 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012884 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012885 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012886 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887
Jesus Ceaac451502011-04-20 17:09:23 +020012888 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012889 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012890 if (PyTuple_Check(subobj)) {
12891 Py_ssize_t i;
12892 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012893 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012894 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012895 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012896 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012897 result = tailmatch(self, substring, start, end, +1);
12898 Py_DECREF(substring);
12899 if (result) {
12900 Py_RETURN_TRUE;
12901 }
12902 }
12903 Py_RETURN_FALSE;
12904 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012905 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012906 if (substring == NULL) {
12907 if (PyErr_ExceptionMatches(PyExc_TypeError))
12908 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12909 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012911 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012912 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012914 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012915}
12916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012917#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012918
12919PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012920 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012921\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012922Return a formatted version of S, using substitutions from args and kwargs.\n\
12923The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012924
Eric Smith27bbca62010-11-04 17:06:58 +000012925PyDoc_STRVAR(format_map__doc__,
12926 "S.format_map(mapping) -> str\n\
12927\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012928Return a formatted version of S, using substitutions from mapping.\n\
12929The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012930
Eric Smith4a7d76d2008-05-30 18:10:19 +000012931static PyObject *
12932unicode__format__(PyObject* self, PyObject* args)
12933{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012934 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012935
12936 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12937 return NULL;
12938
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012939 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012940 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012941 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012942}
12943
Eric Smith8c663262007-08-25 02:26:07 +000012944PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012945 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012946\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012947Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012948
12949static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012950unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012952 Py_ssize_t size;
12953
12954 /* If it's a compact object, account for base structure +
12955 character data. */
12956 if (PyUnicode_IS_COMPACT_ASCII(v))
12957 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12958 else if (PyUnicode_IS_COMPACT(v))
12959 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012960 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012961 else {
12962 /* If it is a two-block object, account for base object, and
12963 for character block if present. */
12964 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012965 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012967 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012968 }
12969 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012970 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012971 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012972 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012973 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012974 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012975
12976 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012977}
12978
12979PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012980 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012981
12982static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012983unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012984{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012985 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012986 if (!copy)
12987 return NULL;
12988 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012989}
12990
Guido van Rossumd57fd912000-03-10 22:53:23 +000012991static PyMethodDef unicode_methods[] = {
12992
12993 /* Order is according to common usage: often used methods should
12994 appear first, since lookup is done sequentially. */
12995
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012996 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012997 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12998 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012999 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013000 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13001 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13002 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13003 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13004 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13005 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13006 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013007 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013008 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13009 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13010 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013011 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013012 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13013 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13014 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013015 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013016 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013017 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013018 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013019 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13020 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13021 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13022 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13023 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13024 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13025 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13026 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13027 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13028 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13029 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13030 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13031 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13032 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013033 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013034 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013035 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013036 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013037 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013038 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013039 {"maketrans", (PyCFunction) unicode_maketrans,
13040 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013041 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013042#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013043 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013044#endif
13045
13046#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013047 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013048 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013049#endif
13050
Benjamin Peterson14339b62009-01-31 16:36:08 +000013051 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052 {NULL, NULL}
13053};
13054
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013055static PyObject *
13056unicode_mod(PyObject *v, PyObject *w)
13057{
Brian Curtindfc80e32011-08-10 20:28:54 -050013058 if (!PyUnicode_Check(v))
13059 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013060 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013061}
13062
13063static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013064 0, /*nb_add*/
13065 0, /*nb_subtract*/
13066 0, /*nb_multiply*/
13067 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013068};
13069
Guido van Rossumd57fd912000-03-10 22:53:23 +000013070static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013071 (lenfunc) unicode_length, /* sq_length */
13072 PyUnicode_Concat, /* sq_concat */
13073 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13074 (ssizeargfunc) unicode_getitem, /* sq_item */
13075 0, /* sq_slice */
13076 0, /* sq_ass_item */
13077 0, /* sq_ass_slice */
13078 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079};
13080
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013081static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013082unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013083{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013084 if (PyUnicode_READY(self) == -1)
13085 return NULL;
13086
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013087 if (PyIndex_Check(item)) {
13088 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013089 if (i == -1 && PyErr_Occurred())
13090 return NULL;
13091 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013092 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013093 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013094 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013095 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013096 PyObject *result;
13097 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013098 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013099 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013100
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013101 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013102 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013103 return NULL;
13104 }
13105
13106 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013107 return PyUnicode_New(0, 0);
13108 } else if (start == 0 && step == 1 &&
13109 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013110 PyUnicode_CheckExact(self)) {
13111 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013112 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013113 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013114 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013115 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013116 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013117 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013118 src_kind = PyUnicode_KIND(self);
13119 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013120 if (!PyUnicode_IS_ASCII(self)) {
13121 kind_limit = kind_maxchar_limit(src_kind);
13122 max_char = 0;
13123 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13124 ch = PyUnicode_READ(src_kind, src_data, cur);
13125 if (ch > max_char) {
13126 max_char = ch;
13127 if (max_char >= kind_limit)
13128 break;
13129 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013130 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013131 }
Victor Stinner55c99112011-10-13 01:17:06 +020013132 else
13133 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013134 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013135 if (result == NULL)
13136 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013137 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013138 dest_data = PyUnicode_DATA(result);
13139
13140 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013141 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13142 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013143 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013144 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013145 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013146 } else {
13147 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13148 return NULL;
13149 }
13150}
13151
13152static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013153 (lenfunc)unicode_length, /* mp_length */
13154 (binaryfunc)unicode_subscript, /* mp_subscript */
13155 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013156};
13157
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158
Guido van Rossumd57fd912000-03-10 22:53:23 +000013159/* Helpers for PyUnicode_Format() */
13160
13161static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013162getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013164 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013166 (*p_argidx)++;
13167 if (arglen < 0)
13168 return args;
13169 else
13170 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013171 }
13172 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013173 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013174 return NULL;
13175}
13176
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013177/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013179static PyObject *
13180formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013182 char *p;
13183 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013185
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186 x = PyFloat_AsDouble(v);
13187 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013188 return NULL;
13189
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013191 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013192
Eric Smith0923d1d2009-04-16 20:16:10 +000013193 p = PyOS_double_to_string(x, type, prec,
13194 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013195 if (p == NULL)
13196 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013197 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013198 PyMem_Free(p);
13199 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200}
13201
Tim Peters38fd5b62000-09-21 05:43:11 +000013202static PyObject*
13203formatlong(PyObject *val, int flags, int prec, int type)
13204{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013205 char *buf;
13206 int len;
13207 PyObject *str; /* temporary string object. */
13208 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013209
Benjamin Peterson14339b62009-01-31 16:36:08 +000013210 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13211 if (!str)
13212 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013213 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013214 Py_DECREF(str);
13215 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013216}
13217
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013218static Py_UCS4
13219formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013221 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013222 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013223 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013224 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013225 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013226 goto onError;
13227 }
13228 else {
13229 /* Integer input truncated to a character */
13230 long x;
13231 x = PyLong_AsLong(v);
13232 if (x == -1 && PyErr_Occurred())
13233 goto onError;
13234
13235 if (x < 0 || x > 0x10ffff) {
13236 PyErr_SetString(PyExc_OverflowError,
13237 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013238 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 }
13240
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013241 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013242 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013243
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013245 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013247 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013248}
13249
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013250static int
13251repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13252{
13253 int r;
13254 assert(count > 0);
13255 assert(PyUnicode_Check(obj));
13256 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013257 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013258 if (repeated == NULL)
13259 return -1;
13260 r = _PyAccu_Accumulate(acc, repeated);
13261 Py_DECREF(repeated);
13262 return r;
13263 }
13264 else {
13265 do {
13266 if (_PyAccu_Accumulate(acc, obj))
13267 return -1;
13268 } while (--count);
13269 return 0;
13270 }
13271}
13272
Alexander Belopolsky40018472011-02-26 01:02:56 +000013273PyObject *
13274PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013275{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013276 void *fmt;
13277 int fmtkind;
13278 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013279 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013280 int r;
13281 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013282 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013283 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013284 PyObject *temp = NULL;
13285 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013286 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013287 _PyAccu acc;
13288 static PyObject *plus, *minus, *blank, *zero, *percent;
13289
13290 if (!plus && !(plus = get_latin1_char('+')))
13291 return NULL;
13292 if (!minus && !(minus = get_latin1_char('-')))
13293 return NULL;
13294 if (!blank && !(blank = get_latin1_char(' ')))
13295 return NULL;
13296 if (!zero && !(zero = get_latin1_char('0')))
13297 return NULL;
13298 if (!percent && !(percent = get_latin1_char('%')))
13299 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013300
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013302 PyErr_BadInternalCall();
13303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013304 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013305 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013306 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013307 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013308 if (_PyAccu_Init(&acc))
13309 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013310 fmt = PyUnicode_DATA(uformat);
13311 fmtkind = PyUnicode_KIND(uformat);
13312 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13313 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013314
Guido van Rossumd57fd912000-03-10 22:53:23 +000013315 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013316 arglen = PyTuple_Size(args);
13317 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013318 }
13319 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013320 arglen = -1;
13321 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013322 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013323 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013324 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013326
13327 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013328 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013329 PyObject *nonfmt;
13330 Py_ssize_t nonfmtpos;
13331 nonfmtpos = fmtpos++;
13332 while (fmtcnt >= 0 &&
13333 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13334 fmtpos++;
13335 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013336 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013337 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
13338 if (nonfmt == NULL)
13339 goto onError;
13340 r = _PyAccu_Accumulate(&acc, nonfmt);
13341 Py_DECREF(nonfmt);
13342 if (r)
13343 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013344 }
13345 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013346 /* Got a format specifier */
13347 int flags = 0;
13348 Py_ssize_t width = -1;
13349 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013350 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013351 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 int isnumok;
13353 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013354 void *pbuf = NULL;
13355 Py_ssize_t pindex, len;
13356 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013357
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013358 fmtpos++;
13359 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13360 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013361 Py_ssize_t keylen;
13362 PyObject *key;
13363 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013364
Benjamin Peterson29060642009-01-31 22:14:21 +000013365 if (dict == NULL) {
13366 PyErr_SetString(PyExc_TypeError,
13367 "format requires a mapping");
13368 goto onError;
13369 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013370 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013372 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 /* Skip over balanced parentheses */
13374 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013375 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013379 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013381 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 if (fmtcnt < 0 || pcount > 0) {
13383 PyErr_SetString(PyExc_ValueError,
13384 "incomplete format key");
13385 goto onError;
13386 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020013387 key = PyUnicode_Substring((PyObject*)uformat,
13388 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013389 if (key == NULL)
13390 goto onError;
13391 if (args_owned) {
13392 Py_DECREF(args);
13393 args_owned = 0;
13394 }
13395 args = PyObject_GetItem(dict, key);
13396 Py_DECREF(key);
13397 if (args == NULL) {
13398 goto onError;
13399 }
13400 args_owned = 1;
13401 arglen = -1;
13402 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013403 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013404 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013405 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013406 case '-': flags |= F_LJUST; continue;
13407 case '+': flags |= F_SIGN; continue;
13408 case ' ': flags |= F_BLANK; continue;
13409 case '#': flags |= F_ALT; continue;
13410 case '0': flags |= F_ZERO; continue;
13411 }
13412 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013413 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 if (c == '*') {
13415 v = getnextarg(args, arglen, &argidx);
13416 if (v == NULL)
13417 goto onError;
13418 if (!PyLong_Check(v)) {
13419 PyErr_SetString(PyExc_TypeError,
13420 "* wants int");
13421 goto onError;
13422 }
13423 width = PyLong_AsLong(v);
13424 if (width == -1 && PyErr_Occurred())
13425 goto onError;
13426 if (width < 0) {
13427 flags |= F_LJUST;
13428 width = -width;
13429 }
13430 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013431 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 }
13433 else if (c >= '0' && c <= '9') {
13434 width = c - '0';
13435 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013436 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 if (c < '0' || c > '9')
13438 break;
13439 if ((width*10) / 10 != width) {
13440 PyErr_SetString(PyExc_ValueError,
13441 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013442 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 }
13444 width = width*10 + (c - '0');
13445 }
13446 }
13447 if (c == '.') {
13448 prec = 0;
13449 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013450 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013451 if (c == '*') {
13452 v = getnextarg(args, arglen, &argidx);
13453 if (v == NULL)
13454 goto onError;
13455 if (!PyLong_Check(v)) {
13456 PyErr_SetString(PyExc_TypeError,
13457 "* wants int");
13458 goto onError;
13459 }
13460 prec = PyLong_AsLong(v);
13461 if (prec == -1 && PyErr_Occurred())
13462 goto onError;
13463 if (prec < 0)
13464 prec = 0;
13465 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013466 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013467 }
13468 else if (c >= '0' && c <= '9') {
13469 prec = c - '0';
13470 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013471 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013472 if (c < '0' || c > '9')
13473 break;
13474 if ((prec*10) / 10 != prec) {
13475 PyErr_SetString(PyExc_ValueError,
13476 "prec too big");
13477 goto onError;
13478 }
13479 prec = prec*10 + (c - '0');
13480 }
13481 }
13482 } /* prec */
13483 if (fmtcnt >= 0) {
13484 if (c == 'h' || c == 'l' || c == 'L') {
13485 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013486 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 }
13488 }
13489 if (fmtcnt < 0) {
13490 PyErr_SetString(PyExc_ValueError,
13491 "incomplete format");
13492 goto onError;
13493 }
13494 if (c != '%') {
13495 v = getnextarg(args, arglen, &argidx);
13496 if (v == NULL)
13497 goto onError;
13498 }
13499 sign = 0;
13500 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013501 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013502 switch (c) {
13503
13504 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013505 _PyAccu_Accumulate(&acc, percent);
13506 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013507
13508 case 's':
13509 case 'r':
13510 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013511 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013512 temp = v;
13513 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013514 }
13515 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 if (c == 's')
13517 temp = PyObject_Str(v);
13518 else if (c == 'r')
13519 temp = PyObject_Repr(v);
13520 else
13521 temp = PyObject_ASCII(v);
13522 if (temp == NULL)
13523 goto onError;
13524 if (PyUnicode_Check(temp))
13525 /* nothing to do */;
13526 else {
13527 Py_DECREF(temp);
13528 PyErr_SetString(PyExc_TypeError,
13529 "%s argument has non-string str()");
13530 goto onError;
13531 }
13532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013533 if (PyUnicode_READY(temp) == -1) {
13534 Py_CLEAR(temp);
13535 goto onError;
13536 }
13537 pbuf = PyUnicode_DATA(temp);
13538 kind = PyUnicode_KIND(temp);
13539 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 if (prec >= 0 && len > prec)
13541 len = prec;
13542 break;
13543
13544 case 'i':
13545 case 'd':
13546 case 'u':
13547 case 'o':
13548 case 'x':
13549 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 isnumok = 0;
13551 if (PyNumber_Check(v)) {
13552 PyObject *iobj=NULL;
13553
13554 if (PyLong_Check(v)) {
13555 iobj = v;
13556 Py_INCREF(iobj);
13557 }
13558 else {
13559 iobj = PyNumber_Long(v);
13560 }
13561 if (iobj!=NULL) {
13562 if (PyLong_Check(iobj)) {
13563 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013564 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013565 Py_DECREF(iobj);
13566 if (!temp)
13567 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013568 if (PyUnicode_READY(temp) == -1) {
13569 Py_CLEAR(temp);
13570 goto onError;
13571 }
13572 pbuf = PyUnicode_DATA(temp);
13573 kind = PyUnicode_KIND(temp);
13574 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013575 sign = 1;
13576 }
13577 else {
13578 Py_DECREF(iobj);
13579 }
13580 }
13581 }
13582 if (!isnumok) {
13583 PyErr_Format(PyExc_TypeError,
13584 "%%%c format: a number is required, "
13585 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13586 goto onError;
13587 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013588 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013589 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013590 fillobj = zero;
13591 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 break;
13593
13594 case 'e':
13595 case 'E':
13596 case 'f':
13597 case 'F':
13598 case 'g':
13599 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013600 temp = formatfloat(v, flags, prec, c);
13601 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013602 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013603 if (PyUnicode_READY(temp) == -1) {
13604 Py_CLEAR(temp);
13605 goto onError;
13606 }
13607 pbuf = PyUnicode_DATA(temp);
13608 kind = PyUnicode_KIND(temp);
13609 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013611 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013612 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013613 fillobj = zero;
13614 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 break;
13616
13617 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013618 {
13619 Py_UCS4 ch = formatchar(v);
13620 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013622 temp = _PyUnicode_FromUCS4(&ch, 1);
13623 if (temp == NULL)
13624 goto onError;
13625 pbuf = PyUnicode_DATA(temp);
13626 kind = PyUnicode_KIND(temp);
13627 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013628 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013629 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013630
13631 default:
13632 PyErr_Format(PyExc_ValueError,
13633 "unsupported format character '%c' (0x%x) "
13634 "at index %zd",
13635 (31<=c && c<=126) ? (char)c : '?',
13636 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013637 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013638 goto onError;
13639 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013640 /* pbuf is initialized here. */
13641 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013643 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13644 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013646 pindex++;
13647 }
13648 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13649 signobj = plus;
13650 len--;
13651 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013652 }
13653 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013654 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013656 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 else
13658 sign = 0;
13659 }
13660 if (width < len)
13661 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013663 if (fill != ' ') {
13664 assert(signobj != NULL);
13665 if (_PyAccu_Accumulate(&acc, signobj))
13666 goto onError;
13667 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013668 if (width > len)
13669 width--;
13670 }
13671 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013672 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013673 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013675 second = get_latin1_char(
13676 PyUnicode_READ(kind, pbuf, pindex + 1));
13677 pindex += 2;
13678 if (second == NULL ||
13679 _PyAccu_Accumulate(&acc, zero) ||
13680 _PyAccu_Accumulate(&acc, second))
13681 goto onError;
13682 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013683 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013684 width -= 2;
13685 if (width < 0)
13686 width = 0;
13687 len -= 2;
13688 }
13689 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013690 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013691 if (repeat_accumulate(&acc, fillobj, width - len))
13692 goto onError;
13693 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013694 }
13695 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013696 if (sign) {
13697 assert(signobj != NULL);
13698 if (_PyAccu_Accumulate(&acc, signobj))
13699 goto onError;
13700 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013701 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013702 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13703 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013704 second = get_latin1_char(
13705 PyUnicode_READ(kind, pbuf, pindex + 1));
13706 pindex += 2;
13707 if (second == NULL ||
13708 _PyAccu_Accumulate(&acc, zero) ||
13709 _PyAccu_Accumulate(&acc, second))
13710 goto onError;
13711 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013712 }
13713 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013714 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013715 if (temp != NULL) {
13716 assert(pbuf == PyUnicode_DATA(temp));
13717 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013718 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013719 else {
13720 const char *p = (const char *) pbuf;
13721 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013722 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013723 v = PyUnicode_FromKindAndData(kind, p, len);
13724 }
13725 if (v == NULL)
13726 goto onError;
13727 r = _PyAccu_Accumulate(&acc, v);
13728 Py_DECREF(v);
13729 if (r)
13730 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013731 if (width > len && repeat_accumulate(&acc, blank, width - len))
13732 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013733 if (dict && (argidx < arglen) && c != '%') {
13734 PyErr_SetString(PyExc_TypeError,
13735 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013736 goto onError;
13737 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013738 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013739 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013740 } /* until end */
13741 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013742 PyErr_SetString(PyExc_TypeError,
13743 "not all arguments converted during string formatting");
13744 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745 }
13746
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013747 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013748 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013749 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013750 }
13751 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013752 Py_XDECREF(temp);
13753 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013754 return (PyObject *)result;
13755
Benjamin Peterson29060642009-01-31 22:14:21 +000013756 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013757 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013758 Py_XDECREF(temp);
13759 Py_XDECREF(second);
13760 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013761 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013762 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013763 }
13764 return NULL;
13765}
13766
Jeremy Hylton938ace62002-07-17 16:30:39 +000013767static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013768unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13769
Tim Peters6d6c1a32001-08-02 04:15:00 +000013770static PyObject *
13771unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13772{
Benjamin Peterson29060642009-01-31 22:14:21 +000013773 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013774 static char *kwlist[] = {"object", "encoding", "errors", 0};
13775 char *encoding = NULL;
13776 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013777
Benjamin Peterson14339b62009-01-31 16:36:08 +000013778 if (type != &PyUnicode_Type)
13779 return unicode_subtype_new(type, args, kwds);
13780 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013781 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013782 return NULL;
13783 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013784 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013785 if (encoding == NULL && errors == NULL)
13786 return PyObject_Str(x);
13787 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013788 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013789}
13790
Guido van Rossume023fe02001-08-30 03:12:59 +000013791static PyObject *
13792unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13793{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013794 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013795 Py_ssize_t length, char_size;
13796 int share_wstr, share_utf8;
13797 unsigned int kind;
13798 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013799
Benjamin Peterson14339b62009-01-31 16:36:08 +000013800 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013801
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013802 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013803 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013804 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013805 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013806 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013807 return NULL;
13808
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013809 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013810 if (self == NULL) {
13811 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013812 return NULL;
13813 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013814 kind = PyUnicode_KIND(unicode);
13815 length = PyUnicode_GET_LENGTH(unicode);
13816
13817 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013818#ifdef Py_DEBUG
13819 _PyUnicode_HASH(self) = -1;
13820#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013821 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013822#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013823 _PyUnicode_STATE(self).interned = 0;
13824 _PyUnicode_STATE(self).kind = kind;
13825 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013826 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013827 _PyUnicode_STATE(self).ready = 1;
13828 _PyUnicode_WSTR(self) = NULL;
13829 _PyUnicode_UTF8_LENGTH(self) = 0;
13830 _PyUnicode_UTF8(self) = NULL;
13831 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013832 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013833
13834 share_utf8 = 0;
13835 share_wstr = 0;
13836 if (kind == PyUnicode_1BYTE_KIND) {
13837 char_size = 1;
13838 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13839 share_utf8 = 1;
13840 }
13841 else if (kind == PyUnicode_2BYTE_KIND) {
13842 char_size = 2;
13843 if (sizeof(wchar_t) == 2)
13844 share_wstr = 1;
13845 }
13846 else {
13847 assert(kind == PyUnicode_4BYTE_KIND);
13848 char_size = 4;
13849 if (sizeof(wchar_t) == 4)
13850 share_wstr = 1;
13851 }
13852
13853 /* Ensure we won't overflow the length. */
13854 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13855 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013856 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013857 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013858 data = PyObject_MALLOC((length + 1) * char_size);
13859 if (data == NULL) {
13860 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 goto onError;
13862 }
13863
Victor Stinnerc3c74152011-10-02 20:39:55 +020013864 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013865 if (share_utf8) {
13866 _PyUnicode_UTF8_LENGTH(self) = length;
13867 _PyUnicode_UTF8(self) = data;
13868 }
13869 if (share_wstr) {
13870 _PyUnicode_WSTR_LENGTH(self) = length;
13871 _PyUnicode_WSTR(self) = (wchar_t *)data;
13872 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013873
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013874 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013875 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013876 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013877#ifdef Py_DEBUG
13878 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13879#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013880 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013881 return (PyObject *)self;
13882
13883onError:
13884 Py_DECREF(unicode);
13885 Py_DECREF(self);
13886 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013887}
13888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013889PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013890 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013891\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013892Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013893encoding defaults to the current default string encoding.\n\
13894errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013895
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013896static PyObject *unicode_iter(PyObject *seq);
13897
Guido van Rossumd57fd912000-03-10 22:53:23 +000013898PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013899 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013900 "str", /* tp_name */
13901 sizeof(PyUnicodeObject), /* tp_size */
13902 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013903 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013904 (destructor)unicode_dealloc, /* tp_dealloc */
13905 0, /* tp_print */
13906 0, /* tp_getattr */
13907 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013908 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 unicode_repr, /* tp_repr */
13910 &unicode_as_number, /* tp_as_number */
13911 &unicode_as_sequence, /* tp_as_sequence */
13912 &unicode_as_mapping, /* tp_as_mapping */
13913 (hashfunc) unicode_hash, /* tp_hash*/
13914 0, /* tp_call*/
13915 (reprfunc) unicode_str, /* tp_str */
13916 PyObject_GenericGetAttr, /* tp_getattro */
13917 0, /* tp_setattro */
13918 0, /* tp_as_buffer */
13919 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013920 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013921 unicode_doc, /* tp_doc */
13922 0, /* tp_traverse */
13923 0, /* tp_clear */
13924 PyUnicode_RichCompare, /* tp_richcompare */
13925 0, /* tp_weaklistoffset */
13926 unicode_iter, /* tp_iter */
13927 0, /* tp_iternext */
13928 unicode_methods, /* tp_methods */
13929 0, /* tp_members */
13930 0, /* tp_getset */
13931 &PyBaseObject_Type, /* tp_base */
13932 0, /* tp_dict */
13933 0, /* tp_descr_get */
13934 0, /* tp_descr_set */
13935 0, /* tp_dictoffset */
13936 0, /* tp_init */
13937 0, /* tp_alloc */
13938 unicode_new, /* tp_new */
13939 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013940};
13941
13942/* Initialize the Unicode implementation */
13943
Victor Stinner3a50e702011-10-18 21:21:00 +020013944int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013946 int i;
13947
Thomas Wouters477c8d52006-05-27 19:21:47 +000013948 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013949 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013950 0x000A, /* LINE FEED */
13951 0x000D, /* CARRIAGE RETURN */
13952 0x001C, /* FILE SEPARATOR */
13953 0x001D, /* GROUP SEPARATOR */
13954 0x001E, /* RECORD SEPARATOR */
13955 0x0085, /* NEXT LINE */
13956 0x2028, /* LINE SEPARATOR */
13957 0x2029, /* PARAGRAPH SEPARATOR */
13958 };
13959
Fred Drakee4315f52000-05-09 19:53:39 +000013960 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013961 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013962 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013963 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013964 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013965
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013966 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013967 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013968 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013969 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013970
13971 /* initialize the linebreak bloom filter */
13972 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013973 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013974 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013975
13976 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013977
13978#ifdef HAVE_MBCS
13979 winver.dwOSVersionInfoSize = sizeof(winver);
13980 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13981 PyErr_SetFromWindowsErr(0);
13982 return -1;
13983 }
13984#endif
13985 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013986}
13987
13988/* Finalize the Unicode implementation */
13989
Christian Heimesa156e092008-02-16 07:38:31 +000013990int
13991PyUnicode_ClearFreeList(void)
13992{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013993 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013994}
13995
Guido van Rossumd57fd912000-03-10 22:53:23 +000013996void
Thomas Wouters78890102000-07-22 19:25:51 +000013997_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013998{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013999 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014000
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014001 Py_XDECREF(unicode_empty);
14002 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014003
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014004 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014005 if (unicode_latin1[i]) {
14006 Py_DECREF(unicode_latin1[i]);
14007 unicode_latin1[i] = NULL;
14008 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014009 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014010 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014011 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014012}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014013
Walter Dörwald16807132007-05-25 13:52:07 +000014014void
14015PyUnicode_InternInPlace(PyObject **p)
14016{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014017 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014018 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014019#ifdef Py_DEBUG
14020 assert(s != NULL);
14021 assert(_PyUnicode_CHECK(s));
14022#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014024 return;
14025#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014026 /* If it's a subclass, we don't really know what putting
14027 it in the interned dict might do. */
14028 if (!PyUnicode_CheckExact(s))
14029 return;
14030 if (PyUnicode_CHECK_INTERNED(s))
14031 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020014032 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014033 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014034 return;
14035 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014036 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014037 if (interned == NULL) {
14038 interned = PyDict_New();
14039 if (interned == NULL) {
14040 PyErr_Clear(); /* Don't leave an exception */
14041 return;
14042 }
14043 }
14044 /* It might be that the GetItem call fails even
14045 though the key is present in the dictionary,
14046 namely when this happens during a stack overflow. */
14047 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000014048 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014049 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014050
Benjamin Peterson29060642009-01-31 22:14:21 +000014051 if (t) {
14052 Py_INCREF(t);
14053 Py_DECREF(*p);
14054 *p = t;
14055 return;
14056 }
Walter Dörwald16807132007-05-25 13:52:07 +000014057
Benjamin Peterson14339b62009-01-31 16:36:08 +000014058 PyThreadState_GET()->recursion_critical = 1;
14059 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
14060 PyErr_Clear();
14061 PyThreadState_GET()->recursion_critical = 0;
14062 return;
14063 }
14064 PyThreadState_GET()->recursion_critical = 0;
14065 /* The two references in interned are not counted by refcnt.
14066 The deallocator will take care of this */
14067 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014068 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014069}
14070
14071void
14072PyUnicode_InternImmortal(PyObject **p)
14073{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014074 PyUnicode_InternInPlace(p);
14075 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014076 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014077 Py_INCREF(*p);
14078 }
Walter Dörwald16807132007-05-25 13:52:07 +000014079}
14080
14081PyObject *
14082PyUnicode_InternFromString(const char *cp)
14083{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014084 PyObject *s = PyUnicode_FromString(cp);
14085 if (s == NULL)
14086 return NULL;
14087 PyUnicode_InternInPlace(&s);
14088 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014089}
14090
Alexander Belopolsky40018472011-02-26 01:02:56 +000014091void
14092_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014093{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014095 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014096 Py_ssize_t i, n;
14097 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014098
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 if (interned == NULL || !PyDict_Check(interned))
14100 return;
14101 keys = PyDict_Keys(interned);
14102 if (keys == NULL || !PyList_Check(keys)) {
14103 PyErr_Clear();
14104 return;
14105 }
Walter Dörwald16807132007-05-25 13:52:07 +000014106
Benjamin Peterson14339b62009-01-31 16:36:08 +000014107 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14108 detector, interned unicode strings are not forcibly deallocated;
14109 rather, we give them their stolen references back, and then clear
14110 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014111
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 n = PyList_GET_SIZE(keys);
14113 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014114 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014115 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014116 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014117 if (PyUnicode_READY(s) == -1) {
14118 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014119 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014120 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014121 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014122 case SSTATE_NOT_INTERNED:
14123 /* XXX Shouldn't happen */
14124 break;
14125 case SSTATE_INTERNED_IMMORTAL:
14126 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014127 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014128 break;
14129 case SSTATE_INTERNED_MORTAL:
14130 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014131 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 break;
14133 default:
14134 Py_FatalError("Inconsistent interned string state.");
14135 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014136 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 }
14138 fprintf(stderr, "total size of all interned strings: "
14139 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14140 "mortal/immortal\n", mortal_size, immortal_size);
14141 Py_DECREF(keys);
14142 PyDict_Clear(interned);
14143 Py_DECREF(interned);
14144 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014145}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014146
14147
14148/********************* Unicode Iterator **************************/
14149
14150typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014151 PyObject_HEAD
14152 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014153 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014154} unicodeiterobject;
14155
14156static void
14157unicodeiter_dealloc(unicodeiterobject *it)
14158{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014159 _PyObject_GC_UNTRACK(it);
14160 Py_XDECREF(it->it_seq);
14161 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014162}
14163
14164static int
14165unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14166{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014167 Py_VISIT(it->it_seq);
14168 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014169}
14170
14171static PyObject *
14172unicodeiter_next(unicodeiterobject *it)
14173{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014174 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014175
Benjamin Peterson14339b62009-01-31 16:36:08 +000014176 assert(it != NULL);
14177 seq = it->it_seq;
14178 if (seq == NULL)
14179 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014180 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014181
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014182 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14183 int kind = PyUnicode_KIND(seq);
14184 void *data = PyUnicode_DATA(seq);
14185 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14186 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014187 if (item != NULL)
14188 ++it->it_index;
14189 return item;
14190 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014191
Benjamin Peterson14339b62009-01-31 16:36:08 +000014192 Py_DECREF(seq);
14193 it->it_seq = NULL;
14194 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014195}
14196
14197static PyObject *
14198unicodeiter_len(unicodeiterobject *it)
14199{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014200 Py_ssize_t len = 0;
14201 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014202 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014203 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014204}
14205
14206PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14207
14208static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014209 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014210 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014211 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014212};
14213
14214PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014215 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14216 "str_iterator", /* tp_name */
14217 sizeof(unicodeiterobject), /* tp_basicsize */
14218 0, /* tp_itemsize */
14219 /* methods */
14220 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14221 0, /* tp_print */
14222 0, /* tp_getattr */
14223 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014224 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014225 0, /* tp_repr */
14226 0, /* tp_as_number */
14227 0, /* tp_as_sequence */
14228 0, /* tp_as_mapping */
14229 0, /* tp_hash */
14230 0, /* tp_call */
14231 0, /* tp_str */
14232 PyObject_GenericGetAttr, /* tp_getattro */
14233 0, /* tp_setattro */
14234 0, /* tp_as_buffer */
14235 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14236 0, /* tp_doc */
14237 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14238 0, /* tp_clear */
14239 0, /* tp_richcompare */
14240 0, /* tp_weaklistoffset */
14241 PyObject_SelfIter, /* tp_iter */
14242 (iternextfunc)unicodeiter_next, /* tp_iternext */
14243 unicodeiter_methods, /* tp_methods */
14244 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014245};
14246
14247static PyObject *
14248unicode_iter(PyObject *seq)
14249{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014250 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014251
Benjamin Peterson14339b62009-01-31 16:36:08 +000014252 if (!PyUnicode_Check(seq)) {
14253 PyErr_BadInternalCall();
14254 return NULL;
14255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014256 if (PyUnicode_READY(seq) == -1)
14257 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014258 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14259 if (it == NULL)
14260 return NULL;
14261 it->it_index = 0;
14262 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014263 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014264 _PyObject_GC_TRACK(it);
14265 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014266}
14267
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014268
14269size_t
14270Py_UNICODE_strlen(const Py_UNICODE *u)
14271{
14272 int res = 0;
14273 while(*u++)
14274 res++;
14275 return res;
14276}
14277
14278Py_UNICODE*
14279Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14280{
14281 Py_UNICODE *u = s1;
14282 while ((*u++ = *s2++));
14283 return s1;
14284}
14285
14286Py_UNICODE*
14287Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14288{
14289 Py_UNICODE *u = s1;
14290 while ((*u++ = *s2++))
14291 if (n-- == 0)
14292 break;
14293 return s1;
14294}
14295
14296Py_UNICODE*
14297Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14298{
14299 Py_UNICODE *u1 = s1;
14300 u1 += Py_UNICODE_strlen(u1);
14301 Py_UNICODE_strcpy(u1, s2);
14302 return s1;
14303}
14304
14305int
14306Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14307{
14308 while (*s1 && *s2 && *s1 == *s2)
14309 s1++, s2++;
14310 if (*s1 && *s2)
14311 return (*s1 < *s2) ? -1 : +1;
14312 if (*s1)
14313 return 1;
14314 if (*s2)
14315 return -1;
14316 return 0;
14317}
14318
14319int
14320Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14321{
14322 register Py_UNICODE u1, u2;
14323 for (; n != 0; n--) {
14324 u1 = *s1;
14325 u2 = *s2;
14326 if (u1 != u2)
14327 return (u1 < u2) ? -1 : +1;
14328 if (u1 == '\0')
14329 return 0;
14330 s1++;
14331 s2++;
14332 }
14333 return 0;
14334}
14335
14336Py_UNICODE*
14337Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14338{
14339 const Py_UNICODE *p;
14340 for (p = s; *p; p++)
14341 if (*p == c)
14342 return (Py_UNICODE*)p;
14343 return NULL;
14344}
14345
14346Py_UNICODE*
14347Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14348{
14349 const Py_UNICODE *p;
14350 p = s + Py_UNICODE_strlen(s);
14351 while (p != s) {
14352 p--;
14353 if (*p == c)
14354 return (Py_UNICODE*)p;
14355 }
14356 return NULL;
14357}
Victor Stinner331ea922010-08-10 16:37:20 +000014358
Victor Stinner71133ff2010-09-01 23:43:53 +000014359Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014360PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014361{
Victor Stinner577db2c2011-10-11 22:12:48 +020014362 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014363 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014365 if (!PyUnicode_Check(unicode)) {
14366 PyErr_BadArgument();
14367 return NULL;
14368 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014369 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014370 if (u == NULL)
14371 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014372 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014373 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014374 PyErr_NoMemory();
14375 return NULL;
14376 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014377 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014378 size *= sizeof(Py_UNICODE);
14379 copy = PyMem_Malloc(size);
14380 if (copy == NULL) {
14381 PyErr_NoMemory();
14382 return NULL;
14383 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014384 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014385 return copy;
14386}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014387
Georg Brandl66c221e2010-10-14 07:04:07 +000014388/* A _string module, to export formatter_parser and formatter_field_name_split
14389 to the string.Formatter class implemented in Python. */
14390
14391static PyMethodDef _string_methods[] = {
14392 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14393 METH_O, PyDoc_STR("split the argument as a field name")},
14394 {"formatter_parser", (PyCFunction) formatter_parser,
14395 METH_O, PyDoc_STR("parse the argument as a format string")},
14396 {NULL, NULL}
14397};
14398
14399static struct PyModuleDef _string_module = {
14400 PyModuleDef_HEAD_INIT,
14401 "_string",
14402 PyDoc_STR("string helper module"),
14403 0,
14404 _string_methods,
14405 NULL,
14406 NULL,
14407 NULL,
14408 NULL
14409};
14410
14411PyMODINIT_FUNC
14412PyInit__string(void)
14413{
14414 return PyModule_Create(&_string_module);
14415}
14416
14417
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014418#ifdef __cplusplus
14419}
14420#endif