blob: 58f657e1e1a9fe823b7b1077cbd0fe391c7fd4e9 [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,
251 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
252 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);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 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,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200305/* FIXME: use PyObject* type for op */
306_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200307{
308 PyASCIIObject *ascii;
309 unsigned int kind;
310
311 assert(PyUnicode_Check(op));
312
313 ascii = (PyASCIIObject *)op;
314 kind = ascii->state.kind;
315
Victor Stinnera3b334d2011-10-03 13:53:37 +0200316 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200318 assert(ascii->state.ready == 1);
319 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200320 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200321 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200322 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200323
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 if (ascii->state.compact == 1) {
325 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200326 assert(kind == PyUnicode_1BYTE_KIND
327 || kind == PyUnicode_2BYTE_KIND
328 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200330 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200331 assert (compact->utf8 != data);
332 } else {
333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
337 assert(ascii->state.compact == 0);
338 assert(ascii->state.ascii == 0);
339 assert(ascii->state.ready == 0);
340 assert(ascii->wstr != NULL);
341 assert(data == NULL);
342 assert(compact->utf8 == NULL);
343 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
344 }
345 else {
346 assert(kind == PyUnicode_1BYTE_KIND
347 || kind == PyUnicode_2BYTE_KIND
348 || kind == PyUnicode_4BYTE_KIND);
349 assert(ascii->state.compact == 0);
350 assert(ascii->state.ready == 1);
351 assert(data != NULL);
352 if (ascii->state.ascii) {
353 assert (compact->utf8 == data);
354 assert (compact->utf8_length == ascii->length);
355 }
356 else
357 assert (compact->utf8 != data);
358 }
359 }
360 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200361 if (
362#if SIZEOF_WCHAR_T == 2
363 kind == PyUnicode_2BYTE_KIND
364#else
365 kind == PyUnicode_4BYTE_KIND
366#endif
367 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200368 {
369 assert(ascii->wstr == data);
370 assert(compact->wstr_length == ascii->length);
371 } else
372 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200373 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200374
375 if (compact->utf8 == NULL)
376 assert(compact->utf8_length == 0);
377 if (ascii->wstr == NULL)
378 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200380 /* check that the best kind is used */
381 if (check_content && kind != PyUnicode_WCHAR_KIND)
382 {
383 Py_ssize_t i;
384 Py_UCS4 maxchar = 0;
385 void *data = PyUnicode_DATA(ascii);
386 for (i=0; i < ascii->length; i++)
387 {
388 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
389 if (ch > maxchar)
390 maxchar = ch;
391 }
392 if (kind == PyUnicode_1BYTE_KIND) {
393 if (ascii->state.ascii == 0)
394 assert(maxchar >= 128);
395 else
396 assert(maxchar < 128);
397 }
398 else if (kind == PyUnicode_2BYTE_KIND)
399 assert(maxchar >= 0x100);
400 else
401 assert(maxchar >= 0x10000);
402 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200403 if (check_content && !unicode_is_singleton((PyObject*)ascii))
404 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400405 return 1;
406}
Victor Stinner910337b2011-10-03 03:20:16 +0200407#endif
408
Victor Stinner3a50e702011-10-18 21:21:00 +0200409#ifdef HAVE_MBCS
410static OSVERSIONINFOEX winver;
411#endif
412
Thomas Wouters477c8d52006-05-27 19:21:47 +0000413/* --- Bloom Filters ----------------------------------------------------- */
414
415/* stuff to implement simple "bloom filters" for Unicode characters.
416 to keep things simple, we use a single bitmask, using the least 5
417 bits from each unicode characters as the bit index. */
418
419/* the linebreak mask is set up by Unicode_Init below */
420
Antoine Pitrouf068f942010-01-13 14:19:12 +0000421#if LONG_BIT >= 128
422#define BLOOM_WIDTH 128
423#elif LONG_BIT >= 64
424#define BLOOM_WIDTH 64
425#elif LONG_BIT >= 32
426#define BLOOM_WIDTH 32
427#else
428#error "LONG_BIT is smaller than 32"
429#endif
430
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431#define BLOOM_MASK unsigned long
432
433static BLOOM_MASK bloom_linebreak;
434
Antoine Pitrouf068f942010-01-13 14:19:12 +0000435#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
436#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437
Benjamin Peterson29060642009-01-31 22:14:21 +0000438#define BLOOM_LINEBREAK(ch) \
439 ((ch) < 128U ? ascii_linebreak[(ch)] : \
440 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441
Alexander Belopolsky40018472011-02-26 01:02:56 +0000442Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200443make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000444{
445 /* calculate simple bloom-style bitmask for a given unicode string */
446
Antoine Pitrouf068f942010-01-13 14:19:12 +0000447 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448 Py_ssize_t i;
449
450 mask = 0;
451 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200452 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000453
454 return mask;
455}
456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200457#define BLOOM_MEMBER(mask, chr, str) \
458 (BLOOM(mask, chr) \
459 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200461/* Compilation of templated routines */
462
463#include "stringlib/asciilib.h"
464#include "stringlib/fastsearch.h"
465#include "stringlib/partition.h"
466#include "stringlib/split.h"
467#include "stringlib/count.h"
468#include "stringlib/find.h"
469#include "stringlib/find_max_char.h"
470#include "stringlib/localeutil.h"
471#include "stringlib/undef.h"
472
473#include "stringlib/ucs1lib.h"
474#include "stringlib/fastsearch.h"
475#include "stringlib/partition.h"
476#include "stringlib/split.h"
477#include "stringlib/count.h"
478#include "stringlib/find.h"
479#include "stringlib/find_max_char.h"
480#include "stringlib/localeutil.h"
481#include "stringlib/undef.h"
482
483#include "stringlib/ucs2lib.h"
484#include "stringlib/fastsearch.h"
485#include "stringlib/partition.h"
486#include "stringlib/split.h"
487#include "stringlib/count.h"
488#include "stringlib/find.h"
489#include "stringlib/find_max_char.h"
490#include "stringlib/localeutil.h"
491#include "stringlib/undef.h"
492
493#include "stringlib/ucs4lib.h"
494#include "stringlib/fastsearch.h"
495#include "stringlib/partition.h"
496#include "stringlib/split.h"
497#include "stringlib/count.h"
498#include "stringlib/find.h"
499#include "stringlib/find_max_char.h"
500#include "stringlib/localeutil.h"
501#include "stringlib/undef.h"
502
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200503#include "stringlib/unicodedefs.h"
504#include "stringlib/fastsearch.h"
505#include "stringlib/count.h"
506#include "stringlib/find.h"
507
Guido van Rossumd57fd912000-03-10 22:53:23 +0000508/* --- Unicode Object ----------------------------------------------------- */
509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200510static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200511fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200513Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
514 Py_ssize_t size, Py_UCS4 ch,
515 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200516{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200517 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
518
519 switch (kind) {
520 case PyUnicode_1BYTE_KIND:
521 {
522 Py_UCS1 ch1 = (Py_UCS1) ch;
523 if (ch1 == ch)
524 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
525 else
526 return -1;
527 }
528 case PyUnicode_2BYTE_KIND:
529 {
530 Py_UCS2 ch2 = (Py_UCS2) ch;
531 if (ch2 == ch)
532 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
533 else
534 return -1;
535 }
536 case PyUnicode_4BYTE_KIND:
537 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
538 default:
539 assert(0);
540 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200542}
543
Victor Stinnerfe226c02011-10-03 03:52:20 +0200544static PyObject*
545resize_compact(PyObject *unicode, Py_ssize_t length)
546{
547 Py_ssize_t char_size;
548 Py_ssize_t struct_size;
549 Py_ssize_t new_size;
550 int share_wstr;
551
552 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200553 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200554 if (PyUnicode_IS_COMPACT_ASCII(unicode))
555 struct_size = sizeof(PyASCIIObject);
556 else
557 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200558 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200559
560 _Py_DEC_REFTOTAL;
561 _Py_ForgetReference(unicode);
562
563 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
564 PyErr_NoMemory();
565 return NULL;
566 }
567 new_size = (struct_size + (length + 1) * char_size);
568
569 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
570 if (unicode == NULL) {
571 PyObject_Del(unicode);
572 PyErr_NoMemory();
573 return NULL;
574 }
575 _Py_NewReference(unicode);
576 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200577 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200578 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
580 _PyUnicode_WSTR_LENGTH(unicode) = length;
581 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200582 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
583 length, 0);
584 return unicode;
585}
586
Alexander Belopolsky40018472011-02-26 01:02:56 +0000587static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200588resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000589{
Victor Stinner95663112011-10-04 01:03:50 +0200590 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200591 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200592 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000593
Victor Stinner95663112011-10-04 01:03:50 +0200594 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200595
596 if (PyUnicode_IS_READY(unicode)) {
597 Py_ssize_t char_size;
598 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200599 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200600 void *data;
601
602 data = _PyUnicode_DATA_ANY(unicode);
603 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200604 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200605 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
606 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200607 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
608 {
609 PyObject_DEL(_PyUnicode_UTF8(unicode));
610 _PyUnicode_UTF8(unicode) = NULL;
611 _PyUnicode_UTF8_LENGTH(unicode) = 0;
612 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200613
614 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
615 PyErr_NoMemory();
616 return -1;
617 }
618 new_size = (length + 1) * char_size;
619
620 data = (PyObject *)PyObject_REALLOC(data, new_size);
621 if (data == NULL) {
622 PyErr_NoMemory();
623 return -1;
624 }
625 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200626 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200627 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 _PyUnicode_WSTR_LENGTH(unicode) = length;
629 }
630 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200631 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200632 _PyUnicode_UTF8_LENGTH(unicode) = length;
633 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200634 _PyUnicode_LENGTH(unicode) = length;
635 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200636 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200637 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200638 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200639 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 }
Victor Stinner95663112011-10-04 01:03:50 +0200641 assert(_PyUnicode_WSTR(unicode) != NULL);
642
643 /* check for integer overflow */
644 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
645 PyErr_NoMemory();
646 return -1;
647 }
648 wstr = _PyUnicode_WSTR(unicode);
649 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
650 if (!wstr) {
651 PyErr_NoMemory();
652 return -1;
653 }
654 _PyUnicode_WSTR(unicode) = wstr;
655 _PyUnicode_WSTR(unicode)[length] = 0;
656 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200657 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000658 return 0;
659}
660
Victor Stinnerfe226c02011-10-03 03:52:20 +0200661static PyObject*
662resize_copy(PyObject *unicode, Py_ssize_t length)
663{
664 Py_ssize_t copy_length;
665 if (PyUnicode_IS_COMPACT(unicode)) {
666 PyObject *copy;
667 assert(PyUnicode_IS_READY(unicode));
668
669 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
670 if (copy == NULL)
671 return NULL;
672
673 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200674 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200675 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200676 }
677 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200678 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200679 assert(_PyUnicode_WSTR(unicode) != NULL);
680 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200681 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 if (w == NULL)
683 return NULL;
684 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
685 copy_length = Py_MIN(copy_length, length);
686 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
687 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200688 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200689 }
690}
691
Guido van Rossumd57fd912000-03-10 22:53:23 +0000692/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000693 Ux0000 terminated; some code (e.g. new_identifier)
694 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000695
696 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000697 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000698
699*/
700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200701#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200702static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#endif
704
Alexander Belopolsky40018472011-02-26 01:02:56 +0000705static PyUnicodeObject *
706_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000707{
708 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000710
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712 if (length == 0 && unicode_empty != NULL) {
713 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200714 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000715 }
716
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000717 /* Ensure we won't overflow the size. */
718 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
719 return (PyUnicodeObject *)PyErr_NoMemory();
720 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200721 if (length < 0) {
722 PyErr_SetString(PyExc_SystemError,
723 "Negative size passed to _PyUnicode_New");
724 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000725 }
726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200727#ifdef Py_DEBUG
728 ++unicode_old_new_calls;
729#endif
730
731 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
732 if (unicode == NULL)
733 return NULL;
734 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
735 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
736 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000737 PyErr_NoMemory();
738 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000739 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200740
Jeremy Hyltond8082792003-09-16 19:41:39 +0000741 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000742 * the caller fails before initializing str -- unicode_resize()
743 * reads str[0], and the Keep-Alive optimization can keep memory
744 * allocated for str alive across a call to unicode_dealloc(unicode).
745 * We don't want unicode_resize to read uninitialized memory in
746 * that case.
747 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200748 _PyUnicode_WSTR(unicode)[0] = 0;
749 _PyUnicode_WSTR(unicode)[length] = 0;
750 _PyUnicode_WSTR_LENGTH(unicode) = length;
751 _PyUnicode_HASH(unicode) = -1;
752 _PyUnicode_STATE(unicode).interned = 0;
753 _PyUnicode_STATE(unicode).kind = 0;
754 _PyUnicode_STATE(unicode).compact = 0;
755 _PyUnicode_STATE(unicode).ready = 0;
756 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200757 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200758 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200759 _PyUnicode_UTF8(unicode) = NULL;
760 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner67072932011-10-18 22:10:14 +0200761 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000762 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000763
Benjamin Peterson29060642009-01-31 22:14:21 +0000764 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000765 /* XXX UNREF/NEWREF interface should be more symmetrical */
766 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000767 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000768 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000770}
771
Victor Stinnerf42dc442011-10-02 23:33:16 +0200772static const char*
773unicode_kind_name(PyObject *unicode)
774{
Victor Stinner42dfd712011-10-03 14:41:45 +0200775 /* don't check consistency: unicode_kind_name() is called from
776 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200777 if (!PyUnicode_IS_COMPACT(unicode))
778 {
779 if (!PyUnicode_IS_READY(unicode))
780 return "wstr";
781 switch(PyUnicode_KIND(unicode))
782 {
783 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200784 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200785 return "legacy ascii";
786 else
787 return "legacy latin1";
788 case PyUnicode_2BYTE_KIND:
789 return "legacy UCS2";
790 case PyUnicode_4BYTE_KIND:
791 return "legacy UCS4";
792 default:
793 return "<legacy invalid kind>";
794 }
795 }
796 assert(PyUnicode_IS_READY(unicode));
797 switch(PyUnicode_KIND(unicode))
798 {
799 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200800 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200801 return "ascii";
802 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200803 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200804 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 default:
809 return "<invalid compact kind>";
810 }
811}
812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200813#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200814static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815
816/* Functions wrapping macros for use in debugger */
817char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200818 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819}
820
821void *_PyUnicode_compact_data(void *unicode) {
822 return _PyUnicode_COMPACT_DATA(unicode);
823}
824void *_PyUnicode_data(void *unicode){
825 printf("obj %p\n", unicode);
826 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
827 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
828 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
829 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
830 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
831 return PyUnicode_DATA(unicode);
832}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200833
834void
835_PyUnicode_Dump(PyObject *op)
836{
837 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200838 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
839 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
840 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200841
Victor Stinnera849a4b2011-10-03 12:12:11 +0200842 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200843 {
844 if (ascii->state.ascii)
845 data = (ascii + 1);
846 else
847 data = (compact + 1);
848 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200849 else
850 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200851 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
852
Victor Stinnera849a4b2011-10-03 12:12:11 +0200853 if (ascii->wstr == data)
854 printf("shared ");
855 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200856
Victor Stinnera3b334d2011-10-03 13:53:37 +0200857 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200858 printf(" (%zu), ", compact->wstr_length);
859 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
860 printf("shared ");
861 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200862 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200863 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200865#endif
866
867PyObject *
868PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
869{
870 PyObject *obj;
871 PyCompactUnicodeObject *unicode;
872 void *data;
873 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200874 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200875 Py_ssize_t char_size;
876 Py_ssize_t struct_size;
877
878 /* Optimization for empty strings */
879 if (size == 0 && unicode_empty != NULL) {
880 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200881 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200882 }
883
884#ifdef Py_DEBUG
885 ++unicode_new_new_calls;
886#endif
887
Victor Stinner9e9d6892011-10-04 01:02:02 +0200888 is_ascii = 0;
889 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200890 struct_size = sizeof(PyCompactUnicodeObject);
891 if (maxchar < 128) {
892 kind_state = PyUnicode_1BYTE_KIND;
893 char_size = 1;
894 is_ascii = 1;
895 struct_size = sizeof(PyASCIIObject);
896 }
897 else if (maxchar < 256) {
898 kind_state = PyUnicode_1BYTE_KIND;
899 char_size = 1;
900 }
901 else if (maxchar < 65536) {
902 kind_state = PyUnicode_2BYTE_KIND;
903 char_size = 2;
904 if (sizeof(wchar_t) == 2)
905 is_sharing = 1;
906 }
907 else {
908 kind_state = PyUnicode_4BYTE_KIND;
909 char_size = 4;
910 if (sizeof(wchar_t) == 4)
911 is_sharing = 1;
912 }
913
914 /* Ensure we won't overflow the size. */
915 if (size < 0) {
916 PyErr_SetString(PyExc_SystemError,
917 "Negative size passed to PyUnicode_New");
918 return NULL;
919 }
920 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
921 return PyErr_NoMemory();
922
923 /* Duplicated allocation code from _PyObject_New() instead of a call to
924 * PyObject_New() so we are able to allocate space for the object and
925 * it's data buffer.
926 */
927 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
928 if (obj == NULL)
929 return PyErr_NoMemory();
930 obj = PyObject_INIT(obj, &PyUnicode_Type);
931 if (obj == NULL)
932 return NULL;
933
934 unicode = (PyCompactUnicodeObject *)obj;
935 if (is_ascii)
936 data = ((PyASCIIObject*)obj) + 1;
937 else
938 data = unicode + 1;
939 _PyUnicode_LENGTH(unicode) = size;
940 _PyUnicode_HASH(unicode) = -1;
941 _PyUnicode_STATE(unicode).interned = 0;
942 _PyUnicode_STATE(unicode).kind = kind_state;
943 _PyUnicode_STATE(unicode).compact = 1;
944 _PyUnicode_STATE(unicode).ready = 1;
945 _PyUnicode_STATE(unicode).ascii = is_ascii;
946 if (is_ascii) {
947 ((char*)data)[size] = 0;
948 _PyUnicode_WSTR(unicode) = NULL;
949 }
950 else if (kind_state == PyUnicode_1BYTE_KIND) {
951 ((char*)data)[size] = 0;
952 _PyUnicode_WSTR(unicode) = NULL;
953 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200954 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200955 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 }
957 else {
958 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200959 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 if (kind_state == PyUnicode_2BYTE_KIND)
961 ((Py_UCS2*)data)[size] = 0;
962 else /* kind_state == PyUnicode_4BYTE_KIND */
963 ((Py_UCS4*)data)[size] = 0;
964 if (is_sharing) {
965 _PyUnicode_WSTR_LENGTH(unicode) = size;
966 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
967 }
968 else {
969 _PyUnicode_WSTR_LENGTH(unicode) = 0;
970 _PyUnicode_WSTR(unicode) = NULL;
971 }
972 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200973 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200974 return obj;
975}
976
977#if SIZEOF_WCHAR_T == 2
978/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
979 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200980 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200981
982 This function assumes that unicode can hold one more code point than wstr
983 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200984static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200985unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200986 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987{
988 const wchar_t *iter;
989 Py_UCS4 *ucs4_out;
990
Victor Stinner910337b2011-10-03 03:20:16 +0200991 assert(unicode != NULL);
992 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
994 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
995
996 for (iter = begin; iter < end; ) {
997 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
998 _PyUnicode_GET_LENGTH(unicode)));
999 if (*iter >= 0xD800 && *iter <= 0xDBFF
1000 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1001 {
1002 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1003 iter += 2;
1004 }
1005 else {
1006 *ucs4_out++ = *iter;
1007 iter++;
1008 }
1009 }
1010 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1011 _PyUnicode_GET_LENGTH(unicode)));
1012
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001013}
1014#endif
1015
Victor Stinnercd9950f2011-10-02 00:34:53 +02001016static int
1017_PyUnicode_Dirty(PyObject *unicode)
1018{
Victor Stinner910337b2011-10-03 03:20:16 +02001019 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001020 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001021 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 "Cannot modify a string having more than 1 reference");
1023 return -1;
1024 }
1025 _PyUnicode_DIRTY(unicode);
1026 return 0;
1027}
1028
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001029static int
1030_copy_characters(PyObject *to, Py_ssize_t to_start,
1031 PyObject *from, Py_ssize_t from_start,
1032 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001033{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001034 unsigned int from_kind, to_kind;
1035 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001036 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001037
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 assert(PyUnicode_Check(from));
1039 assert(PyUnicode_Check(to));
1040 assert(PyUnicode_IS_READY(from));
1041 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001042
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001043 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1044 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1045 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001047 if (how_many == 0)
1048 return 0;
1049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001050 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001051 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001055#ifdef Py_DEBUG
1056 if (!check_maxchar
1057 && (from_kind > to_kind
1058 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001059 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001060 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1061 Py_UCS4 ch;
1062 Py_ssize_t i;
1063 for (i=0; i < how_many; i++) {
1064 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1065 assert(ch <= to_maxchar);
1066 }
1067 }
1068#endif
1069 fast = (from_kind == to_kind);
1070 if (check_maxchar
1071 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1072 {
1073 /* deny latin1 => ascii */
1074 fast = 0;
1075 }
1076
1077 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001078 Py_MEMCPY((char*)to_data + to_kind * to_start,
1079 (char*)from_data + from_kind * from_start,
1080 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001081 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001082 else if (from_kind == PyUnicode_1BYTE_KIND
1083 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001084 {
1085 _PyUnicode_CONVERT_BYTES(
1086 Py_UCS1, Py_UCS2,
1087 PyUnicode_1BYTE_DATA(from) + from_start,
1088 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1089 PyUnicode_2BYTE_DATA(to) + to_start
1090 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001091 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001092 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 && to_kind == PyUnicode_4BYTE_KIND)
1094 {
1095 _PyUnicode_CONVERT_BYTES(
1096 Py_UCS1, Py_UCS4,
1097 PyUnicode_1BYTE_DATA(from) + from_start,
1098 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1099 PyUnicode_4BYTE_DATA(to) + to_start
1100 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001101 }
1102 else if (from_kind == PyUnicode_2BYTE_KIND
1103 && to_kind == PyUnicode_4BYTE_KIND)
1104 {
1105 _PyUnicode_CONVERT_BYTES(
1106 Py_UCS2, Py_UCS4,
1107 PyUnicode_2BYTE_DATA(from) + from_start,
1108 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1109 PyUnicode_4BYTE_DATA(to) + to_start
1110 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001111 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001112 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001113 /* check if max_char(from substring) <= max_char(to) */
1114 if (from_kind > to_kind
1115 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001116 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001117 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001118 /* slow path to check for character overflow */
1119 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001120 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001121 Py_ssize_t i;
1122
Victor Stinner56c161a2011-10-06 02:47:11 +02001123#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001124 for (i=0; i < how_many; i++) {
1125 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001126 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1128 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001129#else
1130 if (!check_maxchar) {
1131 for (i=0; i < how_many; i++) {
1132 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1133 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1134 }
1135 }
1136 else {
1137 for (i=0; i < how_many; i++) {
1138 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1139 if (ch > to_maxchar)
1140 return 1;
1141 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1142 }
1143 }
1144#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001145 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001146 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001147 assert(0 && "inconsistent state");
1148 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001149 }
1150 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001151 return 0;
1152}
1153
1154static void
1155copy_characters(PyObject *to, Py_ssize_t to_start,
1156 PyObject *from, Py_ssize_t from_start,
1157 Py_ssize_t how_many)
1158{
1159 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1160}
1161
1162Py_ssize_t
1163PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1164 PyObject *from, Py_ssize_t from_start,
1165 Py_ssize_t how_many)
1166{
1167 int err;
1168
1169 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1170 PyErr_BadInternalCall();
1171 return -1;
1172 }
1173
1174 if (PyUnicode_READY(from))
1175 return -1;
1176 if (PyUnicode_READY(to))
1177 return -1;
1178
1179 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1180 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1181 PyErr_Format(PyExc_SystemError,
1182 "Cannot write %zi characters at %zi "
1183 "in a string of %zi characters",
1184 how_many, to_start, PyUnicode_GET_LENGTH(to));
1185 return -1;
1186 }
1187
1188 if (how_many == 0)
1189 return 0;
1190
1191 if (_PyUnicode_Dirty(to))
1192 return -1;
1193
1194 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1195 if (err) {
1196 PyErr_Format(PyExc_SystemError,
1197 "Cannot copy %s characters "
1198 "into a string of %s characters",
1199 unicode_kind_name(from),
1200 unicode_kind_name(to));
1201 return -1;
1202 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001203 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001204}
1205
Victor Stinner17222162011-09-28 22:15:37 +02001206/* Find the maximum code point and count the number of surrogate pairs so a
1207 correct string length can be computed before converting a string to UCS4.
1208 This function counts single surrogates as a character and not as a pair.
1209
1210 Return 0 on success, or -1 on error. */
1211static int
1212find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1213 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001214{
1215 const wchar_t *iter;
1216
Victor Stinnerc53be962011-10-02 21:33:54 +02001217 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001218 *num_surrogates = 0;
1219 *maxchar = 0;
1220
1221 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001222 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001224#if SIZEOF_WCHAR_T != 2
1225 if (*maxchar >= 0x10000)
1226 return 0;
1227#endif
1228 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229#if SIZEOF_WCHAR_T == 2
1230 if (*iter >= 0xD800 && *iter <= 0xDBFF
1231 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1232 {
1233 Py_UCS4 surrogate_val;
1234 surrogate_val = (((iter[0] & 0x3FF)<<10)
1235 | (iter[1] & 0x3FF)) + 0x10000;
1236 ++(*num_surrogates);
1237 if (surrogate_val > *maxchar)
1238 *maxchar = surrogate_val;
1239 iter += 2;
1240 }
1241 else
1242 iter++;
1243#else
1244 iter++;
1245#endif
1246 }
1247 return 0;
1248}
1249
1250#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001251static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001252#endif
1253
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001254static int
1255unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001256{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001257 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258 wchar_t *end;
1259 Py_UCS4 maxchar = 0;
1260 Py_ssize_t num_surrogates;
1261#if SIZEOF_WCHAR_T == 2
1262 Py_ssize_t length_wo_surrogates;
1263#endif
1264
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001265 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001266 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267
Georg Brandl7597add2011-10-05 16:36:47 +02001268 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001269 strings were created using _PyObject_New() and where no canonical
1270 representation (the str field) has been set yet aka strings
1271 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001272 assert(_PyUnicode_CHECK(unicode));
1273 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001274 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001275 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001276 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001277 /* Actually, it should neither be interned nor be anything else: */
1278 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001279
1280#ifdef Py_DEBUG
1281 ++unicode_ready_calls;
1282#endif
1283
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001284#ifdef Py_DEBUG
1285 assert(!replace || Py_REFCNT(unicode) == 1);
1286#else
1287 if (replace && Py_REFCNT(unicode) != 1)
1288 replace = 0;
1289#endif
1290 if (replace) {
1291 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1292 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1293 /* Optimization for empty strings */
1294 if (len == 0) {
1295 Py_INCREF(unicode_empty);
1296 Py_DECREF(*p_obj);
1297 *p_obj = unicode_empty;
1298 return 0;
1299 }
1300 if (len == 1 && wstr[0] < 256) {
1301 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1302 if (latin1_char == NULL)
1303 return -1;
1304 Py_DECREF(*p_obj);
1305 *p_obj = latin1_char;
1306 return 0;
1307 }
1308 }
1309
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001311 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001312 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001313 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314
1315 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001316 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1317 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001318 PyErr_NoMemory();
1319 return -1;
1320 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001321 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001322 _PyUnicode_WSTR(unicode), end,
1323 PyUnicode_1BYTE_DATA(unicode));
1324 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1325 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1326 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1327 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001328 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001329 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001330 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001331 }
1332 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001333 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001334 _PyUnicode_UTF8(unicode) = NULL;
1335 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336 }
1337 PyObject_FREE(_PyUnicode_WSTR(unicode));
1338 _PyUnicode_WSTR(unicode) = NULL;
1339 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1340 }
1341 /* In this case we might have to convert down from 4-byte native
1342 wchar_t to 2-byte unicode. */
1343 else if (maxchar < 65536) {
1344 assert(num_surrogates == 0 &&
1345 "FindMaxCharAndNumSurrogatePairs() messed up");
1346
Victor Stinner506f5922011-09-28 22:34:18 +02001347#if SIZEOF_WCHAR_T == 2
1348 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001349 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001350 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1351 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1352 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001353 _PyUnicode_UTF8(unicode) = NULL;
1354 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001355#else
1356 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001357 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001358 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001360 PyErr_NoMemory();
1361 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001362 }
Victor Stinner506f5922011-09-28 22:34:18 +02001363 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1364 _PyUnicode_WSTR(unicode), end,
1365 PyUnicode_2BYTE_DATA(unicode));
1366 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1367 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1368 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001369 _PyUnicode_UTF8(unicode) = NULL;
1370 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001371 PyObject_FREE(_PyUnicode_WSTR(unicode));
1372 _PyUnicode_WSTR(unicode) = NULL;
1373 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1374#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001375 }
1376 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1377 else {
1378#if SIZEOF_WCHAR_T == 2
1379 /* in case the native representation is 2-bytes, we need to allocate a
1380 new normalized 4-byte version. */
1381 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001382 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1383 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001384 PyErr_NoMemory();
1385 return -1;
1386 }
1387 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1388 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001389 _PyUnicode_UTF8(unicode) = NULL;
1390 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001391 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1392 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001393 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001394 PyObject_FREE(_PyUnicode_WSTR(unicode));
1395 _PyUnicode_WSTR(unicode) = NULL;
1396 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1397#else
1398 assert(num_surrogates == 0);
1399
Victor Stinnerc3c74152011-10-02 20:39:55 +02001400 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001401 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001402 _PyUnicode_UTF8(unicode) = NULL;
1403 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001404 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1405#endif
1406 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1407 }
1408 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001409 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410 return 0;
1411}
1412
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001413int
1414_PyUnicode_ReadyReplace(PyObject **op)
1415{
1416 return unicode_ready(op, 1);
1417}
1418
1419int
1420_PyUnicode_Ready(PyObject *op)
1421{
1422 return unicode_ready(&op, 0);
1423}
1424
Alexander Belopolsky40018472011-02-26 01:02:56 +00001425static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001426unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001427{
Walter Dörwald16807132007-05-25 13:52:07 +00001428 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001429 case SSTATE_NOT_INTERNED:
1430 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001431
Benjamin Peterson29060642009-01-31 22:14:21 +00001432 case SSTATE_INTERNED_MORTAL:
1433 /* revive dead object temporarily for DelItem */
1434 Py_REFCNT(unicode) = 3;
1435 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1436 Py_FatalError(
1437 "deletion of interned string failed");
1438 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001439
Benjamin Peterson29060642009-01-31 22:14:21 +00001440 case SSTATE_INTERNED_IMMORTAL:
1441 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001442
Benjamin Peterson29060642009-01-31 22:14:21 +00001443 default:
1444 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001445 }
1446
Victor Stinner03490912011-10-03 23:45:12 +02001447 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001448 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001449 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001450 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001451
1452 if (PyUnicode_IS_COMPACT(unicode)) {
1453 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001454 }
1455 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001456 if (_PyUnicode_DATA_ANY(unicode))
1457 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001458 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001459 }
1460}
1461
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001462#ifdef Py_DEBUG
1463static int
1464unicode_is_singleton(PyObject *unicode)
1465{
1466 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1467 if (unicode == unicode_empty)
1468 return 1;
1469 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1470 {
1471 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1472 if (ch < 256 && unicode_latin1[ch] == unicode)
1473 return 1;
1474 }
1475 return 0;
1476}
1477#endif
1478
Alexander Belopolsky40018472011-02-26 01:02:56 +00001479static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001480unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001481{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482 if (Py_REFCNT(unicode) != 1)
1483 return 0;
1484 if (PyUnicode_CHECK_INTERNED(unicode))
1485 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001486#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001487 /* singleton refcount is greater than 1 */
1488 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001489#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001490 return 1;
1491}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001492
Victor Stinnerfe226c02011-10-03 03:52:20 +02001493static int
1494unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1495{
1496 PyObject *unicode;
1497 Py_ssize_t old_length;
1498
1499 assert(p_unicode != NULL);
1500 unicode = *p_unicode;
1501
1502 assert(unicode != NULL);
1503 assert(PyUnicode_Check(unicode));
1504 assert(0 <= length);
1505
Victor Stinner910337b2011-10-03 03:20:16 +02001506 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001507 old_length = PyUnicode_WSTR_LENGTH(unicode);
1508 else
1509 old_length = PyUnicode_GET_LENGTH(unicode);
1510 if (old_length == length)
1511 return 0;
1512
Victor Stinnerfe226c02011-10-03 03:52:20 +02001513 if (!unicode_resizable(unicode)) {
1514 PyObject *copy = resize_copy(unicode, length);
1515 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001516 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001517 Py_DECREF(*p_unicode);
1518 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001519 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (PyUnicode_IS_COMPACT(unicode)) {
1523 *p_unicode = resize_compact(unicode, length);
1524 if (*p_unicode == NULL)
1525 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001526 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001527 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001528 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001529 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001530}
1531
Alexander Belopolsky40018472011-02-26 01:02:56 +00001532int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001533PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001534{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001535 PyObject *unicode;
1536 if (p_unicode == NULL) {
1537 PyErr_BadInternalCall();
1538 return -1;
1539 }
1540 unicode = *p_unicode;
1541 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1542 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1543 {
1544 PyErr_BadInternalCall();
1545 return -1;
1546 }
1547 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001548}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001550static PyObject*
1551get_latin1_char(unsigned char ch)
1552{
Victor Stinnera464fc12011-10-02 20:39:30 +02001553 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001554 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001555 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001556 if (!unicode)
1557 return NULL;
1558 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001559 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 unicode_latin1[ch] = unicode;
1561 }
1562 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001563 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001564}
1565
Alexander Belopolsky40018472011-02-26 01:02:56 +00001566PyObject *
1567PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001568{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001569 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001570 Py_UCS4 maxchar = 0;
1571 Py_ssize_t num_surrogates;
1572
1573 if (u == NULL)
1574 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001575
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001576 /* If the Unicode data is known at construction time, we can apply
1577 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001578
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001579 /* Optimization for empty strings */
1580 if (size == 0 && unicode_empty != NULL) {
1581 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001582 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583 }
Tim Petersced69f82003-09-16 20:30:58 +00001584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585 /* Single character Unicode objects in the Latin-1 range are
1586 shared when using this constructor */
1587 if (size == 1 && *u < 256)
1588 return get_latin1_char((unsigned char)*u);
1589
1590 /* If not empty and not single character, copy the Unicode data
1591 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001592 if (find_maxchar_surrogates(u, u + size,
1593 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 return NULL;
1595
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001596 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001597 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001598 if (!unicode)
1599 return NULL;
1600
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001601 switch (PyUnicode_KIND(unicode)) {
1602 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001603 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001604 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1605 break;
1606 case PyUnicode_2BYTE_KIND:
1607#if Py_UNICODE_SIZE == 2
1608 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1609#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001610 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001611 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1612#endif
1613 break;
1614 case PyUnicode_4BYTE_KIND:
1615#if SIZEOF_WCHAR_T == 2
1616 /* This is the only case which has to process surrogates, thus
1617 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001618 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001619#else
1620 assert(num_surrogates == 0);
1621 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1622#endif
1623 break;
1624 default:
1625 assert(0 && "Impossible state");
1626 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001627
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001628 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001629 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001630}
1631
Alexander Belopolsky40018472011-02-26 01:02:56 +00001632PyObject *
1633PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001634{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001635 if (size < 0) {
1636 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001637 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001638 return NULL;
1639 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001640
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001641 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001642 some optimizations which share commonly used objects.
1643 Also, this means the input must be UTF-8, so fall back to the
1644 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001645 if (u != NULL) {
1646
Benjamin Peterson29060642009-01-31 22:14:21 +00001647 /* Optimization for empty strings */
1648 if (size == 0 && unicode_empty != NULL) {
1649 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001650 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001651 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001652
1653 /* Single characters are shared when using this constructor.
1654 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001655 if (size == 1 && (unsigned char)*u < 128)
1656 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001657
1658 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001659 }
1660
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001661 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001662}
1663
Alexander Belopolsky40018472011-02-26 01:02:56 +00001664PyObject *
1665PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001666{
1667 size_t size = strlen(u);
1668 if (size > PY_SSIZE_T_MAX) {
1669 PyErr_SetString(PyExc_OverflowError, "input too long");
1670 return NULL;
1671 }
1672
1673 return PyUnicode_FromStringAndSize(u, size);
1674}
1675
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001676PyObject *
1677_PyUnicode_FromId(_Py_Identifier *id)
1678{
1679 if (!id->object) {
1680 id->object = PyUnicode_FromString(id->string);
1681 if (!id->object)
1682 return NULL;
1683 PyUnicode_InternInPlace(&id->object);
1684 assert(!id->next);
1685 id->next = static_strings;
1686 static_strings = id;
1687 }
1688 Py_INCREF(id->object);
1689 return id->object;
1690}
1691
1692void
1693_PyUnicode_ClearStaticStrings()
1694{
1695 _Py_Identifier *i;
1696 for (i = static_strings; i; i = i->next) {
1697 Py_DECREF(i->object);
1698 i->object = NULL;
1699 i->next = NULL;
1700 }
1701}
1702
Victor Stinnere57b1c02011-09-28 22:20:48 +02001703static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001704unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001705{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001706 PyObject *res;
1707#ifdef Py_DEBUG
1708 const unsigned char *p;
1709 const unsigned char *end = s + size;
1710 for (p=s; p < end; p++) {
1711 assert(*p < 128);
1712 }
1713#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001714 if (size == 1)
1715 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001716 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001717 if (!res)
1718 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001719 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001720 return res;
1721}
1722
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001723static Py_UCS4
1724kind_maxchar_limit(unsigned int kind)
1725{
1726 switch(kind) {
1727 case PyUnicode_1BYTE_KIND:
1728 return 0x80;
1729 case PyUnicode_2BYTE_KIND:
1730 return 0x100;
1731 case PyUnicode_4BYTE_KIND:
1732 return 0x10000;
1733 default:
1734 assert(0 && "invalid kind");
1735 return 0x10ffff;
1736 }
1737}
1738
Victor Stinner702c7342011-10-05 13:50:52 +02001739static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001741{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001742 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001743 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001744
1745 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001746 if (size == 1)
1747 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001748 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001749 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001750 if (!res)
1751 return NULL;
1752 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001753 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001754 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001755}
1756
Victor Stinnere57b1c02011-09-28 22:20:48 +02001757static PyObject*
1758_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759{
1760 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001761 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001762
1763 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001764 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001765 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001766 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001767 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001768 if (!res)
1769 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001770 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001771 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001772 else {
1773 _PyUnicode_CONVERT_BYTES(
1774 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1775 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001776 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001777 return res;
1778}
1779
Victor Stinnere57b1c02011-09-28 22:20:48 +02001780static PyObject*
1781_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782{
1783 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001784 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001785
1786 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001787 if (size == 1 && u[0] < 256)
1788 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001789 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001790 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 if (!res)
1792 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001793 if (max_char < 256)
1794 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1795 PyUnicode_1BYTE_DATA(res));
1796 else if (max_char < 0x10000)
1797 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1798 PyUnicode_2BYTE_DATA(res));
1799 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001801 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001802 return res;
1803}
1804
1805PyObject*
1806PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1807{
1808 switch(kind) {
1809 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001810 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001812 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001813 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001814 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001815 default:
1816 assert(0 && "invalid kind");
1817 PyErr_SetString(PyExc_SystemError, "invalid kind");
1818 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001820}
1821
Victor Stinner25a4b292011-10-06 12:31:55 +02001822/* Ensure that a string uses the most efficient storage, if it is not the
1823 case: create a new string with of the right kind. Write NULL into *p_unicode
1824 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001825static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001826unicode_adjust_maxchar(PyObject **p_unicode)
1827{
1828 PyObject *unicode, *copy;
1829 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001830 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001831 unsigned int kind;
1832
1833 assert(p_unicode != NULL);
1834 unicode = *p_unicode;
1835 assert(PyUnicode_IS_READY(unicode));
1836 if (PyUnicode_IS_ASCII(unicode))
1837 return;
1838
1839 len = PyUnicode_GET_LENGTH(unicode);
1840 kind = PyUnicode_KIND(unicode);
1841 if (kind == PyUnicode_1BYTE_KIND) {
1842 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001843 max_char = ucs1lib_find_max_char(u, u + len);
1844 if (max_char >= 128)
1845 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001846 }
1847 else if (kind == PyUnicode_2BYTE_KIND) {
1848 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001849 max_char = ucs2lib_find_max_char(u, u + len);
1850 if (max_char >= 256)
1851 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001852 }
1853 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001854 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001855 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001856 max_char = ucs4lib_find_max_char(u, u + len);
1857 if (max_char >= 0x10000)
1858 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001859 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001860 copy = PyUnicode_New(len, max_char);
1861 copy_characters(copy, 0, unicode, 0, len);
1862 Py_DECREF(unicode);
1863 *p_unicode = copy;
1864}
1865
Victor Stinner034f6cf2011-09-30 02:26:44 +02001866PyObject*
1867PyUnicode_Copy(PyObject *unicode)
1868{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001869 Py_ssize_t size;
1870 PyObject *copy;
1871 void *data;
1872
Victor Stinner034f6cf2011-09-30 02:26:44 +02001873 if (!PyUnicode_Check(unicode)) {
1874 PyErr_BadInternalCall();
1875 return NULL;
1876 }
1877 if (PyUnicode_READY(unicode))
1878 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001879
1880 size = PyUnicode_GET_LENGTH(unicode);
1881 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1882 if (!copy)
1883 return NULL;
1884 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1885
1886 data = PyUnicode_DATA(unicode);
1887 switch (PyUnicode_KIND(unicode))
1888 {
1889 case PyUnicode_1BYTE_KIND:
1890 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1891 break;
1892 case PyUnicode_2BYTE_KIND:
1893 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1894 break;
1895 case PyUnicode_4BYTE_KIND:
1896 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1897 break;
1898 default:
1899 assert(0);
1900 break;
1901 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001902 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001903 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001904}
1905
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001906
Victor Stinnerbc603d12011-10-02 01:00:40 +02001907/* Widen Unicode objects to larger buffers. Don't write terminating null
1908 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001909
1910void*
1911_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1912{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001913 Py_ssize_t len;
1914 void *result;
1915 unsigned int skind;
1916
1917 if (PyUnicode_READY(s))
1918 return NULL;
1919
1920 len = PyUnicode_GET_LENGTH(s);
1921 skind = PyUnicode_KIND(s);
1922 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001923 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001924 return NULL;
1925 }
1926 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001927 case PyUnicode_2BYTE_KIND:
1928 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1929 if (!result)
1930 return PyErr_NoMemory();
1931 assert(skind == PyUnicode_1BYTE_KIND);
1932 _PyUnicode_CONVERT_BYTES(
1933 Py_UCS1, Py_UCS2,
1934 PyUnicode_1BYTE_DATA(s),
1935 PyUnicode_1BYTE_DATA(s) + len,
1936 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001937 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001938 case PyUnicode_4BYTE_KIND:
1939 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1940 if (!result)
1941 return PyErr_NoMemory();
1942 if (skind == PyUnicode_2BYTE_KIND) {
1943 _PyUnicode_CONVERT_BYTES(
1944 Py_UCS2, Py_UCS4,
1945 PyUnicode_2BYTE_DATA(s),
1946 PyUnicode_2BYTE_DATA(s) + len,
1947 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001948 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001949 else {
1950 assert(skind == PyUnicode_1BYTE_KIND);
1951 _PyUnicode_CONVERT_BYTES(
1952 Py_UCS1, Py_UCS4,
1953 PyUnicode_1BYTE_DATA(s),
1954 PyUnicode_1BYTE_DATA(s) + len,
1955 result);
1956 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001957 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001958 default:
1959 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960 }
Victor Stinner01698042011-10-04 00:04:26 +02001961 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962 return NULL;
1963}
1964
1965static Py_UCS4*
1966as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1967 int copy_null)
1968{
1969 int kind;
1970 void *data;
1971 Py_ssize_t len, targetlen;
1972 if (PyUnicode_READY(string) == -1)
1973 return NULL;
1974 kind = PyUnicode_KIND(string);
1975 data = PyUnicode_DATA(string);
1976 len = PyUnicode_GET_LENGTH(string);
1977 targetlen = len;
1978 if (copy_null)
1979 targetlen++;
1980 if (!target) {
1981 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1982 PyErr_NoMemory();
1983 return NULL;
1984 }
1985 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1986 if (!target) {
1987 PyErr_NoMemory();
1988 return NULL;
1989 }
1990 }
1991 else {
1992 if (targetsize < targetlen) {
1993 PyErr_Format(PyExc_SystemError,
1994 "string is longer than the buffer");
1995 if (copy_null && 0 < targetsize)
1996 target[0] = 0;
1997 return NULL;
1998 }
1999 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002000 if (kind == PyUnicode_1BYTE_KIND) {
2001 Py_UCS1 *start = (Py_UCS1 *) data;
2002 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002004 else if (kind == PyUnicode_2BYTE_KIND) {
2005 Py_UCS2 *start = (Py_UCS2 *) data;
2006 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2007 }
2008 else {
2009 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002012 if (copy_null)
2013 target[len] = 0;
2014 return target;
2015}
2016
2017Py_UCS4*
2018PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2019 int copy_null)
2020{
2021 if (target == NULL || targetsize < 1) {
2022 PyErr_BadInternalCall();
2023 return NULL;
2024 }
2025 return as_ucs4(string, target, targetsize, copy_null);
2026}
2027
2028Py_UCS4*
2029PyUnicode_AsUCS4Copy(PyObject *string)
2030{
2031 return as_ucs4(string, NULL, 0, 1);
2032}
2033
2034#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002035
Alexander Belopolsky40018472011-02-26 01:02:56 +00002036PyObject *
2037PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002038{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002039 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002040 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002042 PyErr_BadInternalCall();
2043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002044 }
2045
Martin v. Löwis790465f2008-04-05 20:41:37 +00002046 if (size == -1) {
2047 size = wcslen(w);
2048 }
2049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002051}
2052
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002054
Walter Dörwald346737f2007-05-31 10:44:43 +00002055static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002056makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2057 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002058{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002059 *fmt++ = '%';
2060 if (width) {
2061 if (zeropad)
2062 *fmt++ = '0';
2063 fmt += sprintf(fmt, "%d", width);
2064 }
2065 if (precision)
2066 fmt += sprintf(fmt, ".%d", precision);
2067 if (longflag)
2068 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002069 else if (longlongflag) {
2070 /* longlongflag should only ever be nonzero on machines with
2071 HAVE_LONG_LONG defined */
2072#ifdef HAVE_LONG_LONG
2073 char *f = PY_FORMAT_LONG_LONG;
2074 while (*f)
2075 *fmt++ = *f++;
2076#else
2077 /* we shouldn't ever get here */
2078 assert(0);
2079 *fmt++ = 'l';
2080#endif
2081 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002082 else if (size_tflag) {
2083 char *f = PY_FORMAT_SIZE_T;
2084 while (*f)
2085 *fmt++ = *f++;
2086 }
2087 *fmt++ = c;
2088 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002089}
2090
Victor Stinner96865452011-03-01 23:44:09 +00002091/* helper for PyUnicode_FromFormatV() */
2092
2093static const char*
2094parse_format_flags(const char *f,
2095 int *p_width, int *p_precision,
2096 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2097{
2098 int width, precision, longflag, longlongflag, size_tflag;
2099
2100 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2101 f++;
2102 width = 0;
2103 while (Py_ISDIGIT((unsigned)*f))
2104 width = (width*10) + *f++ - '0';
2105 precision = 0;
2106 if (*f == '.') {
2107 f++;
2108 while (Py_ISDIGIT((unsigned)*f))
2109 precision = (precision*10) + *f++ - '0';
2110 if (*f == '%') {
2111 /* "%.3%s" => f points to "3" */
2112 f--;
2113 }
2114 }
2115 if (*f == '\0') {
2116 /* bogus format "%.1" => go backward, f points to "1" */
2117 f--;
2118 }
2119 if (p_width != NULL)
2120 *p_width = width;
2121 if (p_precision != NULL)
2122 *p_precision = precision;
2123
2124 /* Handle %ld, %lu, %lld and %llu. */
2125 longflag = 0;
2126 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002127 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002128
2129 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002130 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002131 longflag = 1;
2132 ++f;
2133 }
2134#ifdef HAVE_LONG_LONG
2135 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002136 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002137 longlongflag = 1;
2138 f += 2;
2139 }
2140#endif
2141 }
2142 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002143 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002144 size_tflag = 1;
2145 ++f;
2146 }
2147 if (p_longflag != NULL)
2148 *p_longflag = longflag;
2149 if (p_longlongflag != NULL)
2150 *p_longlongflag = longlongflag;
2151 if (p_size_tflag != NULL)
2152 *p_size_tflag = size_tflag;
2153 return f;
2154}
2155
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002156/* maximum number of characters required for output of %ld. 21 characters
2157 allows for 64-bit integers (in decimal) and an optional sign. */
2158#define MAX_LONG_CHARS 21
2159/* maximum number of characters required for output of %lld.
2160 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2161 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2162#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2163
Walter Dörwaldd2034312007-05-18 16:29:38 +00002164PyObject *
2165PyUnicode_FromFormatV(const char *format, va_list vargs)
2166{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002167 va_list count;
2168 Py_ssize_t callcount = 0;
2169 PyObject **callresults = NULL;
2170 PyObject **callresult = NULL;
2171 Py_ssize_t n = 0;
2172 int width = 0;
2173 int precision = 0;
2174 int zeropad;
2175 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002176 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002177 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002178 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002179 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2180 Py_UCS4 argmaxchar;
2181 Py_ssize_t numbersize = 0;
2182 char *numberresults = NULL;
2183 char *numberresult = NULL;
2184 Py_ssize_t i;
2185 int kind;
2186 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002187
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002188 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002189 /* step 1: count the number of %S/%R/%A/%s format specifications
2190 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2191 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002192 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002193 * also estimate a upper bound for all the number formats in the string,
2194 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002195 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002196 for (f = format; *f; f++) {
2197 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002198 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002199 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2200 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2201 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2202 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002205#ifdef HAVE_LONG_LONG
2206 if (longlongflag) {
2207 if (width < MAX_LONG_LONG_CHARS)
2208 width = MAX_LONG_LONG_CHARS;
2209 }
2210 else
2211#endif
2212 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2213 including sign. Decimal takes the most space. This
2214 isn't enough for octal. If a width is specified we
2215 need more (which we allocate later). */
2216 if (width < MAX_LONG_CHARS)
2217 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002218
2219 /* account for the size + '\0' to separate numbers
2220 inside of the numberresults buffer */
2221 numbersize += (width + 1);
2222 }
2223 }
2224 else if ((unsigned char)*f > 127) {
2225 PyErr_Format(PyExc_ValueError,
2226 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2227 "string, got a non-ASCII byte: 0x%02x",
2228 (unsigned char)*f);
2229 return NULL;
2230 }
2231 }
2232 /* step 2: allocate memory for the results of
2233 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2234 if (callcount) {
2235 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2236 if (!callresults) {
2237 PyErr_NoMemory();
2238 return NULL;
2239 }
2240 callresult = callresults;
2241 }
2242 /* step 2.5: allocate memory for the results of formating numbers */
2243 if (numbersize) {
2244 numberresults = PyObject_Malloc(numbersize);
2245 if (!numberresults) {
2246 PyErr_NoMemory();
2247 goto fail;
2248 }
2249 numberresult = numberresults;
2250 }
2251
2252 /* step 3: format numbers and figure out how large a buffer we need */
2253 for (f = format; *f; f++) {
2254 if (*f == '%') {
2255 const char* p;
2256 int longflag;
2257 int longlongflag;
2258 int size_tflag;
2259 int numprinted;
2260
2261 p = f;
2262 zeropad = (f[1] == '0');
2263 f = parse_format_flags(f, &width, &precision,
2264 &longflag, &longlongflag, &size_tflag);
2265 switch (*f) {
2266 case 'c':
2267 {
2268 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002269 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002270 n++;
2271 break;
2272 }
2273 case '%':
2274 n++;
2275 break;
2276 case 'i':
2277 case 'd':
2278 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2279 width, precision, *f);
2280 if (longflag)
2281 numprinted = sprintf(numberresult, fmt,
2282 va_arg(count, long));
2283#ifdef HAVE_LONG_LONG
2284 else if (longlongflag)
2285 numprinted = sprintf(numberresult, fmt,
2286 va_arg(count, PY_LONG_LONG));
2287#endif
2288 else if (size_tflag)
2289 numprinted = sprintf(numberresult, fmt,
2290 va_arg(count, Py_ssize_t));
2291 else
2292 numprinted = sprintf(numberresult, fmt,
2293 va_arg(count, int));
2294 n += numprinted;
2295 /* advance by +1 to skip over the '\0' */
2296 numberresult += (numprinted + 1);
2297 assert(*(numberresult - 1) == '\0');
2298 assert(*(numberresult - 2) != '\0');
2299 assert(numprinted >= 0);
2300 assert(numberresult <= numberresults + numbersize);
2301 break;
2302 case 'u':
2303 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2304 width, precision, 'u');
2305 if (longflag)
2306 numprinted = sprintf(numberresult, fmt,
2307 va_arg(count, unsigned long));
2308#ifdef HAVE_LONG_LONG
2309 else if (longlongflag)
2310 numprinted = sprintf(numberresult, fmt,
2311 va_arg(count, unsigned PY_LONG_LONG));
2312#endif
2313 else if (size_tflag)
2314 numprinted = sprintf(numberresult, fmt,
2315 va_arg(count, size_t));
2316 else
2317 numprinted = sprintf(numberresult, fmt,
2318 va_arg(count, unsigned int));
2319 n += numprinted;
2320 numberresult += (numprinted + 1);
2321 assert(*(numberresult - 1) == '\0');
2322 assert(*(numberresult - 2) != '\0');
2323 assert(numprinted >= 0);
2324 assert(numberresult <= numberresults + numbersize);
2325 break;
2326 case 'x':
2327 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2328 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2329 n += numprinted;
2330 numberresult += (numprinted + 1);
2331 assert(*(numberresult - 1) == '\0');
2332 assert(*(numberresult - 2) != '\0');
2333 assert(numprinted >= 0);
2334 assert(numberresult <= numberresults + numbersize);
2335 break;
2336 case 'p':
2337 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2338 /* %p is ill-defined: ensure leading 0x. */
2339 if (numberresult[1] == 'X')
2340 numberresult[1] = 'x';
2341 else if (numberresult[1] != 'x') {
2342 memmove(numberresult + 2, numberresult,
2343 strlen(numberresult) + 1);
2344 numberresult[0] = '0';
2345 numberresult[1] = 'x';
2346 numprinted += 2;
2347 }
2348 n += numprinted;
2349 numberresult += (numprinted + 1);
2350 assert(*(numberresult - 1) == '\0');
2351 assert(*(numberresult - 2) != '\0');
2352 assert(numprinted >= 0);
2353 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002354 break;
2355 case 's':
2356 {
2357 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002358 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002359 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2360 if (!str)
2361 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002362 /* since PyUnicode_DecodeUTF8 returns already flexible
2363 unicode objects, there is no need to call ready on them */
2364 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002365 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002366 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002367 /* Remember the str and switch to the next slot */
2368 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002369 break;
2370 }
2371 case 'U':
2372 {
2373 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002374 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002375 if (PyUnicode_READY(obj) == -1)
2376 goto fail;
2377 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002378 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002379 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002380 break;
2381 }
2382 case 'V':
2383 {
2384 PyObject *obj = va_arg(count, PyObject *);
2385 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002386 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002387 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002388 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002389 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002390 if (PyUnicode_READY(obj) == -1)
2391 goto fail;
2392 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002393 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002394 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002395 *callresult++ = NULL;
2396 }
2397 else {
2398 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2399 if (!str_obj)
2400 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002401 if (PyUnicode_READY(str_obj)) {
2402 Py_DECREF(str_obj);
2403 goto fail;
2404 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002405 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002406 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002408 *callresult++ = str_obj;
2409 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 break;
2411 }
2412 case 'S':
2413 {
2414 PyObject *obj = va_arg(count, PyObject *);
2415 PyObject *str;
2416 assert(obj);
2417 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002419 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002421 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002422 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002423 /* Remember the str and switch to the next slot */
2424 *callresult++ = str;
2425 break;
2426 }
2427 case 'R':
2428 {
2429 PyObject *obj = va_arg(count, PyObject *);
2430 PyObject *repr;
2431 assert(obj);
2432 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002434 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002436 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002437 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002438 /* Remember the repr and switch to the next slot */
2439 *callresult++ = repr;
2440 break;
2441 }
2442 case 'A':
2443 {
2444 PyObject *obj = va_arg(count, PyObject *);
2445 PyObject *ascii;
2446 assert(obj);
2447 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002449 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002451 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002452 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002453 /* Remember the repr and switch to the next slot */
2454 *callresult++ = ascii;
2455 break;
2456 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002457 default:
2458 /* if we stumble upon an unknown
2459 formatting code, copy the rest of
2460 the format string to the output
2461 string. (we cannot just skip the
2462 code, since there's no way to know
2463 what's in the argument list) */
2464 n += strlen(p);
2465 goto expand;
2466 }
2467 } else
2468 n++;
2469 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002470 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002473 we don't have to resize the string.
2474 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002475 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002476 if (!string)
2477 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 kind = PyUnicode_KIND(string);
2479 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002480 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002481 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002482
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002484 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002485 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002486
2487 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002488 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2489 /* checking for == because the last argument could be a empty
2490 string, which causes i to point to end, the assert at the end of
2491 the loop */
2492 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002493
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 switch (*f) {
2495 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002496 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002497 const int ordinal = va_arg(vargs, int);
2498 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002499 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002500 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002501 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002502 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002503 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002504 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002505 case 'p':
2506 /* unused, since we already have the result */
2507 if (*f == 'p')
2508 (void) va_arg(vargs, void *);
2509 else
2510 (void) va_arg(vargs, int);
2511 /* extract the result from numberresults and append. */
2512 for (; *numberresult; ++i, ++numberresult)
2513 PyUnicode_WRITE(kind, data, i, *numberresult);
2514 /* skip over the separating '\0' */
2515 assert(*numberresult == '\0');
2516 numberresult++;
2517 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002518 break;
2519 case 's':
2520 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002521 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002523 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002524 size = PyUnicode_GET_LENGTH(*callresult);
2525 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002526 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002527 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002528 /* We're done with the unicode()/repr() => forget it */
2529 Py_DECREF(*callresult);
2530 /* switch to next unicode()/repr() result */
2531 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002532 break;
2533 }
2534 case 'U':
2535 {
2536 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002537 Py_ssize_t size;
2538 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2539 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002540 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002541 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002542 break;
2543 }
2544 case 'V':
2545 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002546 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002547 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002548 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002549 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002550 size = PyUnicode_GET_LENGTH(obj);
2551 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002552 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002554 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002555 size = PyUnicode_GET_LENGTH(*callresult);
2556 assert(PyUnicode_KIND(*callresult) <=
2557 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002558 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002560 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002561 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002562 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002563 break;
2564 }
2565 case 'S':
2566 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002567 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002568 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002569 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002570 /* unused, since we already have the result */
2571 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002572 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002573 copy_characters(string, i, *callresult, 0, size);
2574 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 /* We're done with the unicode()/repr() => forget it */
2576 Py_DECREF(*callresult);
2577 /* switch to next unicode()/repr() result */
2578 ++callresult;
2579 break;
2580 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002581 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002583 break;
2584 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002585 for (; *p; ++p, ++i)
2586 PyUnicode_WRITE(kind, data, i, *p);
2587 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002588 goto end;
2589 }
Victor Stinner1205f272010-09-11 00:54:47 +00002590 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 else {
2592 assert(i < PyUnicode_GET_LENGTH(string));
2593 PyUnicode_WRITE(kind, data, i++, *f);
2594 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002597
Benjamin Peterson29060642009-01-31 22:14:21 +00002598 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002599 if (callresults)
2600 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 if (numberresults)
2602 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002603 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002604 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002605 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002606 if (callresults) {
2607 PyObject **callresult2 = callresults;
2608 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002609 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002610 ++callresult2;
2611 }
2612 PyObject_Free(callresults);
2613 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002614 if (numberresults)
2615 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002616 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002617}
2618
Walter Dörwaldd2034312007-05-18 16:29:38 +00002619PyObject *
2620PyUnicode_FromFormat(const char *format, ...)
2621{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 PyObject* ret;
2623 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002624
2625#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002626 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002627#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002628 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002629#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002630 ret = PyUnicode_FromFormatV(format, vargs);
2631 va_end(vargs);
2632 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002633}
2634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002635#ifdef HAVE_WCHAR_H
2636
Victor Stinner5593d8a2010-10-02 11:11:27 +00002637/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2638 convert a Unicode object to a wide character string.
2639
Victor Stinnerd88d9832011-09-06 02:00:05 +02002640 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002641 character) required to convert the unicode object. Ignore size argument.
2642
Victor Stinnerd88d9832011-09-06 02:00:05 +02002643 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002644 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002645 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002646static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002647unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002648 wchar_t *w,
2649 Py_ssize_t size)
2650{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002651 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 const wchar_t *wstr;
2653
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002654 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 if (wstr == NULL)
2656 return -1;
2657
Victor Stinner5593d8a2010-10-02 11:11:27 +00002658 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002659 if (size > res)
2660 size = res + 1;
2661 else
2662 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002663 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002664 return res;
2665 }
2666 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002667 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002668}
2669
2670Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002671PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002672 wchar_t *w,
2673 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002674{
2675 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002676 PyErr_BadInternalCall();
2677 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002678 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002679 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002680}
2681
Victor Stinner137c34c2010-09-29 10:25:54 +00002682wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002683PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002684 Py_ssize_t *size)
2685{
2686 wchar_t* buffer;
2687 Py_ssize_t buflen;
2688
2689 if (unicode == NULL) {
2690 PyErr_BadInternalCall();
2691 return NULL;
2692 }
2693
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002694 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002695 if (buflen == -1)
2696 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002697 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002698 PyErr_NoMemory();
2699 return NULL;
2700 }
2701
Victor Stinner137c34c2010-09-29 10:25:54 +00002702 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2703 if (buffer == NULL) {
2704 PyErr_NoMemory();
2705 return NULL;
2706 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002707 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002708 if (buflen == -1)
2709 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002710 if (size != NULL)
2711 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002712 return buffer;
2713}
2714
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002715#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002716
Alexander Belopolsky40018472011-02-26 01:02:56 +00002717PyObject *
2718PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002719{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002721 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002722 PyErr_SetString(PyExc_ValueError,
2723 "chr() arg not in range(0x110000)");
2724 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002725 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002727 if (ordinal < 256)
2728 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002730 v = PyUnicode_New(1, ordinal);
2731 if (v == NULL)
2732 return NULL;
2733 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002734 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002736}
2737
Alexander Belopolsky40018472011-02-26 01:02:56 +00002738PyObject *
2739PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002740{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002741 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002742 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002743 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002744 if (PyUnicode_READY(obj))
2745 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002746 Py_INCREF(obj);
2747 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002748 }
2749 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002750 /* For a Unicode subtype that's not a Unicode object,
2751 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002752 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002753 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002754 PyErr_Format(PyExc_TypeError,
2755 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002756 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002757 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002758}
2759
Alexander Belopolsky40018472011-02-26 01:02:56 +00002760PyObject *
2761PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002762 const char *encoding,
2763 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002764{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002765 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002766 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002767
Guido van Rossumd57fd912000-03-10 22:53:23 +00002768 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002769 PyErr_BadInternalCall();
2770 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002771 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002772
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002773 /* Decoding bytes objects is the most common case and should be fast */
2774 if (PyBytes_Check(obj)) {
2775 if (PyBytes_GET_SIZE(obj) == 0) {
2776 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002777 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002778 }
2779 else {
2780 v = PyUnicode_Decode(
2781 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2782 encoding, errors);
2783 }
2784 return v;
2785 }
2786
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002787 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002788 PyErr_SetString(PyExc_TypeError,
2789 "decoding str is not supported");
2790 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002791 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002792
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002793 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2794 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2795 PyErr_Format(PyExc_TypeError,
2796 "coercing to str: need bytes, bytearray "
2797 "or buffer-like object, %.80s found",
2798 Py_TYPE(obj)->tp_name);
2799 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002800 }
Tim Petersced69f82003-09-16 20:30:58 +00002801
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002802 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002803 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002804 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002805 }
Tim Petersced69f82003-09-16 20:30:58 +00002806 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002807 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002808
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002809 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002810 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002811}
2812
Victor Stinner600d3be2010-06-10 12:00:55 +00002813/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002814 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2815 1 on success. */
2816static int
2817normalize_encoding(const char *encoding,
2818 char *lower,
2819 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002820{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002821 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002822 char *l;
2823 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002824
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002825 if (encoding == NULL) {
2826 strcpy(lower, "utf-8");
2827 return 1;
2828 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002829 e = encoding;
2830 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002831 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002832 while (*e) {
2833 if (l == l_end)
2834 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002835 if (Py_ISUPPER(*e)) {
2836 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002837 }
2838 else if (*e == '_') {
2839 *l++ = '-';
2840 e++;
2841 }
2842 else {
2843 *l++ = *e++;
2844 }
2845 }
2846 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002847 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002848}
2849
Alexander Belopolsky40018472011-02-26 01:02:56 +00002850PyObject *
2851PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002852 Py_ssize_t size,
2853 const char *encoding,
2854 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002855{
2856 PyObject *buffer = NULL, *unicode;
2857 Py_buffer info;
2858 char lower[11]; /* Enough for any encoding shortcut */
2859
Fred Drakee4315f52000-05-09 19:53:39 +00002860 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002861 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002862 if ((strcmp(lower, "utf-8") == 0) ||
2863 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002864 return PyUnicode_DecodeUTF8(s, size, errors);
2865 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002866 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002867 (strcmp(lower, "iso-8859-1") == 0))
2868 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002869#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002870 else if (strcmp(lower, "mbcs") == 0)
2871 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002872#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002873 else if (strcmp(lower, "ascii") == 0)
2874 return PyUnicode_DecodeASCII(s, size, errors);
2875 else if (strcmp(lower, "utf-16") == 0)
2876 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2877 else if (strcmp(lower, "utf-32") == 0)
2878 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2879 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002880
2881 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002882 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002883 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002884 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002885 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886 if (buffer == NULL)
2887 goto onError;
2888 unicode = PyCodec_Decode(buffer, encoding, errors);
2889 if (unicode == NULL)
2890 goto onError;
2891 if (!PyUnicode_Check(unicode)) {
2892 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002893 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002894 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002895 Py_DECREF(unicode);
2896 goto onError;
2897 }
2898 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002899#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002900 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002901 Py_DECREF(unicode);
2902 return NULL;
2903 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002904#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002905 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002906 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002907
Benjamin Peterson29060642009-01-31 22:14:21 +00002908 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002909 Py_XDECREF(buffer);
2910 return NULL;
2911}
2912
Alexander Belopolsky40018472011-02-26 01:02:56 +00002913PyObject *
2914PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002915 const char *encoding,
2916 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002917{
2918 PyObject *v;
2919
2920 if (!PyUnicode_Check(unicode)) {
2921 PyErr_BadArgument();
2922 goto onError;
2923 }
2924
2925 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002926 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002927
2928 /* Decode via the codec registry */
2929 v = PyCodec_Decode(unicode, encoding, errors);
2930 if (v == NULL)
2931 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002932 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002933 return v;
2934
Benjamin Peterson29060642009-01-31 22:14:21 +00002935 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002936 return NULL;
2937}
2938
Alexander Belopolsky40018472011-02-26 01:02:56 +00002939PyObject *
2940PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002941 const char *encoding,
2942 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002943{
2944 PyObject *v;
2945
2946 if (!PyUnicode_Check(unicode)) {
2947 PyErr_BadArgument();
2948 goto onError;
2949 }
2950
2951 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002952 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002953
2954 /* Decode via the codec registry */
2955 v = PyCodec_Decode(unicode, encoding, errors);
2956 if (v == NULL)
2957 goto onError;
2958 if (!PyUnicode_Check(v)) {
2959 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002960 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002961 Py_TYPE(v)->tp_name);
2962 Py_DECREF(v);
2963 goto onError;
2964 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002965 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002966 return v;
2967
Benjamin Peterson29060642009-01-31 22:14:21 +00002968 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002969 return NULL;
2970}
2971
Alexander Belopolsky40018472011-02-26 01:02:56 +00002972PyObject *
2973PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002974 Py_ssize_t size,
2975 const char *encoding,
2976 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002977{
2978 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002979
Guido van Rossumd57fd912000-03-10 22:53:23 +00002980 unicode = PyUnicode_FromUnicode(s, size);
2981 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002982 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002983 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2984 Py_DECREF(unicode);
2985 return v;
2986}
2987
Alexander Belopolsky40018472011-02-26 01:02:56 +00002988PyObject *
2989PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002990 const char *encoding,
2991 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002992{
2993 PyObject *v;
2994
2995 if (!PyUnicode_Check(unicode)) {
2996 PyErr_BadArgument();
2997 goto onError;
2998 }
2999
3000 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003001 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003002
3003 /* Encode via the codec registry */
3004 v = PyCodec_Encode(unicode, encoding, errors);
3005 if (v == NULL)
3006 goto onError;
3007 return v;
3008
Benjamin Peterson29060642009-01-31 22:14:21 +00003009 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003010 return NULL;
3011}
3012
Victor Stinnerad158722010-10-27 00:25:46 +00003013PyObject *
3014PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003015{
Victor Stinner99b95382011-07-04 14:23:54 +02003016#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003017 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3018 PyUnicode_GET_SIZE(unicode),
3019 NULL);
3020#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003021 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003022#else
Victor Stinner793b5312011-04-27 00:24:21 +02003023 PyInterpreterState *interp = PyThreadState_GET()->interp;
3024 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3025 cannot use it to encode and decode filenames before it is loaded. Load
3026 the Python codec requires to encode at least its own filename. Use the C
3027 version of the locale codec until the codec registry is initialized and
3028 the Python codec is loaded.
3029
3030 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3031 cannot only rely on it: check also interp->fscodec_initialized for
3032 subinterpreters. */
3033 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003034 return PyUnicode_AsEncodedString(unicode,
3035 Py_FileSystemDefaultEncoding,
3036 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003037 }
3038 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003039 /* locale encoding with surrogateescape */
3040 wchar_t *wchar;
3041 char *bytes;
3042 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003043 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003044
3045 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3046 if (wchar == NULL)
3047 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003048 bytes = _Py_wchar2char(wchar, &error_pos);
3049 if (bytes == NULL) {
3050 if (error_pos != (size_t)-1) {
3051 char *errmsg = strerror(errno);
3052 PyObject *exc = NULL;
3053 if (errmsg == NULL)
3054 errmsg = "Py_wchar2char() failed";
3055 raise_encode_exception(&exc,
3056 "filesystemencoding",
3057 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3058 error_pos, error_pos+1,
3059 errmsg);
3060 Py_XDECREF(exc);
3061 }
3062 else
3063 PyErr_NoMemory();
3064 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003065 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003066 }
3067 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003068
3069 bytes_obj = PyBytes_FromString(bytes);
3070 PyMem_Free(bytes);
3071 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003072 }
Victor Stinnerad158722010-10-27 00:25:46 +00003073#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003074}
3075
Alexander Belopolsky40018472011-02-26 01:02:56 +00003076PyObject *
3077PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003078 const char *encoding,
3079 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003080{
3081 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003082 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003083
Guido van Rossumd57fd912000-03-10 22:53:23 +00003084 if (!PyUnicode_Check(unicode)) {
3085 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003086 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003087 }
Fred Drakee4315f52000-05-09 19:53:39 +00003088
Fred Drakee4315f52000-05-09 19:53:39 +00003089 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003090 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003091 if ((strcmp(lower, "utf-8") == 0) ||
3092 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003093 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003094 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003095 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003096 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003097 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003098 }
Victor Stinner37296e82010-06-10 13:36:23 +00003099 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003100 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003101 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003102 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003103#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003104 else if (strcmp(lower, "mbcs") == 0)
3105 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3106 PyUnicode_GET_SIZE(unicode),
3107 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003108#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003109 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003110 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003111 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003112
3113 /* Encode via the codec registry */
3114 v = PyCodec_Encode(unicode, encoding, errors);
3115 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003116 return NULL;
3117
3118 /* The normal path */
3119 if (PyBytes_Check(v))
3120 return v;
3121
3122 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003123 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003124 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003125 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003126
3127 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3128 "encoder %s returned bytearray instead of bytes",
3129 encoding);
3130 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003131 Py_DECREF(v);
3132 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003133 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003134
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003135 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3136 Py_DECREF(v);
3137 return b;
3138 }
3139
3140 PyErr_Format(PyExc_TypeError,
3141 "encoder did not return a bytes object (type=%.400s)",
3142 Py_TYPE(v)->tp_name);
3143 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003144 return NULL;
3145}
3146
Alexander Belopolsky40018472011-02-26 01:02:56 +00003147PyObject *
3148PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003149 const char *encoding,
3150 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003151{
3152 PyObject *v;
3153
3154 if (!PyUnicode_Check(unicode)) {
3155 PyErr_BadArgument();
3156 goto onError;
3157 }
3158
3159 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003160 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003161
3162 /* Encode via the codec registry */
3163 v = PyCodec_Encode(unicode, encoding, errors);
3164 if (v == NULL)
3165 goto onError;
3166 if (!PyUnicode_Check(v)) {
3167 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003168 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003169 Py_TYPE(v)->tp_name);
3170 Py_DECREF(v);
3171 goto onError;
3172 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003173 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003174
Benjamin Peterson29060642009-01-31 22:14:21 +00003175 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003176 return NULL;
3177}
3178
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003179PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003180PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003181 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003182 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3183}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003184
Christian Heimes5894ba72007-11-04 11:43:14 +00003185PyObject*
3186PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3187{
Victor Stinner99b95382011-07-04 14:23:54 +02003188#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003189 return PyUnicode_DecodeMBCS(s, size, NULL);
3190#elif defined(__APPLE__)
3191 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3192#else
Victor Stinner793b5312011-04-27 00:24:21 +02003193 PyInterpreterState *interp = PyThreadState_GET()->interp;
3194 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3195 cannot use it to encode and decode filenames before it is loaded. Load
3196 the Python codec requires to encode at least its own filename. Use the C
3197 version of the locale codec until the codec registry is initialized and
3198 the Python codec is loaded.
3199
3200 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3201 cannot only rely on it: check also interp->fscodec_initialized for
3202 subinterpreters. */
3203 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003204 return PyUnicode_Decode(s, size,
3205 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003206 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003207 }
3208 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003209 /* locale encoding with surrogateescape */
3210 wchar_t *wchar;
3211 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003212 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003213
3214 if (s[size] != '\0' || size != strlen(s)) {
3215 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3216 return NULL;
3217 }
3218
Victor Stinner168e1172010-10-16 23:16:16 +00003219 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003220 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003221 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003222
Victor Stinner168e1172010-10-16 23:16:16 +00003223 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003224 PyMem_Free(wchar);
3225 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003226 }
Victor Stinnerad158722010-10-27 00:25:46 +00003227#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003228}
3229
Martin v. Löwis011e8422009-05-05 04:43:17 +00003230
3231int
3232PyUnicode_FSConverter(PyObject* arg, void* addr)
3233{
3234 PyObject *output = NULL;
3235 Py_ssize_t size;
3236 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003237 if (arg == NULL) {
3238 Py_DECREF(*(PyObject**)addr);
3239 return 1;
3240 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003241 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003242 output = arg;
3243 Py_INCREF(output);
3244 }
3245 else {
3246 arg = PyUnicode_FromObject(arg);
3247 if (!arg)
3248 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003249 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003250 Py_DECREF(arg);
3251 if (!output)
3252 return 0;
3253 if (!PyBytes_Check(output)) {
3254 Py_DECREF(output);
3255 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3256 return 0;
3257 }
3258 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003259 size = PyBytes_GET_SIZE(output);
3260 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003261 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003262 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003263 Py_DECREF(output);
3264 return 0;
3265 }
3266 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003267 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003268}
3269
3270
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003271int
3272PyUnicode_FSDecoder(PyObject* arg, void* addr)
3273{
3274 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003275 if (arg == NULL) {
3276 Py_DECREF(*(PyObject**)addr);
3277 return 1;
3278 }
3279 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003280 if (PyUnicode_READY(arg))
3281 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003282 output = arg;
3283 Py_INCREF(output);
3284 }
3285 else {
3286 arg = PyBytes_FromObject(arg);
3287 if (!arg)
3288 return 0;
3289 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3290 PyBytes_GET_SIZE(arg));
3291 Py_DECREF(arg);
3292 if (!output)
3293 return 0;
3294 if (!PyUnicode_Check(output)) {
3295 Py_DECREF(output);
3296 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3297 return 0;
3298 }
3299 }
Victor Stinner065836e2011-10-27 01:56:33 +02003300 if (PyUnicode_READY(output) < 0) {
3301 Py_DECREF(output);
3302 return 0;
3303 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003304 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003305 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003306 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3307 Py_DECREF(output);
3308 return 0;
3309 }
3310 *(PyObject**)addr = output;
3311 return Py_CLEANUP_SUPPORTED;
3312}
3313
3314
Martin v. Löwis5b222132007-06-10 09:51:05 +00003315char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003316PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003317{
Christian Heimesf3863112007-11-22 07:46:41 +00003318 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003319
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003320 if (!PyUnicode_Check(unicode)) {
3321 PyErr_BadArgument();
3322 return NULL;
3323 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003324 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003325 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003326
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003327 if (PyUnicode_UTF8(unicode) == NULL) {
3328 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003329 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3330 if (bytes == NULL)
3331 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003332 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3333 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003334 Py_DECREF(bytes);
3335 return NULL;
3336 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003337 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3338 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3339 PyBytes_AS_STRING(bytes),
3340 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 Py_DECREF(bytes);
3342 }
3343
3344 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003345 *psize = PyUnicode_UTF8_LENGTH(unicode);
3346 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003347}
3348
3349char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003350PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3353}
3354
3355#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003356static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003357#endif
3358
3359
3360Py_UNICODE *
3361PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3362{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003363 const unsigned char *one_byte;
3364#if SIZEOF_WCHAR_T == 4
3365 const Py_UCS2 *two_bytes;
3366#else
3367 const Py_UCS4 *four_bytes;
3368 const Py_UCS4 *ucs4_end;
3369 Py_ssize_t num_surrogates;
3370#endif
3371 wchar_t *w;
3372 wchar_t *wchar_end;
3373
3374 if (!PyUnicode_Check(unicode)) {
3375 PyErr_BadArgument();
3376 return NULL;
3377 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003378 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003379 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003380 assert(_PyUnicode_KIND(unicode) != 0);
3381 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003382
3383#ifdef Py_DEBUG
3384 ++unicode_as_unicode_calls;
3385#endif
3386
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003387 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003389 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3390 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003391 num_surrogates = 0;
3392
3393 for (; four_bytes < ucs4_end; ++four_bytes) {
3394 if (*four_bytes > 0xFFFF)
3395 ++num_surrogates;
3396 }
3397
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003398 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3399 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3400 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003401 PyErr_NoMemory();
3402 return NULL;
3403 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003404 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003405
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003406 w = _PyUnicode_WSTR(unicode);
3407 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3408 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003409 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3410 if (*four_bytes > 0xFFFF) {
3411 /* encode surrogate pair in this case */
3412 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3413 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3414 }
3415 else
3416 *w = *four_bytes;
3417
3418 if (w > wchar_end) {
3419 assert(0 && "Miscalculated string end");
3420 }
3421 }
3422 *w = 0;
3423#else
3424 /* sizeof(wchar_t) == 4 */
3425 Py_FatalError("Impossible unicode object state, wstr and str "
3426 "should share memory already.");
3427 return NULL;
3428#endif
3429 }
3430 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003431 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3432 (_PyUnicode_LENGTH(unicode) + 1));
3433 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003434 PyErr_NoMemory();
3435 return NULL;
3436 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003437 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3438 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3439 w = _PyUnicode_WSTR(unicode);
3440 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003441
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3443 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003444 for (; w < wchar_end; ++one_byte, ++w)
3445 *w = *one_byte;
3446 /* null-terminate the wstr */
3447 *w = 0;
3448 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003449 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003450#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003451 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003452 for (; w < wchar_end; ++two_bytes, ++w)
3453 *w = *two_bytes;
3454 /* null-terminate the wstr */
3455 *w = 0;
3456#else
3457 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003458 PyObject_FREE(_PyUnicode_WSTR(unicode));
3459 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003460 Py_FatalError("Impossible unicode object state, wstr "
3461 "and str should share memory already.");
3462 return NULL;
3463#endif
3464 }
3465 else {
3466 assert(0 && "This should never happen.");
3467 }
3468 }
3469 }
3470 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003471 *size = PyUnicode_WSTR_LENGTH(unicode);
3472 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003473}
3474
Alexander Belopolsky40018472011-02-26 01:02:56 +00003475Py_UNICODE *
3476PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003477{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003478 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003479}
3480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003481
Alexander Belopolsky40018472011-02-26 01:02:56 +00003482Py_ssize_t
3483PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003484{
3485 if (!PyUnicode_Check(unicode)) {
3486 PyErr_BadArgument();
3487 goto onError;
3488 }
3489 return PyUnicode_GET_SIZE(unicode);
3490
Benjamin Peterson29060642009-01-31 22:14:21 +00003491 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003492 return -1;
3493}
3494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003495Py_ssize_t
3496PyUnicode_GetLength(PyObject *unicode)
3497{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003498 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003499 PyErr_BadArgument();
3500 return -1;
3501 }
3502
3503 return PyUnicode_GET_LENGTH(unicode);
3504}
3505
3506Py_UCS4
3507PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3508{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003509 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3510 PyErr_BadArgument();
3511 return (Py_UCS4)-1;
3512 }
3513 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3514 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003515 return (Py_UCS4)-1;
3516 }
3517 return PyUnicode_READ_CHAR(unicode, index);
3518}
3519
3520int
3521PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3522{
3523 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003524 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003525 return -1;
3526 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003527 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3528 PyErr_SetString(PyExc_IndexError, "string index out of range");
3529 return -1;
3530 }
3531 if (_PyUnicode_Dirty(unicode))
3532 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003533 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3534 index, ch);
3535 return 0;
3536}
3537
Alexander Belopolsky40018472011-02-26 01:02:56 +00003538const char *
3539PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003540{
Victor Stinner42cb4622010-09-01 19:39:01 +00003541 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003542}
3543
Victor Stinner554f3f02010-06-16 23:33:54 +00003544/* create or adjust a UnicodeDecodeError */
3545static void
3546make_decode_exception(PyObject **exceptionObject,
3547 const char *encoding,
3548 const char *input, Py_ssize_t length,
3549 Py_ssize_t startpos, Py_ssize_t endpos,
3550 const char *reason)
3551{
3552 if (*exceptionObject == NULL) {
3553 *exceptionObject = PyUnicodeDecodeError_Create(
3554 encoding, input, length, startpos, endpos, reason);
3555 }
3556 else {
3557 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3558 goto onError;
3559 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3560 goto onError;
3561 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3562 goto onError;
3563 }
3564 return;
3565
3566onError:
3567 Py_DECREF(*exceptionObject);
3568 *exceptionObject = NULL;
3569}
3570
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003571/* error handling callback helper:
3572 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003573 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003574 and adjust various state variables.
3575 return 0 on success, -1 on error
3576*/
3577
Alexander Belopolsky40018472011-02-26 01:02:56 +00003578static int
3579unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003580 const char *encoding, const char *reason,
3581 const char **input, const char **inend, Py_ssize_t *startinpos,
3582 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3583 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003584{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003585 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003586
3587 PyObject *restuple = NULL;
3588 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003589 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003590 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003591 Py_ssize_t requiredsize;
3592 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003593 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003594 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003595 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003596 int res = -1;
3597
3598 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003599 *errorHandler = PyCodec_LookupError(errors);
3600 if (*errorHandler == NULL)
3601 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003602 }
3603
Victor Stinner554f3f02010-06-16 23:33:54 +00003604 make_decode_exception(exceptionObject,
3605 encoding,
3606 *input, *inend - *input,
3607 *startinpos, *endinpos,
3608 reason);
3609 if (*exceptionObject == NULL)
3610 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003611
3612 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3613 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003614 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003615 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003616 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003617 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003618 }
3619 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003620 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003621
3622 /* Copy back the bytes variables, which might have been modified by the
3623 callback */
3624 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3625 if (!inputobj)
3626 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003627 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003628 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003629 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003630 *input = PyBytes_AS_STRING(inputobj);
3631 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003632 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003633 /* we can DECREF safely, as the exception has another reference,
3634 so the object won't go away. */
3635 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003638 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003639 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003640 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3641 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003642 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643
3644 /* need more space? (at least enough for what we
3645 have+the replacement+the rest of the string (starting
3646 at the new input position), so we won't have to check space
3647 when there are no errors in the rest of the string) */
3648 repptr = PyUnicode_AS_UNICODE(repunicode);
3649 repsize = PyUnicode_GET_SIZE(repunicode);
3650 requiredsize = *outpos + repsize + insize-newpos;
3651 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003652 if (requiredsize<2*outsize)
3653 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003654 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003655 goto onError;
3656 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003657 }
3658 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003659 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003660 Py_UNICODE_COPY(*outptr, repptr, repsize);
3661 *outptr += repsize;
3662 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003663
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003664 /* we made it! */
3665 res = 0;
3666
Benjamin Peterson29060642009-01-31 22:14:21 +00003667 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003668 Py_XDECREF(restuple);
3669 return res;
3670}
3671
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003672/* --- UTF-7 Codec -------------------------------------------------------- */
3673
Antoine Pitrou244651a2009-05-04 18:56:13 +00003674/* See RFC2152 for details. We encode conservatively and decode liberally. */
3675
3676/* Three simple macros defining base-64. */
3677
3678/* Is c a base-64 character? */
3679
3680#define IS_BASE64(c) \
3681 (((c) >= 'A' && (c) <= 'Z') || \
3682 ((c) >= 'a' && (c) <= 'z') || \
3683 ((c) >= '0' && (c) <= '9') || \
3684 (c) == '+' || (c) == '/')
3685
3686/* given that c is a base-64 character, what is its base-64 value? */
3687
3688#define FROM_BASE64(c) \
3689 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3690 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3691 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3692 (c) == '+' ? 62 : 63)
3693
3694/* What is the base-64 character of the bottom 6 bits of n? */
3695
3696#define TO_BASE64(n) \
3697 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3698
3699/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3700 * decoded as itself. We are permissive on decoding; the only ASCII
3701 * byte not decoding to itself is the + which begins a base64
3702 * string. */
3703
3704#define DECODE_DIRECT(c) \
3705 ((c) <= 127 && (c) != '+')
3706
3707/* The UTF-7 encoder treats ASCII characters differently according to
3708 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3709 * the above). See RFC2152. This array identifies these different
3710 * sets:
3711 * 0 : "Set D"
3712 * alphanumeric and '(),-./:?
3713 * 1 : "Set O"
3714 * !"#$%&*;<=>@[]^_`{|}
3715 * 2 : "whitespace"
3716 * ht nl cr sp
3717 * 3 : special (must be base64 encoded)
3718 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3719 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003720
Tim Petersced69f82003-09-16 20:30:58 +00003721static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003722char utf7_category[128] = {
3723/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3724 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3725/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3726 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3727/* sp ! " # $ % & ' ( ) * + , - . / */
3728 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3729/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3730 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3731/* @ A B C D E F G H I J K L M N O */
3732 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3733/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3734 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3735/* ` a b c d e f g h i j k l m n o */
3736 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3737/* p q r s t u v w x y z { | } ~ del */
3738 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003739};
3740
Antoine Pitrou244651a2009-05-04 18:56:13 +00003741/* ENCODE_DIRECT: this character should be encoded as itself. The
3742 * answer depends on whether we are encoding set O as itself, and also
3743 * on whether we are encoding whitespace as itself. RFC2152 makes it
3744 * clear that the answers to these questions vary between
3745 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003746
Antoine Pitrou244651a2009-05-04 18:56:13 +00003747#define ENCODE_DIRECT(c, directO, directWS) \
3748 ((c) < 128 && (c) > 0 && \
3749 ((utf7_category[(c)] == 0) || \
3750 (directWS && (utf7_category[(c)] == 2)) || \
3751 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003752
Alexander Belopolsky40018472011-02-26 01:02:56 +00003753PyObject *
3754PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003755 Py_ssize_t size,
3756 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003757{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003758 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3759}
3760
Antoine Pitrou244651a2009-05-04 18:56:13 +00003761/* The decoder. The only state we preserve is our read position,
3762 * i.e. how many characters we have consumed. So if we end in the
3763 * middle of a shift sequence we have to back off the read position
3764 * and the output to the beginning of the sequence, otherwise we lose
3765 * all the shift state (seen bits, number of bits seen, high
3766 * surrogate). */
3767
Alexander Belopolsky40018472011-02-26 01:02:56 +00003768PyObject *
3769PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003770 Py_ssize_t size,
3771 const char *errors,
3772 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003773{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003774 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003775 Py_ssize_t startinpos;
3776 Py_ssize_t endinpos;
3777 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003778 const char *e;
3779 PyUnicodeObject *unicode;
3780 Py_UNICODE *p;
3781 const char *errmsg = "";
3782 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003783 Py_UNICODE *shiftOutStart;
3784 unsigned int base64bits = 0;
3785 unsigned long base64buffer = 0;
3786 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003787 PyObject *errorHandler = NULL;
3788 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003789
3790 unicode = _PyUnicode_New(size);
3791 if (!unicode)
3792 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003793 if (size == 0) {
3794 if (consumed)
3795 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003796 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003797 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003798
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003799 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003800 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003801 e = s + size;
3802
3803 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003804 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003805 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003806 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003807
Antoine Pitrou244651a2009-05-04 18:56:13 +00003808 if (inShift) { /* in a base-64 section */
3809 if (IS_BASE64(ch)) { /* consume a base-64 character */
3810 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3811 base64bits += 6;
3812 s++;
3813 if (base64bits >= 16) {
3814 /* we have enough bits for a UTF-16 value */
3815 Py_UNICODE outCh = (Py_UNICODE)
3816 (base64buffer >> (base64bits-16));
3817 base64bits -= 16;
3818 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3819 if (surrogate) {
3820 /* expecting a second surrogate */
3821 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3822#ifdef Py_UNICODE_WIDE
3823 *p++ = (((surrogate & 0x3FF)<<10)
3824 | (outCh & 0x3FF)) + 0x10000;
3825#else
3826 *p++ = surrogate;
3827 *p++ = outCh;
3828#endif
3829 surrogate = 0;
3830 }
3831 else {
3832 surrogate = 0;
3833 errmsg = "second surrogate missing";
3834 goto utf7Error;
3835 }
3836 }
3837 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3838 /* first surrogate */
3839 surrogate = outCh;
3840 }
3841 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3842 errmsg = "unexpected second surrogate";
3843 goto utf7Error;
3844 }
3845 else {
3846 *p++ = outCh;
3847 }
3848 }
3849 }
3850 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003851 inShift = 0;
3852 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003853 if (surrogate) {
3854 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003855 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003856 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003857 if (base64bits > 0) { /* left-over bits */
3858 if (base64bits >= 6) {
3859 /* We've seen at least one base-64 character */
3860 errmsg = "partial character in shift sequence";
3861 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003863 else {
3864 /* Some bits remain; they should be zero */
3865 if (base64buffer != 0) {
3866 errmsg = "non-zero padding bits in shift sequence";
3867 goto utf7Error;
3868 }
3869 }
3870 }
3871 if (ch != '-') {
3872 /* '-' is absorbed; other terminating
3873 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003874 *p++ = ch;
3875 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003876 }
3877 }
3878 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003879 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003880 s++; /* consume '+' */
3881 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003882 s++;
3883 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003884 }
3885 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003886 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003887 shiftOutStart = p;
3888 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003889 }
3890 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003891 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003892 *p++ = ch;
3893 s++;
3894 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003895 else {
3896 startinpos = s-starts;
3897 s++;
3898 errmsg = "unexpected special character";
3899 goto utf7Error;
3900 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003901 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003902utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003903 outpos = p-PyUnicode_AS_UNICODE(unicode);
3904 endinpos = s-starts;
3905 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003906 errors, &errorHandler,
3907 "utf7", errmsg,
3908 &starts, &e, &startinpos, &endinpos, &exc, &s,
3909 &unicode, &outpos, &p))
3910 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003911 }
3912
Antoine Pitrou244651a2009-05-04 18:56:13 +00003913 /* end of string */
3914
3915 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3916 /* if we're in an inconsistent state, that's an error */
3917 if (surrogate ||
3918 (base64bits >= 6) ||
3919 (base64bits > 0 && base64buffer != 0)) {
3920 outpos = p-PyUnicode_AS_UNICODE(unicode);
3921 endinpos = size;
3922 if (unicode_decode_call_errorhandler(
3923 errors, &errorHandler,
3924 "utf7", "unterminated shift sequence",
3925 &starts, &e, &startinpos, &endinpos, &exc, &s,
3926 &unicode, &outpos, &p))
3927 goto onError;
3928 if (s < e)
3929 goto restart;
3930 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003931 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003932
3933 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003934 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003935 if (inShift) {
3936 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003937 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938 }
3939 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003940 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003941 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003942 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003943
Victor Stinnerfe226c02011-10-03 03:52:20 +02003944 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003945 goto onError;
3946
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003947 Py_XDECREF(errorHandler);
3948 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003949#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003950 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003951 Py_DECREF(unicode);
3952 return NULL;
3953 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003954#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003955 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003956 return (PyObject *)unicode;
3957
Benjamin Peterson29060642009-01-31 22:14:21 +00003958 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003959 Py_XDECREF(errorHandler);
3960 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003961 Py_DECREF(unicode);
3962 return NULL;
3963}
3964
3965
Alexander Belopolsky40018472011-02-26 01:02:56 +00003966PyObject *
3967PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003968 Py_ssize_t size,
3969 int base64SetO,
3970 int base64WhiteSpace,
3971 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003972{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003973 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003974 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003975 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003976 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003977 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003978 unsigned int base64bits = 0;
3979 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003980 char * out;
3981 char * start;
3982
3983 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003984 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003985
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003986 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003987 return PyErr_NoMemory();
3988
Antoine Pitrou244651a2009-05-04 18:56:13 +00003989 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003990 if (v == NULL)
3991 return NULL;
3992
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003993 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003994 for (;i < size; ++i) {
3995 Py_UNICODE ch = s[i];
3996
Antoine Pitrou244651a2009-05-04 18:56:13 +00003997 if (inShift) {
3998 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3999 /* shifting out */
4000 if (base64bits) { /* output remaining bits */
4001 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4002 base64buffer = 0;
4003 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004004 }
4005 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004006 /* Characters not in the BASE64 set implicitly unshift the sequence
4007 so no '-' is required, except if the character is itself a '-' */
4008 if (IS_BASE64(ch) || ch == '-') {
4009 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004010 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004011 *out++ = (char) ch;
4012 }
4013 else {
4014 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004015 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004016 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004017 else { /* not in a shift sequence */
4018 if (ch == '+') {
4019 *out++ = '+';
4020 *out++ = '-';
4021 }
4022 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4023 *out++ = (char) ch;
4024 }
4025 else {
4026 *out++ = '+';
4027 inShift = 1;
4028 goto encode_char;
4029 }
4030 }
4031 continue;
4032encode_char:
4033#ifdef Py_UNICODE_WIDE
4034 if (ch >= 0x10000) {
4035 /* code first surrogate */
4036 base64bits += 16;
4037 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4038 while (base64bits >= 6) {
4039 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4040 base64bits -= 6;
4041 }
4042 /* prepare second surrogate */
4043 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4044 }
4045#endif
4046 base64bits += 16;
4047 base64buffer = (base64buffer << 16) | ch;
4048 while (base64bits >= 6) {
4049 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4050 base64bits -= 6;
4051 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004052 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004053 if (base64bits)
4054 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4055 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004056 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004057 if (_PyBytes_Resize(&v, out - start) < 0)
4058 return NULL;
4059 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004060}
4061
Antoine Pitrou244651a2009-05-04 18:56:13 +00004062#undef IS_BASE64
4063#undef FROM_BASE64
4064#undef TO_BASE64
4065#undef DECODE_DIRECT
4066#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004067
Guido van Rossumd57fd912000-03-10 22:53:23 +00004068/* --- UTF-8 Codec -------------------------------------------------------- */
4069
Tim Petersced69f82003-09-16 20:30:58 +00004070static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004071char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004072 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4073 illegal prefix. See RFC 3629 for details */
4074 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4075 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004076 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004077 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4078 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4079 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4082 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 +00004083 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4084 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004085 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4086 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4087 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4088 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4089 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 +00004090};
4091
Alexander Belopolsky40018472011-02-26 01:02:56 +00004092PyObject *
4093PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004094 Py_ssize_t size,
4095 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004096{
Walter Dörwald69652032004-09-07 20:24:22 +00004097 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4098}
4099
Antoine Pitrouab868312009-01-10 15:40:25 +00004100/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4101#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4102
4103/* Mask to quickly check whether a C 'long' contains a
4104 non-ASCII, UTF8-encoded char. */
4105#if (SIZEOF_LONG == 8)
4106# define ASCII_CHAR_MASK 0x8080808080808080L
4107#elif (SIZEOF_LONG == 4)
4108# define ASCII_CHAR_MASK 0x80808080L
4109#else
4110# error C 'long' size should be either 4 or 8!
4111#endif
4112
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004113/* Scans a UTF-8 string and returns the maximum character to be expected,
4114 the size of the decoded unicode string and if any major errors were
4115 encountered.
4116
4117 This function does check basic UTF-8 sanity, it does however NOT CHECK
4118 if the string contains surrogates, and if all continuation bytes are
4119 within the correct ranges, these checks are performed in
4120 PyUnicode_DecodeUTF8Stateful.
4121
4122 If it sets has_errors to 1, it means the value of unicode_size and max_char
4123 will be bogus and you should not rely on useful information in them.
4124 */
4125static Py_UCS4
4126utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4127 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4128 int *has_errors)
4129{
4130 Py_ssize_t n;
4131 Py_ssize_t char_count = 0;
4132 Py_UCS4 max_char = 127, new_max;
4133 Py_UCS4 upper_bound;
4134 const unsigned char *p = (const unsigned char *)s;
4135 const unsigned char *end = p + string_size;
4136 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4137 int err = 0;
4138
4139 for (; p < end && !err; ++p, ++char_count) {
4140 /* Only check value if it's not a ASCII char... */
4141 if (*p < 0x80) {
4142 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4143 an explanation. */
4144 if (!((size_t) p & LONG_PTR_MASK)) {
4145 /* Help register allocation */
4146 register const unsigned char *_p = p;
4147 while (_p < aligned_end) {
4148 unsigned long value = *(unsigned long *) _p;
4149 if (value & ASCII_CHAR_MASK)
4150 break;
4151 _p += SIZEOF_LONG;
4152 char_count += SIZEOF_LONG;
4153 }
4154 p = _p;
4155 if (p == end)
4156 break;
4157 }
4158 }
4159 if (*p >= 0x80) {
4160 n = utf8_code_length[*p];
4161 new_max = max_char;
4162 switch (n) {
4163 /* invalid start byte */
4164 case 0:
4165 err = 1;
4166 break;
4167 case 2:
4168 /* Code points between 0x00FF and 0x07FF inclusive.
4169 Approximate the upper bound of the code point,
4170 if this flips over 255 we can be sure it will be more
4171 than 255 and the string will need 2 bytes per code coint,
4172 if it stays under or equal to 255, we can be sure 1 byte
4173 is enough.
4174 ((*p & 0b00011111) << 6) | 0b00111111 */
4175 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4176 if (max_char < upper_bound)
4177 new_max = upper_bound;
4178 /* Ensure we track at least that we left ASCII space. */
4179 if (new_max < 128)
4180 new_max = 128;
4181 break;
4182 case 3:
4183 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4184 always > 255 and <= 65535 and will always need 2 bytes. */
4185 if (max_char < 65535)
4186 new_max = 65535;
4187 break;
4188 case 4:
4189 /* Code point will be above 0xFFFF for sure in this case. */
4190 new_max = 65537;
4191 break;
4192 /* Internal error, this should be caught by the first if */
4193 case 1:
4194 default:
4195 assert(0 && "Impossible case in utf8_max_char_and_size");
4196 err = 1;
4197 }
4198 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004199 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004200 --n;
4201 /* Check if the follow up chars are all valid continuation bytes */
4202 if (n >= 1) {
4203 const unsigned char *cont;
4204 if ((p + n) >= end) {
4205 if (consumed == 0)
4206 /* incomplete data, non-incremental decoding */
4207 err = 1;
4208 break;
4209 }
4210 for (cont = p + 1; cont < (p + n); ++cont) {
4211 if ((*cont & 0xc0) != 0x80) {
4212 err = 1;
4213 break;
4214 }
4215 }
4216 p += n;
4217 }
4218 else
4219 err = 1;
4220 max_char = new_max;
4221 }
4222 }
4223
4224 if (unicode_size)
4225 *unicode_size = char_count;
4226 if (has_errors)
4227 *has_errors = err;
4228 return max_char;
4229}
4230
4231/* Similar to PyUnicode_WRITE but can also write into wstr field
4232 of the legacy unicode representation */
4233#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4234 do { \
4235 const int k_ = (kind); \
4236 if (k_ == PyUnicode_WCHAR_KIND) \
4237 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4238 else if (k_ == PyUnicode_1BYTE_KIND) \
4239 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4240 else if (k_ == PyUnicode_2BYTE_KIND) \
4241 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4242 else \
4243 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4244 } while (0)
4245
Alexander Belopolsky40018472011-02-26 01:02:56 +00004246PyObject *
4247PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004248 Py_ssize_t size,
4249 const char *errors,
4250 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004251{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004252 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004253 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004254 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004255 Py_ssize_t startinpos;
4256 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004257 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004258 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004259 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004260 PyObject *errorHandler = NULL;
4261 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004262 Py_UCS4 maxchar = 0;
4263 Py_ssize_t unicode_size;
4264 Py_ssize_t i;
4265 int kind;
4266 void *data;
4267 int has_errors;
4268 Py_UNICODE *error_outptr;
4269#if SIZEOF_WCHAR_T == 2
4270 Py_ssize_t wchar_offset = 0;
4271#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004272
Walter Dörwald69652032004-09-07 20:24:22 +00004273 if (size == 0) {
4274 if (consumed)
4275 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004276 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004277 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004278 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4279 consumed, &has_errors);
4280 if (has_errors) {
4281 unicode = _PyUnicode_New(size);
4282 if (!unicode)
4283 return NULL;
4284 kind = PyUnicode_WCHAR_KIND;
4285 data = PyUnicode_AS_UNICODE(unicode);
4286 assert(data != NULL);
4287 }
4288 else {
4289 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4290 if (!unicode)
4291 return NULL;
4292 /* When the string is ASCII only, just use memcpy and return.
4293 unicode_size may be != size if there is an incomplete UTF-8
4294 sequence at the end of the ASCII block. */
4295 if (maxchar < 128 && size == unicode_size) {
4296 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4297 return (PyObject *)unicode;
4298 }
4299 kind = PyUnicode_KIND(unicode);
4300 data = PyUnicode_DATA(unicode);
4301 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004302 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004303 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004304 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004305 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004306
4307 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004308 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004309
4310 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004311 /* Fast path for runs of ASCII characters. Given that common UTF-8
4312 input will consist of an overwhelming majority of ASCII
4313 characters, we try to optimize for this case by checking
4314 as many characters as a C 'long' can contain.
4315 First, check if we can do an aligned read, as most CPUs have
4316 a penalty for unaligned reads.
4317 */
4318 if (!((size_t) s & LONG_PTR_MASK)) {
4319 /* Help register allocation */
4320 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004321 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004322 while (_s < aligned_end) {
4323 /* Read a whole long at a time (either 4 or 8 bytes),
4324 and do a fast unrolled copy if it only contains ASCII
4325 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004326 unsigned long value = *(unsigned long *) _s;
4327 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004328 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004329 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4330 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4331 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4332 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004333#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004334 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4335 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4336 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4337 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004338#endif
4339 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004340 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004341 }
4342 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004343 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004344 if (s == e)
4345 break;
4346 ch = (unsigned char)*s;
4347 }
4348 }
4349
4350 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004351 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004352 s++;
4353 continue;
4354 }
4355
4356 n = utf8_code_length[ch];
4357
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004358 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004359 if (consumed)
4360 break;
4361 else {
4362 errmsg = "unexpected end of data";
4363 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004364 endinpos = startinpos+1;
4365 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4366 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004367 goto utf8Error;
4368 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004369 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004370
4371 switch (n) {
4372
4373 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004374 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004375 startinpos = s-starts;
4376 endinpos = startinpos+1;
4377 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004378
4379 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004380 errmsg = "internal error";
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 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004386 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004387 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004388 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004389 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004390 goto utf8Error;
4391 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004392 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004393 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004394 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004395 break;
4396
4397 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004398 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4399 will result in surrogates in range d800-dfff. Surrogates are
4400 not valid UTF-8 so they are rejected.
4401 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4402 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004403 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004404 (s[2] & 0xc0) != 0x80 ||
4405 ((unsigned char)s[0] == 0xE0 &&
4406 (unsigned char)s[1] < 0xA0) ||
4407 ((unsigned char)s[0] == 0xED &&
4408 (unsigned char)s[1] > 0x9F)) {
4409 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004410 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004411 endinpos = startinpos + 1;
4412
4413 /* if s[1] first two bits are 1 and 0, then the invalid
4414 continuation byte is s[2], so increment endinpos by 1,
4415 if not, s[1] is invalid and endinpos doesn't need to
4416 be incremented. */
4417 if ((s[1] & 0xC0) == 0x80)
4418 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004419 goto utf8Error;
4420 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004421 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004422 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004423 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004424 break;
4425
4426 case 4:
4427 if ((s[1] & 0xc0) != 0x80 ||
4428 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004429 (s[3] & 0xc0) != 0x80 ||
4430 ((unsigned char)s[0] == 0xF0 &&
4431 (unsigned char)s[1] < 0x90) ||
4432 ((unsigned char)s[0] == 0xF4 &&
4433 (unsigned char)s[1] > 0x8F)) {
4434 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004435 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004436 endinpos = startinpos + 1;
4437 if ((s[1] & 0xC0) == 0x80) {
4438 endinpos++;
4439 if ((s[2] & 0xC0) == 0x80)
4440 endinpos++;
4441 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004442 goto utf8Error;
4443 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004444 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004445 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4446 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4447
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004448 /* If the string is flexible or we have native UCS-4, write
4449 directly.. */
4450 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4451 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004453 else {
4454 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004456 /* translate from 10000..10FFFF to 0..FFFF */
4457 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004459 /* high surrogate = top 10 bits added to D800 */
4460 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4461 (Py_UNICODE)(0xD800 + (ch >> 10)));
4462
4463 /* low surrogate = bottom 10 bits added to DC00 */
4464 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4465 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4466 }
4467#if SIZEOF_WCHAR_T == 2
4468 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004469#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004471 }
4472 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004473 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004474
Benjamin Peterson29060642009-01-31 22:14:21 +00004475 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004476 /* If this is not yet a resizable string, make it one.. */
4477 if (kind != PyUnicode_WCHAR_KIND) {
4478 const Py_UNICODE *u;
4479 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4480 if (!new_unicode)
4481 goto onError;
4482 u = PyUnicode_AsUnicode((PyObject *)unicode);
4483 if (!u)
4484 goto onError;
4485#if SIZEOF_WCHAR_T == 2
4486 i += wchar_offset;
4487#endif
4488 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4489 Py_DECREF(unicode);
4490 unicode = new_unicode;
4491 kind = 0;
4492 data = PyUnicode_AS_UNICODE(new_unicode);
4493 assert(data != NULL);
4494 }
4495 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004496 if (unicode_decode_call_errorhandler(
4497 errors, &errorHandler,
4498 "utf8", errmsg,
4499 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004500 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004502 /* Update data because unicode_decode_call_errorhandler might have
4503 re-created or resized the unicode object. */
4504 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004505 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004506 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507 /* Ensure the unicode_size calculation above was correct: */
4508 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4509
Walter Dörwald69652032004-09-07 20:24:22 +00004510 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004513 /* Adjust length and ready string when it contained errors and
4514 is of the old resizable kind. */
4515 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004516 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004517 goto onError;
4518 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004519
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004520 Py_XDECREF(errorHandler);
4521 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004522#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004523 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004524 Py_DECREF(unicode);
4525 return NULL;
4526 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004527#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004528 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529 return (PyObject *)unicode;
4530
Benjamin Peterson29060642009-01-31 22:14:21 +00004531 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004532 Py_XDECREF(errorHandler);
4533 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004534 Py_DECREF(unicode);
4535 return NULL;
4536}
4537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004538#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004539
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004540#ifdef __APPLE__
4541
4542/* Simplified UTF-8 decoder using surrogateescape error handler,
4543 used to decode the command line arguments on Mac OS X. */
4544
4545wchar_t*
4546_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4547{
4548 int n;
4549 const char *e;
4550 wchar_t *unicode, *p;
4551
4552 /* Note: size will always be longer than the resulting Unicode
4553 character count */
4554 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4555 PyErr_NoMemory();
4556 return NULL;
4557 }
4558 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4559 if (!unicode)
4560 return NULL;
4561
4562 /* Unpack UTF-8 encoded data */
4563 p = unicode;
4564 e = s + size;
4565 while (s < e) {
4566 Py_UCS4 ch = (unsigned char)*s;
4567
4568 if (ch < 0x80) {
4569 *p++ = (wchar_t)ch;
4570 s++;
4571 continue;
4572 }
4573
4574 n = utf8_code_length[ch];
4575 if (s + n > e) {
4576 goto surrogateescape;
4577 }
4578
4579 switch (n) {
4580 case 0:
4581 case 1:
4582 goto surrogateescape;
4583
4584 case 2:
4585 if ((s[1] & 0xc0) != 0x80)
4586 goto surrogateescape;
4587 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4588 assert ((ch > 0x007F) && (ch <= 0x07FF));
4589 *p++ = (wchar_t)ch;
4590 break;
4591
4592 case 3:
4593 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4594 will result in surrogates in range d800-dfff. Surrogates are
4595 not valid UTF-8 so they are rejected.
4596 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4597 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4598 if ((s[1] & 0xc0) != 0x80 ||
4599 (s[2] & 0xc0) != 0x80 ||
4600 ((unsigned char)s[0] == 0xE0 &&
4601 (unsigned char)s[1] < 0xA0) ||
4602 ((unsigned char)s[0] == 0xED &&
4603 (unsigned char)s[1] > 0x9F)) {
4604
4605 goto surrogateescape;
4606 }
4607 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4608 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004609 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004610 break;
4611
4612 case 4:
4613 if ((s[1] & 0xc0) != 0x80 ||
4614 (s[2] & 0xc0) != 0x80 ||
4615 (s[3] & 0xc0) != 0x80 ||
4616 ((unsigned char)s[0] == 0xF0 &&
4617 (unsigned char)s[1] < 0x90) ||
4618 ((unsigned char)s[0] == 0xF4 &&
4619 (unsigned char)s[1] > 0x8F)) {
4620 goto surrogateescape;
4621 }
4622 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4623 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4624 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4625
4626#if SIZEOF_WCHAR_T == 4
4627 *p++ = (wchar_t)ch;
4628#else
4629 /* compute and append the two surrogates: */
4630
4631 /* translate from 10000..10FFFF to 0..FFFF */
4632 ch -= 0x10000;
4633
4634 /* high surrogate = top 10 bits added to D800 */
4635 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4636
4637 /* low surrogate = bottom 10 bits added to DC00 */
4638 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4639#endif
4640 break;
4641 }
4642 s += n;
4643 continue;
4644
4645 surrogateescape:
4646 *p++ = 0xDC00 + ch;
4647 s++;
4648 }
4649 *p = L'\0';
4650 return unicode;
4651}
4652
4653#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004654
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655/* Primary internal function which creates utf8 encoded bytes objects.
4656
4657 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004658 and allocate exactly as much space needed at the end. Else allocate the
4659 maximum possible needed (4 result bytes per Unicode character), and return
4660 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004661*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004662PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004663_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004664{
Tim Peters602f7402002-04-27 18:03:26 +00004665#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004666
Guido van Rossum98297ee2007-11-06 21:34:58 +00004667 Py_ssize_t i; /* index into s of next input byte */
4668 PyObject *result; /* result string object */
4669 char *p; /* next free byte in output buffer */
4670 Py_ssize_t nallocated; /* number of result bytes allocated */
4671 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004672 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004673 PyObject *errorHandler = NULL;
4674 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004675 int kind;
4676 void *data;
4677 Py_ssize_t size;
4678 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4679#if SIZEOF_WCHAR_T == 2
4680 Py_ssize_t wchar_offset = 0;
4681#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004683 if (!PyUnicode_Check(unicode)) {
4684 PyErr_BadArgument();
4685 return NULL;
4686 }
4687
4688 if (PyUnicode_READY(unicode) == -1)
4689 return NULL;
4690
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004691 if (PyUnicode_UTF8(unicode))
4692 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4693 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004694
4695 kind = PyUnicode_KIND(unicode);
4696 data = PyUnicode_DATA(unicode);
4697 size = PyUnicode_GET_LENGTH(unicode);
4698
Tim Peters602f7402002-04-27 18:03:26 +00004699 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004700
Tim Peters602f7402002-04-27 18:03:26 +00004701 if (size <= MAX_SHORT_UNICHARS) {
4702 /* Write into the stack buffer; nallocated can't overflow.
4703 * At the end, we'll allocate exactly as much heap space as it
4704 * turns out we need.
4705 */
4706 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004707 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004708 p = stackbuf;
4709 }
4710 else {
4711 /* Overallocate on the heap, and give the excess back at the end. */
4712 nallocated = size * 4;
4713 if (nallocated / 4 != size) /* overflow! */
4714 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004715 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004716 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004717 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004718 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004719 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004720
Tim Peters602f7402002-04-27 18:03:26 +00004721 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004722 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004723
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004724 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004725 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004726 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004727
Guido van Rossumd57fd912000-03-10 22:53:23 +00004728 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004729 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004730 *p++ = (char)(0xc0 | (ch >> 6));
4731 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004732 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004733 Py_ssize_t newpos;
4734 PyObject *rep;
4735 Py_ssize_t repsize, k, startpos;
4736 startpos = i-1;
4737#if SIZEOF_WCHAR_T == 2
4738 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004739#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004740 rep = unicode_encode_call_errorhandler(
4741 errors, &errorHandler, "utf-8", "surrogates not allowed",
4742 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4743 &exc, startpos, startpos+1, &newpos);
4744 if (!rep)
4745 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004747 if (PyBytes_Check(rep))
4748 repsize = PyBytes_GET_SIZE(rep);
4749 else
4750 repsize = PyUnicode_GET_SIZE(rep);
4751
4752 if (repsize > 4) {
4753 Py_ssize_t offset;
4754
4755 if (result == NULL)
4756 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004757 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004758 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004760 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4761 /* integer overflow */
4762 PyErr_NoMemory();
4763 goto error;
4764 }
4765 nallocated += repsize - 4;
4766 if (result != NULL) {
4767 if (_PyBytes_Resize(&result, nallocated) < 0)
4768 goto error;
4769 } else {
4770 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004771 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004772 goto error;
4773 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4774 }
4775 p = PyBytes_AS_STRING(result) + offset;
4776 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004777
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004778 if (PyBytes_Check(rep)) {
4779 char *prep = PyBytes_AS_STRING(rep);
4780 for(k = repsize; k > 0; k--)
4781 *p++ = *prep++;
4782 } else /* rep is unicode */ {
4783 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4784 Py_UNICODE c;
4785
4786 for(k=0; k<repsize; k++) {
4787 c = prep[k];
4788 if (0x80 <= c) {
4789 raise_encode_exception(&exc, "utf-8",
4790 PyUnicode_AS_UNICODE(unicode),
4791 size, i-1, i,
4792 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004793 goto error;
4794 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004795 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004796 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004797 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004798 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004799 } else if (ch < 0x10000) {
4800 *p++ = (char)(0xe0 | (ch >> 12));
4801 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4802 *p++ = (char)(0x80 | (ch & 0x3f));
4803 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004804 /* Encode UCS4 Unicode ordinals */
4805 *p++ = (char)(0xf0 | (ch >> 18));
4806 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4807 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4808 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004809#if SIZEOF_WCHAR_T == 2
4810 wchar_offset++;
4811#endif
Tim Peters602f7402002-04-27 18:03:26 +00004812 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004813 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004814
Guido van Rossum98297ee2007-11-06 21:34:58 +00004815 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004816 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004817 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004818 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004819 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004820 }
4821 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004822 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004823 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004824 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004825 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004826 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004828 Py_XDECREF(errorHandler);
4829 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004830 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004831 error:
4832 Py_XDECREF(errorHandler);
4833 Py_XDECREF(exc);
4834 Py_XDECREF(result);
4835 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004836
Tim Peters602f7402002-04-27 18:03:26 +00004837#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004838}
4839
Alexander Belopolsky40018472011-02-26 01:02:56 +00004840PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004841PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4842 Py_ssize_t size,
4843 const char *errors)
4844{
4845 PyObject *v, *unicode;
4846
4847 unicode = PyUnicode_FromUnicode(s, size);
4848 if (unicode == NULL)
4849 return NULL;
4850 v = _PyUnicode_AsUTF8String(unicode, errors);
4851 Py_DECREF(unicode);
4852 return v;
4853}
4854
4855PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004856PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004857{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004858 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004859}
4860
Walter Dörwald41980ca2007-08-16 21:55:45 +00004861/* --- UTF-32 Codec ------------------------------------------------------- */
4862
4863PyObject *
4864PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004865 Py_ssize_t size,
4866 const char *errors,
4867 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004868{
4869 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4870}
4871
4872PyObject *
4873PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004874 Py_ssize_t size,
4875 const char *errors,
4876 int *byteorder,
4877 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004878{
4879 const char *starts = s;
4880 Py_ssize_t startinpos;
4881 Py_ssize_t endinpos;
4882 Py_ssize_t outpos;
4883 PyUnicodeObject *unicode;
4884 Py_UNICODE *p;
4885#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004886 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004887 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004888#else
4889 const int pairs = 0;
4890#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004891 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004892 int bo = 0; /* assume native ordering by default */
4893 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004894 /* Offsets from q for retrieving bytes in the right order. */
4895#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4896 int iorder[] = {0, 1, 2, 3};
4897#else
4898 int iorder[] = {3, 2, 1, 0};
4899#endif
4900 PyObject *errorHandler = NULL;
4901 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004902
Walter Dörwald41980ca2007-08-16 21:55:45 +00004903 q = (unsigned char *)s;
4904 e = q + size;
4905
4906 if (byteorder)
4907 bo = *byteorder;
4908
4909 /* Check for BOM marks (U+FEFF) in the input and adjust current
4910 byte order setting accordingly. In native mode, the leading BOM
4911 mark is skipped, in all other modes, it is copied to the output
4912 stream as-is (giving a ZWNBSP character). */
4913 if (bo == 0) {
4914 if (size >= 4) {
4915 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004916 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004917#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004918 if (bom == 0x0000FEFF) {
4919 q += 4;
4920 bo = -1;
4921 }
4922 else if (bom == 0xFFFE0000) {
4923 q += 4;
4924 bo = 1;
4925 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004926#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004927 if (bom == 0x0000FEFF) {
4928 q += 4;
4929 bo = 1;
4930 }
4931 else if (bom == 0xFFFE0000) {
4932 q += 4;
4933 bo = -1;
4934 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004936 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004937 }
4938
4939 if (bo == -1) {
4940 /* force LE */
4941 iorder[0] = 0;
4942 iorder[1] = 1;
4943 iorder[2] = 2;
4944 iorder[3] = 3;
4945 }
4946 else if (bo == 1) {
4947 /* force BE */
4948 iorder[0] = 3;
4949 iorder[1] = 2;
4950 iorder[2] = 1;
4951 iorder[3] = 0;
4952 }
4953
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004954 /* On narrow builds we split characters outside the BMP into two
4955 codepoints => count how much extra space we need. */
4956#ifndef Py_UNICODE_WIDE
4957 for (qq = q; qq < e; qq += 4)
4958 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4959 pairs++;
4960#endif
4961
4962 /* This might be one to much, because of a BOM */
4963 unicode = _PyUnicode_New((size+3)/4+pairs);
4964 if (!unicode)
4965 return NULL;
4966 if (size == 0)
4967 return (PyObject *)unicode;
4968
4969 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004970 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004971
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004973 Py_UCS4 ch;
4974 /* remaining bytes at the end? (size should be divisible by 4) */
4975 if (e-q<4) {
4976 if (consumed)
4977 break;
4978 errmsg = "truncated data";
4979 startinpos = ((const char *)q)-starts;
4980 endinpos = ((const char *)e)-starts;
4981 goto utf32Error;
4982 /* The remaining input chars are ignored if the callback
4983 chooses to skip the input */
4984 }
4985 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4986 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004987
Benjamin Peterson29060642009-01-31 22:14:21 +00004988 if (ch >= 0x110000)
4989 {
4990 errmsg = "codepoint not in range(0x110000)";
4991 startinpos = ((const char *)q)-starts;
4992 endinpos = startinpos+4;
4993 goto utf32Error;
4994 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004996 if (ch >= 0x10000)
4997 {
4998 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4999 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
5000 }
5001 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00005002#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005003 *p++ = ch;
5004 q += 4;
5005 continue;
5006 utf32Error:
5007 outpos = p-PyUnicode_AS_UNICODE(unicode);
5008 if (unicode_decode_call_errorhandler(
5009 errors, &errorHandler,
5010 "utf32", errmsg,
5011 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5012 &unicode, &outpos, &p))
5013 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005014 }
5015
5016 if (byteorder)
5017 *byteorder = bo;
5018
5019 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005021
5022 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005023 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005024 goto onError;
5025
5026 Py_XDECREF(errorHandler);
5027 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005028#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005029 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005030 Py_DECREF(unicode);
5031 return NULL;
5032 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005033#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005034 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035 return (PyObject *)unicode;
5036
Benjamin Peterson29060642009-01-31 22:14:21 +00005037 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005038 Py_DECREF(unicode);
5039 Py_XDECREF(errorHandler);
5040 Py_XDECREF(exc);
5041 return NULL;
5042}
5043
5044PyObject *
5045PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005046 Py_ssize_t size,
5047 const char *errors,
5048 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005049{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005050 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005052 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005053#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005054 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055#else
5056 const int pairs = 0;
5057#endif
5058 /* Offsets from p for storing byte pairs in the right order. */
5059#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5060 int iorder[] = {0, 1, 2, 3};
5061#else
5062 int iorder[] = {3, 2, 1, 0};
5063#endif
5064
Benjamin Peterson29060642009-01-31 22:14:21 +00005065#define STORECHAR(CH) \
5066 do { \
5067 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5068 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5069 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5070 p[iorder[0]] = (CH) & 0xff; \
5071 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072 } while(0)
5073
5074 /* In narrow builds we can output surrogate pairs as one codepoint,
5075 so we need less space. */
5076#ifndef Py_UNICODE_WIDE
5077 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5079 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5080 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005082 nsize = (size - pairs + (byteorder == 0));
5083 bytesize = nsize * 4;
5084 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005085 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005086 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005087 if (v == NULL)
5088 return NULL;
5089
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005090 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005091 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005092 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005093 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005094 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005095
5096 if (byteorder == -1) {
5097 /* force LE */
5098 iorder[0] = 0;
5099 iorder[1] = 1;
5100 iorder[2] = 2;
5101 iorder[3] = 3;
5102 }
5103 else if (byteorder == 1) {
5104 /* force BE */
5105 iorder[0] = 3;
5106 iorder[1] = 2;
5107 iorder[2] = 1;
5108 iorder[3] = 0;
5109 }
5110
5111 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005112 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005114 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5115 Py_UCS4 ch2 = *s;
5116 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5117 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5118 s++;
5119 size--;
5120 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005121 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122#endif
5123 STORECHAR(ch);
5124 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005125
5126 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005127 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005128#undef STORECHAR
5129}
5130
Alexander Belopolsky40018472011-02-26 01:02:56 +00005131PyObject *
5132PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005133{
5134 if (!PyUnicode_Check(unicode)) {
5135 PyErr_BadArgument();
5136 return NULL;
5137 }
5138 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005139 PyUnicode_GET_SIZE(unicode),
5140 NULL,
5141 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005142}
5143
Guido van Rossumd57fd912000-03-10 22:53:23 +00005144/* --- UTF-16 Codec ------------------------------------------------------- */
5145
Tim Peters772747b2001-08-09 22:21:55 +00005146PyObject *
5147PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005148 Py_ssize_t size,
5149 const char *errors,
5150 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005151{
Walter Dörwald69652032004-09-07 20:24:22 +00005152 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5153}
5154
Antoine Pitrouab868312009-01-10 15:40:25 +00005155/* Two masks for fast checking of whether a C 'long' may contain
5156 UTF16-encoded surrogate characters. This is an efficient heuristic,
5157 assuming that non-surrogate characters with a code point >= 0x8000 are
5158 rare in most input.
5159 FAST_CHAR_MASK is used when the input is in native byte ordering,
5160 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005161*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005162#if (SIZEOF_LONG == 8)
5163# define FAST_CHAR_MASK 0x8000800080008000L
5164# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5165#elif (SIZEOF_LONG == 4)
5166# define FAST_CHAR_MASK 0x80008000L
5167# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5168#else
5169# error C 'long' size should be either 4 or 8!
5170#endif
5171
Walter Dörwald69652032004-09-07 20:24:22 +00005172PyObject *
5173PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005174 Py_ssize_t size,
5175 const char *errors,
5176 int *byteorder,
5177 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005178{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005179 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005180 Py_ssize_t startinpos;
5181 Py_ssize_t endinpos;
5182 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005183 PyUnicodeObject *unicode;
5184 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005185 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005186 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005187 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005188 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005189 /* Offsets from q for retrieving byte pairs in the right order. */
5190#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5191 int ihi = 1, ilo = 0;
5192#else
5193 int ihi = 0, ilo = 1;
5194#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005195 PyObject *errorHandler = NULL;
5196 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005197
5198 /* Note: size will always be longer than the resulting Unicode
5199 character count */
5200 unicode = _PyUnicode_New(size);
5201 if (!unicode)
5202 return NULL;
5203 if (size == 0)
5204 return (PyObject *)unicode;
5205
5206 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005207 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005208 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005209 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005210
5211 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005212 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005214 /* Check for BOM marks (U+FEFF) in the input and adjust current
5215 byte order setting accordingly. In native mode, the leading BOM
5216 mark is skipped, in all other modes, it is copied to the output
5217 stream as-is (giving a ZWNBSP character). */
5218 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005219 if (size >= 2) {
5220 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005221#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005222 if (bom == 0xFEFF) {
5223 q += 2;
5224 bo = -1;
5225 }
5226 else if (bom == 0xFFFE) {
5227 q += 2;
5228 bo = 1;
5229 }
Tim Petersced69f82003-09-16 20:30:58 +00005230#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005231 if (bom == 0xFEFF) {
5232 q += 2;
5233 bo = 1;
5234 }
5235 else if (bom == 0xFFFE) {
5236 q += 2;
5237 bo = -1;
5238 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005239#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005240 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005241 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005242
Tim Peters772747b2001-08-09 22:21:55 +00005243 if (bo == -1) {
5244 /* force LE */
5245 ihi = 1;
5246 ilo = 0;
5247 }
5248 else if (bo == 1) {
5249 /* force BE */
5250 ihi = 0;
5251 ilo = 1;
5252 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005253#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5254 native_ordering = ilo < ihi;
5255#else
5256 native_ordering = ilo > ihi;
5257#endif
Tim Peters772747b2001-08-09 22:21:55 +00005258
Antoine Pitrouab868312009-01-10 15:40:25 +00005259 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005260 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005261 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005262 /* First check for possible aligned read of a C 'long'. Unaligned
5263 reads are more expensive, better to defer to another iteration. */
5264 if (!((size_t) q & LONG_PTR_MASK)) {
5265 /* Fast path for runs of non-surrogate chars. */
5266 register const unsigned char *_q = q;
5267 Py_UNICODE *_p = p;
5268 if (native_ordering) {
5269 /* Native ordering is simple: as long as the input cannot
5270 possibly contain a surrogate char, do an unrolled copy
5271 of several 16-bit code points to the target object.
5272 The non-surrogate check is done on several input bytes
5273 at a time (as many as a C 'long' can contain). */
5274 while (_q < aligned_end) {
5275 unsigned long data = * (unsigned long *) _q;
5276 if (data & FAST_CHAR_MASK)
5277 break;
5278 _p[0] = ((unsigned short *) _q)[0];
5279 _p[1] = ((unsigned short *) _q)[1];
5280#if (SIZEOF_LONG == 8)
5281 _p[2] = ((unsigned short *) _q)[2];
5282 _p[3] = ((unsigned short *) _q)[3];
5283#endif
5284 _q += SIZEOF_LONG;
5285 _p += SIZEOF_LONG / 2;
5286 }
5287 }
5288 else {
5289 /* Byteswapped ordering is similar, but we must decompose
5290 the copy bytewise, and take care of zero'ing out the
5291 upper bytes if the target object is in 32-bit units
5292 (that is, in UCS-4 builds). */
5293 while (_q < aligned_end) {
5294 unsigned long data = * (unsigned long *) _q;
5295 if (data & SWAPPED_FAST_CHAR_MASK)
5296 break;
5297 /* Zero upper bytes in UCS-4 builds */
5298#if (Py_UNICODE_SIZE > 2)
5299 _p[0] = 0;
5300 _p[1] = 0;
5301#if (SIZEOF_LONG == 8)
5302 _p[2] = 0;
5303 _p[3] = 0;
5304#endif
5305#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005306 /* Issue #4916; UCS-4 builds on big endian machines must
5307 fill the two last bytes of each 4-byte unit. */
5308#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5309# define OFF 2
5310#else
5311# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005312#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005313 ((unsigned char *) _p)[OFF + 1] = _q[0];
5314 ((unsigned char *) _p)[OFF + 0] = _q[1];
5315 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5316 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5317#if (SIZEOF_LONG == 8)
5318 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5319 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5320 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5321 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5322#endif
5323#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005324 _q += SIZEOF_LONG;
5325 _p += SIZEOF_LONG / 2;
5326 }
5327 }
5328 p = _p;
5329 q = _q;
5330 if (q >= e)
5331 break;
5332 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005334
Benjamin Peterson14339b62009-01-31 16:36:08 +00005335 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005336
5337 if (ch < 0xD800 || ch > 0xDFFF) {
5338 *p++ = ch;
5339 continue;
5340 }
5341
5342 /* UTF-16 code pair: */
5343 if (q > e) {
5344 errmsg = "unexpected end of data";
5345 startinpos = (((const char *)q) - 2) - starts;
5346 endinpos = ((const char *)e) + 1 - starts;
5347 goto utf16Error;
5348 }
5349 if (0xD800 <= ch && ch <= 0xDBFF) {
5350 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5351 q += 2;
5352 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005353#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005354 *p++ = ch;
5355 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005356#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005358#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 continue;
5360 }
5361 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005362 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 startinpos = (((const char *)q)-4)-starts;
5364 endinpos = startinpos+2;
5365 goto utf16Error;
5366 }
5367
Benjamin Peterson14339b62009-01-31 16:36:08 +00005368 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005369 errmsg = "illegal encoding";
5370 startinpos = (((const char *)q)-2)-starts;
5371 endinpos = startinpos+2;
5372 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005373
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 utf16Error:
5375 outpos = p - PyUnicode_AS_UNICODE(unicode);
5376 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005377 errors,
5378 &errorHandler,
5379 "utf16", errmsg,
5380 &starts,
5381 (const char **)&e,
5382 &startinpos,
5383 &endinpos,
5384 &exc,
5385 (const char **)&q,
5386 &unicode,
5387 &outpos,
5388 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005389 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005390 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005391 /* remaining byte at the end? (size should be even) */
5392 if (e == q) {
5393 if (!consumed) {
5394 errmsg = "truncated data";
5395 startinpos = ((const char *)q) - starts;
5396 endinpos = ((const char *)e) + 1 - starts;
5397 outpos = p - PyUnicode_AS_UNICODE(unicode);
5398 if (unicode_decode_call_errorhandler(
5399 errors,
5400 &errorHandler,
5401 "utf16", errmsg,
5402 &starts,
5403 (const char **)&e,
5404 &startinpos,
5405 &endinpos,
5406 &exc,
5407 (const char **)&q,
5408 &unicode,
5409 &outpos,
5410 &p))
5411 goto onError;
5412 /* The remaining input chars are ignored if the callback
5413 chooses to skip the input */
5414 }
5415 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416
5417 if (byteorder)
5418 *byteorder = bo;
5419
Walter Dörwald69652032004-09-07 20:24:22 +00005420 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005421 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005422
Guido van Rossumd57fd912000-03-10 22:53:23 +00005423 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005424 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005425 goto onError;
5426
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005427 Py_XDECREF(errorHandler);
5428 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005429#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005430 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005431 Py_DECREF(unicode);
5432 return NULL;
5433 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005434#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005435 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436 return (PyObject *)unicode;
5437
Benjamin Peterson29060642009-01-31 22:14:21 +00005438 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005440 Py_XDECREF(errorHandler);
5441 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005442 return NULL;
5443}
5444
Antoine Pitrouab868312009-01-10 15:40:25 +00005445#undef FAST_CHAR_MASK
5446#undef SWAPPED_FAST_CHAR_MASK
5447
Tim Peters772747b2001-08-09 22:21:55 +00005448PyObject *
5449PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005450 Py_ssize_t size,
5451 const char *errors,
5452 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005453{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005454 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005455 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005456 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005457#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005458 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005459#else
5460 const int pairs = 0;
5461#endif
Tim Peters772747b2001-08-09 22:21:55 +00005462 /* Offsets from p for storing byte pairs in the right order. */
5463#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5464 int ihi = 1, ilo = 0;
5465#else
5466 int ihi = 0, ilo = 1;
5467#endif
5468
Benjamin Peterson29060642009-01-31 22:14:21 +00005469#define STORECHAR(CH) \
5470 do { \
5471 p[ihi] = ((CH) >> 8) & 0xff; \
5472 p[ilo] = (CH) & 0xff; \
5473 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005474 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005475
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005476#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005477 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005478 if (s[i] >= 0x10000)
5479 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005480#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005481 /* 2 * (size + pairs + (byteorder == 0)) */
5482 if (size > PY_SSIZE_T_MAX ||
5483 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005485 nsize = size + pairs + (byteorder == 0);
5486 bytesize = nsize * 2;
5487 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005488 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005489 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005490 if (v == NULL)
5491 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005492
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005493 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005494 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005495 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005496 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005497 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005498
5499 if (byteorder == -1) {
5500 /* force LE */
5501 ihi = 1;
5502 ilo = 0;
5503 }
5504 else if (byteorder == 1) {
5505 /* force BE */
5506 ihi = 0;
5507 ilo = 1;
5508 }
5509
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005510 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005511 Py_UNICODE ch = *s++;
5512 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005513#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005514 if (ch >= 0x10000) {
5515 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5516 ch = 0xD800 | ((ch-0x10000) >> 10);
5517 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005518#endif
Tim Peters772747b2001-08-09 22:21:55 +00005519 STORECHAR(ch);
5520 if (ch2)
5521 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005522 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005523
5524 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005525 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005526#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005527}
5528
Alexander Belopolsky40018472011-02-26 01:02:56 +00005529PyObject *
5530PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005531{
5532 if (!PyUnicode_Check(unicode)) {
5533 PyErr_BadArgument();
5534 return NULL;
5535 }
5536 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005537 PyUnicode_GET_SIZE(unicode),
5538 NULL,
5539 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005540}
5541
5542/* --- Unicode Escape Codec ----------------------------------------------- */
5543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5545 if all the escapes in the string make it still a valid ASCII string.
5546 Returns -1 if any escapes were found which cause the string to
5547 pop out of ASCII range. Otherwise returns the length of the
5548 required buffer to hold the string.
5549 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005550static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005551length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5552{
5553 const unsigned char *p = (const unsigned char *)s;
5554 const unsigned char *end = p + size;
5555 Py_ssize_t length = 0;
5556
5557 if (size < 0)
5558 return -1;
5559
5560 for (; p < end; ++p) {
5561 if (*p > 127) {
5562 /* Non-ASCII */
5563 return -1;
5564 }
5565 else if (*p != '\\') {
5566 /* Normal character */
5567 ++length;
5568 }
5569 else {
5570 /* Backslash-escape, check next char */
5571 ++p;
5572 /* Escape sequence reaches till end of string or
5573 non-ASCII follow-up. */
5574 if (p >= end || *p > 127)
5575 return -1;
5576 switch (*p) {
5577 case '\n':
5578 /* backslash + \n result in zero characters */
5579 break;
5580 case '\\': case '\'': case '\"':
5581 case 'b': case 'f': case 't':
5582 case 'n': case 'r': case 'v': case 'a':
5583 ++length;
5584 break;
5585 case '0': case '1': case '2': case '3':
5586 case '4': case '5': case '6': case '7':
5587 case 'x': case 'u': case 'U': case 'N':
5588 /* these do not guarantee ASCII characters */
5589 return -1;
5590 default:
5591 /* count the backslash + the other character */
5592 length += 2;
5593 }
5594 }
5595 }
5596 return length;
5597}
5598
5599/* Similar to PyUnicode_WRITE but either write into wstr field
5600 or treat string as ASCII. */
5601#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5602 do { \
5603 if ((kind) != PyUnicode_WCHAR_KIND) \
5604 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5605 else \
5606 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5607 } while (0)
5608
5609#define WRITE_WSTR(buf, index, value) \
5610 assert(kind == PyUnicode_WCHAR_KIND), \
5611 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5612
5613
Fredrik Lundh06d12682001-01-24 07:59:11 +00005614static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005615
Alexander Belopolsky40018472011-02-26 01:02:56 +00005616PyObject *
5617PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005618 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005619 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005621 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005622 Py_ssize_t startinpos;
5623 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005624 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005626 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005627 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005628 char* message;
5629 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005630 PyObject *errorHandler = NULL;
5631 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005632 Py_ssize_t ascii_length;
5633 Py_ssize_t i;
5634 int kind;
5635 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005636
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005637 ascii_length = length_of_escaped_ascii_string(s, size);
5638
5639 /* After length_of_escaped_ascii_string() there are two alternatives,
5640 either the string is pure ASCII with named escapes like \n, etc.
5641 and we determined it's exact size (common case)
5642 or it contains \x, \u, ... escape sequences. then we create a
5643 legacy wchar string and resize it at the end of this function. */
5644 if (ascii_length >= 0) {
5645 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5646 if (!v)
5647 goto onError;
5648 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5649 kind = PyUnicode_1BYTE_KIND;
5650 data = PyUnicode_DATA(v);
5651 }
5652 else {
5653 /* Escaped strings will always be longer than the resulting
5654 Unicode string, so we start with size here and then reduce the
5655 length after conversion to the true value.
5656 (but if the error callback returns a long replacement string
5657 we'll have to allocate more space) */
5658 v = _PyUnicode_New(size);
5659 if (!v)
5660 goto onError;
5661 kind = PyUnicode_WCHAR_KIND;
5662 data = PyUnicode_AS_UNICODE(v);
5663 }
5664
Guido van Rossumd57fd912000-03-10 22:53:23 +00005665 if (size == 0)
5666 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005667 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005669
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 while (s < end) {
5671 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005672 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005673 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005674
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005675 if (kind == PyUnicode_WCHAR_KIND) {
5676 assert(i < _PyUnicode_WSTR_LENGTH(v));
5677 }
5678 else {
5679 /* The only case in which i == ascii_length is a backslash
5680 followed by a newline. */
5681 assert(i <= ascii_length);
5682 }
5683
Guido van Rossumd57fd912000-03-10 22:53:23 +00005684 /* Non-escape characters are interpreted as Unicode ordinals */
5685 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005686 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687 continue;
5688 }
5689
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005690 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691 /* \ - Escapes */
5692 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005693 c = *s++;
5694 if (s > end)
5695 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005696
5697 if (kind == PyUnicode_WCHAR_KIND) {
5698 assert(i < _PyUnicode_WSTR_LENGTH(v));
5699 }
5700 else {
5701 /* The only case in which i == ascii_length is a backslash
5702 followed by a newline. */
5703 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5704 }
5705
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005706 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005707
Benjamin Peterson29060642009-01-31 22:14:21 +00005708 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5711 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5712 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5713 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5714 /* FF */
5715 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5716 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5717 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5718 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5719 /* VT */
5720 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5721 /* BEL, not classic C */
5722 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723
Benjamin Peterson29060642009-01-31 22:14:21 +00005724 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 case '0': case '1': case '2': case '3':
5726 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005727 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005728 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005729 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005730 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005731 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005733 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734 break;
5735
Benjamin Peterson29060642009-01-31 22:14:21 +00005736 /* hex escapes */
5737 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005739 digits = 2;
5740 message = "truncated \\xXX escape";
5741 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005744 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005745 digits = 4;
5746 message = "truncated \\uXXXX escape";
5747 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005748
Benjamin Peterson29060642009-01-31 22:14:21 +00005749 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005750 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005751 digits = 8;
5752 message = "truncated \\UXXXXXXXX escape";
5753 hexescape:
5754 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005755 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 if (s+digits>end) {
5757 endinpos = size;
5758 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005759 errors, &errorHandler,
5760 "unicodeescape", "end of string in escape sequence",
5761 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005762 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005763 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005764 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 goto nextByte;
5766 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 for (j = 0; j < digits; ++j) {
5768 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005769 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005770 endinpos = (s+j+1)-starts;
5771 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005772 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005773 errors, &errorHandler,
5774 "unicodeescape", message,
5775 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005776 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005777 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005778 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005780 }
5781 chr = (chr<<4) & ~0xF;
5782 if (c >= '0' && c <= '9')
5783 chr += c - '0';
5784 else if (c >= 'a' && c <= 'f')
5785 chr += 10 + c - 'a';
5786 else
5787 chr += 10 + c - 'A';
5788 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005789 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005790 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005791 /* _decoding_error will have already written into the
5792 target buffer. */
5793 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005794 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005795 /* when we get here, chr is a 32-bit unicode character */
5796 if (chr <= 0xffff)
5797 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005798 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005799 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005800 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005801 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005802#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005803 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005804#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005805 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005806 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5807 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005808#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005809 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005810 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005813 errors, &errorHandler,
5814 "unicodeescape", "illegal Unicode character",
5815 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005816 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005817 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005818 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005819 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005820 break;
5821
Benjamin Peterson29060642009-01-31 22:14:21 +00005822 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005823 case 'N':
5824 message = "malformed \\N character escape";
5825 if (ucnhash_CAPI == NULL) {
5826 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005827 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5828 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005829 if (ucnhash_CAPI == NULL)
5830 goto ucnhashError;
5831 }
5832 if (*s == '{') {
5833 const char *start = s+1;
5834 /* look for the closing brace */
5835 while (*s != '}' && s < end)
5836 s++;
5837 if (s > start && s < end && *s == '}') {
5838 /* found a name. look it up in the unicode database */
5839 message = "unknown Unicode character name";
5840 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005841 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005842 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005843 goto store;
5844 }
5845 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005846 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005848 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005849 errors, &errorHandler,
5850 "unicodeescape", message,
5851 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005853 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005854 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005855 break;
5856
5857 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005858 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005860 message = "\\ at end of string";
5861 s--;
5862 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005863 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005864 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005865 errors, &errorHandler,
5866 "unicodeescape", message,
5867 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005868 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005869 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005870 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005871 }
5872 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005873 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5874 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005875 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005876 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005878 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005879 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005881 /* Ensure the length prediction worked in case of ASCII strings */
5882 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5883
Victor Stinnerfe226c02011-10-03 03:52:20 +02005884 if (kind == PyUnicode_WCHAR_KIND)
5885 {
5886 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5887 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005888 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005889 Py_XDECREF(errorHandler);
5890 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005891#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005892 if (_PyUnicode_READY_REPLACE(&v)) {
5893 Py_DECREF(v);
5894 return NULL;
5895 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005896#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005897 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005899
Benjamin Peterson29060642009-01-31 22:14:21 +00005900 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005901 PyErr_SetString(
5902 PyExc_UnicodeError,
5903 "\\N escapes not supported (can't load unicodedata module)"
5904 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005905 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005906 Py_XDECREF(errorHandler);
5907 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005908 return NULL;
5909
Benjamin Peterson29060642009-01-31 22:14:21 +00005910 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005911 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005912 Py_XDECREF(errorHandler);
5913 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914 return NULL;
5915}
5916
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005917#undef WRITE_ASCII_OR_WSTR
5918#undef WRITE_WSTR
5919
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920/* Return a Unicode-Escape string version of the Unicode object.
5921
5922 If quotes is true, the string is enclosed in u"" or u'' quotes as
5923 appropriate.
5924
5925*/
5926
Alexander Belopolsky40018472011-02-26 01:02:56 +00005927PyObject *
5928PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005929 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005930{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005931 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005933
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005934#ifdef Py_UNICODE_WIDE
5935 const Py_ssize_t expandsize = 10;
5936#else
5937 const Py_ssize_t expandsize = 6;
5938#endif
5939
Thomas Wouters89f507f2006-12-13 04:49:30 +00005940 /* XXX(nnorwitz): rather than over-allocating, it would be
5941 better to choose a different scheme. Perhaps scan the
5942 first N-chars of the string and allocate based on that size.
5943 */
5944 /* Initial allocation is based on the longest-possible unichr
5945 escape.
5946
5947 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5948 unichr, so in this case it's the longest unichr escape. In
5949 narrow (UTF-16) builds this is five chars per source unichr
5950 since there are two unichrs in the surrogate pair, so in narrow
5951 (UTF-16) builds it's not the longest unichr escape.
5952
5953 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5954 so in the narrow (UTF-16) build case it's the longest unichr
5955 escape.
5956 */
5957
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005958 if (size == 0)
5959 return PyBytes_FromStringAndSize(NULL, 0);
5960
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005961 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005962 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005963
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005964 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005965 2
5966 + expandsize*size
5967 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005968 if (repr == NULL)
5969 return NULL;
5970
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005971 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 while (size-- > 0) {
5974 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005975
Walter Dörwald79e913e2007-05-12 11:08:06 +00005976 /* Escape backslashes */
5977 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 *p++ = '\\';
5979 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005980 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005981 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005982
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005983#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005984 /* Map 21-bit characters to '\U00xxxxxx' */
5985 else if (ch >= 0x10000) {
5986 *p++ = '\\';
5987 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005988 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5989 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5990 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5991 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5993 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5994 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5995 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005996 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005997 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005998#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005999 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6000 else if (ch >= 0xD800 && ch < 0xDC00) {
6001 Py_UNICODE ch2;
6002 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00006003
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 ch2 = *s++;
6005 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006006 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006007 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6008 *p++ = '\\';
6009 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006010 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
6011 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
6012 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
6013 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
6014 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
6015 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
6016 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
6017 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006018 continue;
6019 }
6020 /* Fall through: isolated surrogates are copied as-is */
6021 s--;
6022 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006023 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006024#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006025
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006027 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006028 *p++ = '\\';
6029 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006030 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6031 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6032 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6033 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006035
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006036 /* Map special whitespace to '\t', \n', '\r' */
6037 else if (ch == '\t') {
6038 *p++ = '\\';
6039 *p++ = 't';
6040 }
6041 else if (ch == '\n') {
6042 *p++ = '\\';
6043 *p++ = 'n';
6044 }
6045 else if (ch == '\r') {
6046 *p++ = '\\';
6047 *p++ = 'r';
6048 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006049
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006050 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006051 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006053 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006054 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6055 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006056 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006057
Guido van Rossumd57fd912000-03-10 22:53:23 +00006058 /* Copy everything else as-is */
6059 else
6060 *p++ = (char) ch;
6061 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006062
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006063 assert(p - PyBytes_AS_STRING(repr) > 0);
6064 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6065 return NULL;
6066 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067}
6068
Alexander Belopolsky40018472011-02-26 01:02:56 +00006069PyObject *
6070PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006071{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006072 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006073 if (!PyUnicode_Check(unicode)) {
6074 PyErr_BadArgument();
6075 return NULL;
6076 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006077 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6078 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006079 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006080}
6081
6082/* --- Raw Unicode Escape Codec ------------------------------------------- */
6083
Alexander Belopolsky40018472011-02-26 01:02:56 +00006084PyObject *
6085PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006086 Py_ssize_t size,
6087 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006088{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006089 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006090 Py_ssize_t startinpos;
6091 Py_ssize_t endinpos;
6092 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006094 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095 const char *end;
6096 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006097 PyObject *errorHandler = NULL;
6098 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006099
Guido van Rossumd57fd912000-03-10 22:53:23 +00006100 /* Escaped strings will always be longer than the resulting
6101 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006102 length after conversion to the true value. (But decoding error
6103 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006104 v = _PyUnicode_New(size);
6105 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006106 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006107 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006108 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006109 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006110 end = s + size;
6111 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 unsigned char c;
6113 Py_UCS4 x;
6114 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006115 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116
Benjamin Peterson29060642009-01-31 22:14:21 +00006117 /* Non-escape characters are interpreted as Unicode ordinals */
6118 if (*s != '\\') {
6119 *p++ = (unsigned char)*s++;
6120 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006121 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 startinpos = s-starts;
6123
6124 /* \u-escapes are only interpreted iff the number of leading
6125 backslashes if odd */
6126 bs = s;
6127 for (;s < end;) {
6128 if (*s != '\\')
6129 break;
6130 *p++ = (unsigned char)*s++;
6131 }
6132 if (((s - bs) & 1) == 0 ||
6133 s >= end ||
6134 (*s != 'u' && *s != 'U')) {
6135 continue;
6136 }
6137 p--;
6138 count = *s=='u' ? 4 : 8;
6139 s++;
6140
6141 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6142 outpos = p-PyUnicode_AS_UNICODE(v);
6143 for (x = 0, i = 0; i < count; ++i, ++s) {
6144 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006145 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006146 endinpos = s-starts;
6147 if (unicode_decode_call_errorhandler(
6148 errors, &errorHandler,
6149 "rawunicodeescape", "truncated \\uXXXX",
6150 &starts, &end, &startinpos, &endinpos, &exc, &s,
6151 &v, &outpos, &p))
6152 goto onError;
6153 goto nextByte;
6154 }
6155 x = (x<<4) & ~0xF;
6156 if (c >= '0' && c <= '9')
6157 x += c - '0';
6158 else if (c >= 'a' && c <= 'f')
6159 x += 10 + c - 'a';
6160 else
6161 x += 10 + c - 'A';
6162 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006163 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006164 /* UCS-2 character */
6165 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006166 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 /* UCS-4 character. Either store directly, or as
6168 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006169#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006170 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006171#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 x -= 0x10000L;
6173 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6174 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006175#endif
6176 } else {
6177 endinpos = s-starts;
6178 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006179 if (unicode_decode_call_errorhandler(
6180 errors, &errorHandler,
6181 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006182 &starts, &end, &startinpos, &endinpos, &exc, &s,
6183 &v, &outpos, &p))
6184 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006185 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006186 nextByte:
6187 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006189 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006190 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006191 Py_XDECREF(errorHandler);
6192 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006193#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006194 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006195 Py_DECREF(v);
6196 return NULL;
6197 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006198#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006199 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006201
Benjamin Peterson29060642009-01-31 22:14:21 +00006202 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006203 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006204 Py_XDECREF(errorHandler);
6205 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206 return NULL;
6207}
6208
Alexander Belopolsky40018472011-02-26 01:02:56 +00006209PyObject *
6210PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006211 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006212{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006213 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214 char *p;
6215 char *q;
6216
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006217#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006218 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006219#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006220 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006221#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006222
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006223 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006224 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006225
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006226 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 if (repr == NULL)
6228 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006229 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006230 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006231
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006232 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006233 while (size-- > 0) {
6234 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006235#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006236 /* Map 32-bit characters to '\Uxxxxxxxx' */
6237 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006238 *p++ = '\\';
6239 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006240 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6241 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6242 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6243 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6244 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6245 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6246 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6247 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006248 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006249 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006250#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006251 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6252 if (ch >= 0xD800 && ch < 0xDC00) {
6253 Py_UNICODE ch2;
6254 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006255
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 ch2 = *s++;
6257 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006258 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006259 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6260 *p++ = '\\';
6261 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006262 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6263 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6264 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6265 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6266 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6267 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6268 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6269 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006270 continue;
6271 }
6272 /* Fall through: isolated surrogates are copied as-is */
6273 s--;
6274 size++;
6275 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006276#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006277 /* Map 16-bit characters to '\uxxxx' */
6278 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006279 *p++ = '\\';
6280 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006281 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6282 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6283 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6284 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006285 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006286 /* Copy everything else as-is */
6287 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006288 *p++ = (char) ch;
6289 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006290 size = p - q;
6291
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006292 assert(size > 0);
6293 if (_PyBytes_Resize(&repr, size) < 0)
6294 return NULL;
6295 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296}
6297
Alexander Belopolsky40018472011-02-26 01:02:56 +00006298PyObject *
6299PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006300{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006301 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006303 PyErr_BadArgument();
6304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006306 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6307 PyUnicode_GET_SIZE(unicode));
6308
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006309 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310}
6311
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006312/* --- Unicode Internal Codec ------------------------------------------- */
6313
Alexander Belopolsky40018472011-02-26 01:02:56 +00006314PyObject *
6315_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006316 Py_ssize_t size,
6317 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006318{
6319 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006320 Py_ssize_t startinpos;
6321 Py_ssize_t endinpos;
6322 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323 PyUnicodeObject *v;
6324 Py_UNICODE *p;
6325 const char *end;
6326 const char *reason;
6327 PyObject *errorHandler = NULL;
6328 PyObject *exc = NULL;
6329
Neal Norwitzd43069c2006-01-08 01:12:10 +00006330#ifdef Py_UNICODE_WIDE
6331 Py_UNICODE unimax = PyUnicode_GetMax();
6332#endif
6333
Thomas Wouters89f507f2006-12-13 04:49:30 +00006334 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006335 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6336 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006337 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006338 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6339 as string was created with the old API. */
6340 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006341 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006342 p = PyUnicode_AS_UNICODE(v);
6343 end = s + size;
6344
6345 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006346 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006347 /* We have to sanity check the raw data, otherwise doom looms for
6348 some malformed UCS-4 data. */
6349 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006350#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006351 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006352#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006353 end-s < Py_UNICODE_SIZE
6354 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006356 startinpos = s - starts;
6357 if (end-s < Py_UNICODE_SIZE) {
6358 endinpos = end-starts;
6359 reason = "truncated input";
6360 }
6361 else {
6362 endinpos = s - starts + Py_UNICODE_SIZE;
6363 reason = "illegal code point (> 0x10FFFF)";
6364 }
6365 outpos = p - PyUnicode_AS_UNICODE(v);
6366 if (unicode_decode_call_errorhandler(
6367 errors, &errorHandler,
6368 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006369 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006370 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006371 goto onError;
6372 }
6373 }
6374 else {
6375 p++;
6376 s += Py_UNICODE_SIZE;
6377 }
6378 }
6379
Victor Stinnerfe226c02011-10-03 03:52:20 +02006380 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006381 goto onError;
6382 Py_XDECREF(errorHandler);
6383 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006384#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006385 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006386 Py_DECREF(v);
6387 return NULL;
6388 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006389#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006390 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006391 return (PyObject *)v;
6392
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006394 Py_XDECREF(v);
6395 Py_XDECREF(errorHandler);
6396 Py_XDECREF(exc);
6397 return NULL;
6398}
6399
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400/* --- Latin-1 Codec ------------------------------------------------------ */
6401
Alexander Belopolsky40018472011-02-26 01:02:56 +00006402PyObject *
6403PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006404 Py_ssize_t size,
6405 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006407 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006408 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006409}
6410
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006411/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006412static void
6413make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006414 const char *encoding,
6415 const Py_UNICODE *unicode, Py_ssize_t size,
6416 Py_ssize_t startpos, Py_ssize_t endpos,
6417 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006418{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006419 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006420 *exceptionObject = PyUnicodeEncodeError_Create(
6421 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006422 }
6423 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006424 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6425 goto onError;
6426 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6427 goto onError;
6428 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6429 goto onError;
6430 return;
6431 onError:
6432 Py_DECREF(*exceptionObject);
6433 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006434 }
6435}
6436
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006437/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006438static void
6439raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006440 const char *encoding,
6441 const Py_UNICODE *unicode, Py_ssize_t size,
6442 Py_ssize_t startpos, Py_ssize_t endpos,
6443 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006444{
6445 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006446 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006448 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449}
6450
6451/* error handling callback helper:
6452 build arguments, call the callback and check the arguments,
6453 put the result into newpos and return the replacement string, which
6454 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006455static PyObject *
6456unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006457 PyObject **errorHandler,
6458 const char *encoding, const char *reason,
6459 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6460 Py_ssize_t startpos, Py_ssize_t endpos,
6461 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006462{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006463 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006464
6465 PyObject *restuple;
6466 PyObject *resunicode;
6467
6468 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006472 }
6473
6474 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006478
6479 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006480 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006481 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006483 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006484 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 Py_DECREF(restuple);
6486 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006487 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006488 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006489 &resunicode, newpos)) {
6490 Py_DECREF(restuple);
6491 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006492 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006493 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6494 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6495 Py_DECREF(restuple);
6496 return NULL;
6497 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006498 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006500 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6502 Py_DECREF(restuple);
6503 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006504 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006505 Py_INCREF(resunicode);
6506 Py_DECREF(restuple);
6507 return resunicode;
6508}
6509
Alexander Belopolsky40018472011-02-26 01:02:56 +00006510static PyObject *
6511unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006512 Py_ssize_t size,
6513 const char *errors,
6514 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515{
6516 /* output object */
6517 PyObject *res;
6518 /* pointers to the beginning and end+1 of input */
6519 const Py_UNICODE *startp = p;
6520 const Py_UNICODE *endp = p + size;
6521 /* pointer to the beginning of the unencodable characters */
6522 /* const Py_UNICODE *badp = NULL; */
6523 /* pointer into the output */
6524 char *str;
6525 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006526 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006527 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6528 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006529 PyObject *errorHandler = NULL;
6530 PyObject *exc = NULL;
6531 /* the following variable is used for caching string comparisons
6532 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6533 int known_errorHandler = -1;
6534
6535 /* allocate enough for a simple encoding without
6536 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006537 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006538 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006539 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006540 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006541 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006542 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006543 ressize = size;
6544
6545 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006546 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006547
Benjamin Peterson29060642009-01-31 22:14:21 +00006548 /* can we encode this? */
6549 if (c<limit) {
6550 /* no overflow check, because we know that the space is enough */
6551 *str++ = (char)c;
6552 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006553 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 else {
6555 Py_ssize_t unicodepos = p-startp;
6556 Py_ssize_t requiredsize;
6557 PyObject *repunicode;
6558 Py_ssize_t repsize;
6559 Py_ssize_t newpos;
6560 Py_ssize_t respos;
6561 Py_UNICODE *uni2;
6562 /* startpos for collecting unencodable chars */
6563 const Py_UNICODE *collstart = p;
6564 const Py_UNICODE *collend = p;
6565 /* find all unecodable characters */
6566 while ((collend < endp) && ((*collend)>=limit))
6567 ++collend;
6568 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6569 if (known_errorHandler==-1) {
6570 if ((errors==NULL) || (!strcmp(errors, "strict")))
6571 known_errorHandler = 1;
6572 else if (!strcmp(errors, "replace"))
6573 known_errorHandler = 2;
6574 else if (!strcmp(errors, "ignore"))
6575 known_errorHandler = 3;
6576 else if (!strcmp(errors, "xmlcharrefreplace"))
6577 known_errorHandler = 4;
6578 else
6579 known_errorHandler = 0;
6580 }
6581 switch (known_errorHandler) {
6582 case 1: /* strict */
6583 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6584 goto onError;
6585 case 2: /* replace */
6586 while (collstart++<collend)
6587 *str++ = '?'; /* fall through */
6588 case 3: /* ignore */
6589 p = collend;
6590 break;
6591 case 4: /* xmlcharrefreplace */
6592 respos = str - PyBytes_AS_STRING(res);
6593 /* determine replacement size (temporarily (mis)uses p) */
6594 for (p = collstart, repsize = 0; p < collend; ++p) {
6595 if (*p<10)
6596 repsize += 2+1+1;
6597 else if (*p<100)
6598 repsize += 2+2+1;
6599 else if (*p<1000)
6600 repsize += 2+3+1;
6601 else if (*p<10000)
6602 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006603#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 else
6605 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006606#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 else if (*p<100000)
6608 repsize += 2+5+1;
6609 else if (*p<1000000)
6610 repsize += 2+6+1;
6611 else
6612 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006613#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006614 }
6615 requiredsize = respos+repsize+(endp-collend);
6616 if (requiredsize > ressize) {
6617 if (requiredsize<2*ressize)
6618 requiredsize = 2*ressize;
6619 if (_PyBytes_Resize(&res, requiredsize))
6620 goto onError;
6621 str = PyBytes_AS_STRING(res) + respos;
6622 ressize = requiredsize;
6623 }
6624 /* generate replacement (temporarily (mis)uses p) */
6625 for (p = collstart; p < collend; ++p) {
6626 str += sprintf(str, "&#%d;", (int)*p);
6627 }
6628 p = collend;
6629 break;
6630 default:
6631 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6632 encoding, reason, startp, size, &exc,
6633 collstart-startp, collend-startp, &newpos);
6634 if (repunicode == NULL)
6635 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006636 if (PyBytes_Check(repunicode)) {
6637 /* Directly copy bytes result to output. */
6638 repsize = PyBytes_Size(repunicode);
6639 if (repsize > 1) {
6640 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006641 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006642 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6643 Py_DECREF(repunicode);
6644 goto onError;
6645 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006646 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006647 ressize += repsize-1;
6648 }
6649 memcpy(str, PyBytes_AsString(repunicode), repsize);
6650 str += repsize;
6651 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006652 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006653 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006654 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006655 /* need more space? (at least enough for what we
6656 have+the replacement+the rest of the string, so
6657 we won't have to check space for encodable characters) */
6658 respos = str - PyBytes_AS_STRING(res);
6659 repsize = PyUnicode_GET_SIZE(repunicode);
6660 requiredsize = respos+repsize+(endp-collend);
6661 if (requiredsize > ressize) {
6662 if (requiredsize<2*ressize)
6663 requiredsize = 2*ressize;
6664 if (_PyBytes_Resize(&res, requiredsize)) {
6665 Py_DECREF(repunicode);
6666 goto onError;
6667 }
6668 str = PyBytes_AS_STRING(res) + respos;
6669 ressize = requiredsize;
6670 }
6671 /* check if there is anything unencodable in the replacement
6672 and copy it to the output */
6673 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6674 c = *uni2;
6675 if (c >= limit) {
6676 raise_encode_exception(&exc, encoding, startp, size,
6677 unicodepos, unicodepos+1, reason);
6678 Py_DECREF(repunicode);
6679 goto onError;
6680 }
6681 *str = (char)c;
6682 }
6683 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006684 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006685 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006686 }
6687 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006688 /* Resize if we allocated to much */
6689 size = str - PyBytes_AS_STRING(res);
6690 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006691 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006692 if (_PyBytes_Resize(&res, size) < 0)
6693 goto onError;
6694 }
6695
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006696 Py_XDECREF(errorHandler);
6697 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006698 return res;
6699
6700 onError:
6701 Py_XDECREF(res);
6702 Py_XDECREF(errorHandler);
6703 Py_XDECREF(exc);
6704 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006705}
6706
Alexander Belopolsky40018472011-02-26 01:02:56 +00006707PyObject *
6708PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006709 Py_ssize_t size,
6710 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006711{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006712 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006713}
6714
Alexander Belopolsky40018472011-02-26 01:02:56 +00006715PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006716_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006717{
6718 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006719 PyErr_BadArgument();
6720 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006721 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006722 if (PyUnicode_READY(unicode) == -1)
6723 return NULL;
6724 /* Fast path: if it is a one-byte string, construct
6725 bytes object directly. */
6726 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6727 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6728 PyUnicode_GET_LENGTH(unicode));
6729 /* Non-Latin-1 characters present. Defer to above function to
6730 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006731 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006732 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006733 errors);
6734}
6735
6736PyObject*
6737PyUnicode_AsLatin1String(PyObject *unicode)
6738{
6739 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006740}
6741
6742/* --- 7-bit ASCII Codec -------------------------------------------------- */
6743
Alexander Belopolsky40018472011-02-26 01:02:56 +00006744PyObject *
6745PyUnicode_DecodeASCII(const char *s,
6746 Py_ssize_t size,
6747 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006748{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006749 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006750 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006751 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006752 Py_ssize_t startinpos;
6753 Py_ssize_t endinpos;
6754 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006755 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006756 int has_error;
6757 const unsigned char *p = (const unsigned char *)s;
6758 const unsigned char *end = p + size;
6759 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006760 PyObject *errorHandler = NULL;
6761 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006762
Guido van Rossumd57fd912000-03-10 22:53:23 +00006763 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006764 if (size == 1 && (unsigned char)s[0] < 128)
6765 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006766
Victor Stinner702c7342011-10-05 13:50:52 +02006767 has_error = 0;
6768 while (p < end && !has_error) {
6769 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6770 an explanation. */
6771 if (!((size_t) p & LONG_PTR_MASK)) {
6772 /* Help register allocation */
6773 register const unsigned char *_p = p;
6774 while (_p < aligned_end) {
6775 unsigned long value = *(unsigned long *) _p;
6776 if (value & ASCII_CHAR_MASK) {
6777 has_error = 1;
6778 break;
6779 }
6780 _p += SIZEOF_LONG;
6781 }
6782 if (_p == end)
6783 break;
6784 if (has_error)
6785 break;
6786 p = _p;
6787 }
6788 if (*p & 0x80) {
6789 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006790 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006791 }
6792 else {
6793 ++p;
6794 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006795 }
Victor Stinner702c7342011-10-05 13:50:52 +02006796 if (!has_error)
6797 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006798
Guido van Rossumd57fd912000-03-10 22:53:23 +00006799 v = _PyUnicode_New(size);
6800 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006801 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006802 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006803 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006804 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006805 e = s + size;
6806 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006807 register unsigned char c = (unsigned char)*s;
6808 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006809 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006810 ++s;
6811 }
6812 else {
6813 startinpos = s-starts;
6814 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006815 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006816 if (unicode_decode_call_errorhandler(
6817 errors, &errorHandler,
6818 "ascii", "ordinal not in range(128)",
6819 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006820 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006821 goto onError;
6822 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006823 }
Victor Stinner702c7342011-10-05 13:50:52 +02006824 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6825 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006826 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006827 Py_XDECREF(errorHandler);
6828 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006829#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006830 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006831 Py_DECREF(v);
6832 return NULL;
6833 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006834#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006835 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006836 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006837
Benjamin Peterson29060642009-01-31 22:14:21 +00006838 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006839 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006840 Py_XDECREF(errorHandler);
6841 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006842 return NULL;
6843}
6844
Alexander Belopolsky40018472011-02-26 01:02:56 +00006845PyObject *
6846PyUnicode_EncodeASCII(const Py_UNICODE *p,
6847 Py_ssize_t size,
6848 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006849{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006850 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006851}
6852
Alexander Belopolsky40018472011-02-26 01:02:56 +00006853PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006854_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006855{
6856 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 PyErr_BadArgument();
6858 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006859 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006860 if (PyUnicode_READY(unicode) == -1)
6861 return NULL;
6862 /* Fast path: if it is an ASCII-only string, construct bytes object
6863 directly. Else defer to above function to raise the exception. */
6864 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6865 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6866 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006867 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006868 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006869 errors);
6870}
6871
6872PyObject *
6873PyUnicode_AsASCIIString(PyObject *unicode)
6874{
6875 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006876}
6877
Victor Stinner99b95382011-07-04 14:23:54 +02006878#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006879
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006880/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006881
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006882#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006883#define NEED_RETRY
6884#endif
6885
Victor Stinner3a50e702011-10-18 21:21:00 +02006886#ifndef WC_ERR_INVALID_CHARS
6887# define WC_ERR_INVALID_CHARS 0x0080
6888#endif
6889
6890static char*
6891code_page_name(UINT code_page, PyObject **obj)
6892{
6893 *obj = NULL;
6894 if (code_page == CP_ACP)
6895 return "mbcs";
6896 if (code_page == CP_UTF7)
6897 return "CP_UTF7";
6898 if (code_page == CP_UTF8)
6899 return "CP_UTF8";
6900
6901 *obj = PyBytes_FromFormat("cp%u", code_page);
6902 if (*obj == NULL)
6903 return NULL;
6904 return PyBytes_AS_STRING(*obj);
6905}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006906
Alexander Belopolsky40018472011-02-26 01:02:56 +00006907static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006908is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006909{
6910 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006911 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006912
Victor Stinner3a50e702011-10-18 21:21:00 +02006913 if (!IsDBCSLeadByteEx(code_page, *curr))
6914 return 0;
6915
6916 prev = CharPrevExA(code_page, s, curr, 0);
6917 if (prev == curr)
6918 return 1;
6919 /* FIXME: This code is limited to "true" double-byte encodings,
6920 as it assumes an incomplete character consists of a single
6921 byte. */
6922 if (curr - prev == 2)
6923 return 1;
6924 if (!IsDBCSLeadByteEx(code_page, *prev))
6925 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006926 return 0;
6927}
6928
Victor Stinner3a50e702011-10-18 21:21:00 +02006929static DWORD
6930decode_code_page_flags(UINT code_page)
6931{
6932 if (code_page == CP_UTF7) {
6933 /* The CP_UTF7 decoder only supports flags=0 */
6934 return 0;
6935 }
6936 else
6937 return MB_ERR_INVALID_CHARS;
6938}
6939
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006940/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006941 * Decode a byte string from a Windows code page into unicode object in strict
6942 * mode.
6943 *
6944 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6945 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006946 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006947static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006948decode_code_page_strict(UINT code_page,
6949 PyUnicodeObject **v,
6950 const char *in,
6951 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006952{
Victor Stinner3a50e702011-10-18 21:21:00 +02006953 const DWORD flags = decode_code_page_flags(code_page);
6954 Py_UNICODE *out;
6955 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006956
6957 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006958 assert(insize > 0);
6959 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6960 if (outsize <= 0)
6961 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006962
6963 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006964 /* Create unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006965 *v = _PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006966 if (*v == NULL)
6967 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006968 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006969 }
6970 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006971 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006972 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6973 if (PyUnicode_Resize((PyObject**)v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006974 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006975 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006976 }
6977
6978 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006979 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6980 if (outsize <= 0)
6981 goto error;
6982 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006983
Victor Stinner3a50e702011-10-18 21:21:00 +02006984error:
6985 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6986 return -2;
6987 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006988 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006989}
6990
Victor Stinner3a50e702011-10-18 21:21:00 +02006991/*
6992 * Decode a byte string from a code page into unicode object with an error
6993 * handler.
6994 *
6995 * Returns consumed size if succeed, or raise a WindowsError or
6996 * UnicodeDecodeError exception and returns -1 on error.
6997 */
6998static int
6999decode_code_page_errors(UINT code_page,
7000 PyUnicodeObject **v,
7001 const char *in,
7002 int size,
7003 const char *errors)
7004{
7005 const char *startin = in;
7006 const char *endin = in + size;
7007 const DWORD flags = decode_code_page_flags(code_page);
7008 /* Ideally, we should get reason from FormatMessage. This is the Windows
7009 2000 English version of the message. */
7010 const char *reason = "No mapping for the Unicode character exists "
7011 "in the target code page.";
7012 /* each step cannot decode more than 1 character, but a character can be
7013 represented as a surrogate pair */
7014 wchar_t buffer[2], *startout, *out;
7015 int insize, outsize;
7016 PyObject *errorHandler = NULL;
7017 PyObject *exc = NULL;
7018 PyObject *encoding_obj = NULL;
7019 char *encoding;
7020 DWORD err;
7021 int ret = -1;
7022
7023 assert(size > 0);
7024
7025 encoding = code_page_name(code_page, &encoding_obj);
7026 if (encoding == NULL)
7027 return -1;
7028
7029 if (errors == NULL || strcmp(errors, "strict") == 0) {
7030 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7031 UnicodeDecodeError. */
7032 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7033 if (exc != NULL) {
7034 PyCodec_StrictErrors(exc);
7035 Py_CLEAR(exc);
7036 }
7037 goto error;
7038 }
7039
7040 if (*v == NULL) {
7041 /* Create unicode object */
7042 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7043 PyErr_NoMemory();
7044 goto error;
7045 }
7046 *v = _PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
7047 if (*v == NULL)
7048 goto error;
7049 startout = PyUnicode_AS_UNICODE(*v);
7050 }
7051 else {
7052 /* Extend unicode object */
7053 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7054 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7055 PyErr_NoMemory();
7056 goto error;
7057 }
7058 if (PyUnicode_Resize((PyObject**)v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
7059 goto error;
7060 startout = PyUnicode_AS_UNICODE(*v) + n;
7061 }
7062
7063 /* Decode the byte string character per character */
7064 out = startout;
7065 while (in < endin)
7066 {
7067 /* Decode a character */
7068 insize = 1;
7069 do
7070 {
7071 outsize = MultiByteToWideChar(code_page, flags,
7072 in, insize,
7073 buffer, Py_ARRAY_LENGTH(buffer));
7074 if (outsize > 0)
7075 break;
7076 err = GetLastError();
7077 if (err != ERROR_NO_UNICODE_TRANSLATION
7078 && err != ERROR_INSUFFICIENT_BUFFER)
7079 {
7080 PyErr_SetFromWindowsErr(0);
7081 goto error;
7082 }
7083 insize++;
7084 }
7085 /* 4=maximum length of a UTF-8 sequence */
7086 while (insize <= 4 && (in + insize) <= endin);
7087
7088 if (outsize <= 0) {
7089 Py_ssize_t startinpos, endinpos, outpos;
7090
7091 startinpos = in - startin;
7092 endinpos = startinpos + 1;
7093 outpos = out - PyUnicode_AS_UNICODE(*v);
7094 if (unicode_decode_call_errorhandler(
7095 errors, &errorHandler,
7096 encoding, reason,
7097 &startin, &endin, &startinpos, &endinpos, &exc, &in,
7098 v, &outpos, &out))
7099 {
7100 goto error;
7101 }
7102 }
7103 else {
7104 in += insize;
7105 memcpy(out, buffer, outsize * sizeof(wchar_t));
7106 out += outsize;
7107 }
7108 }
7109
7110 /* write a NUL character at the end */
7111 *out = 0;
7112
7113 /* Extend unicode object */
7114 outsize = out - startout;
7115 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
7116 if (PyUnicode_Resize((PyObject**)v, outsize) < 0)
7117 goto error;
7118 ret = 0;
7119
7120error:
7121 Py_XDECREF(encoding_obj);
7122 Py_XDECREF(errorHandler);
7123 Py_XDECREF(exc);
7124 return ret;
7125}
7126
7127/*
7128 * Decode a byte string from a Windows code page into unicode object. If
7129 * 'final' is set, converts trailing lead-byte too.
7130 *
7131 * Returns consumed size if succeed, or raise a WindowsError or
7132 * UnicodeDecodeError exception and returns -1 on error.
7133 */
7134static int
7135decode_code_page(UINT code_page,
7136 PyUnicodeObject **v,
7137 const char *s, int size,
7138 int final, const char *errors)
7139{
7140 int done;
7141
7142 /* Skip trailing lead-byte unless 'final' is set */
7143 if (size == 0) {
7144 if (*v == NULL) {
7145 Py_INCREF(unicode_empty);
7146 *v = (PyUnicodeObject*)unicode_empty;
7147 if (*v == NULL)
7148 return -1;
7149 }
7150 return 0;
7151 }
7152
7153 if (!final && is_dbcs_lead_byte(code_page, s, size - 1))
7154 --size;
7155
7156 done = decode_code_page_strict(code_page, v, s, size);
7157 if (done == -2)
7158 done = decode_code_page_errors(code_page, v, s, size, errors);
7159 return done;
7160}
7161
7162static PyObject *
7163decode_code_page_stateful(int code_page,
7164 const char *s,
7165 Py_ssize_t size,
7166 const char *errors,
7167 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007168{
7169 PyUnicodeObject *v = NULL;
7170 int done;
7171
Victor Stinner3a50e702011-10-18 21:21:00 +02007172 if (code_page < 0) {
7173 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7174 return NULL;
7175 }
7176
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007177 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007178 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007179
7180#ifdef NEED_RETRY
7181 retry:
7182 if (size > INT_MAX)
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 done = decode_code_page(code_page, &v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007184 else
7185#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007186 done = decode_code_page(code_page, &v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007187
7188 if (done < 0) {
7189 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00007190 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007191 }
7192
7193 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007194 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007195
7196#ifdef NEED_RETRY
7197 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007198 s += done;
7199 size -= done;
7200 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007201 }
7202#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007203
Victor Stinner17efeed2011-10-04 20:05:46 +02007204#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007205 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007206 Py_DECREF(v);
7207 return NULL;
7208 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007209#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007210 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007211 return (PyObject *)v;
7212}
7213
Alexander Belopolsky40018472011-02-26 01:02:56 +00007214PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007215PyUnicode_DecodeCodePageStateful(int code_page,
7216 const char *s,
7217 Py_ssize_t size,
7218 const char *errors,
7219 Py_ssize_t *consumed)
7220{
7221 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7222}
7223
7224PyObject *
7225PyUnicode_DecodeMBCSStateful(const char *s,
7226 Py_ssize_t size,
7227 const char *errors,
7228 Py_ssize_t *consumed)
7229{
7230 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7231}
7232
7233PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007234PyUnicode_DecodeMBCS(const char *s,
7235 Py_ssize_t size,
7236 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007237{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007238 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7239}
7240
Victor Stinner3a50e702011-10-18 21:21:00 +02007241static DWORD
7242encode_code_page_flags(UINT code_page, const char *errors)
7243{
7244 if (code_page == CP_UTF8) {
7245 if (winver.dwMajorVersion >= 6)
7246 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7247 and later */
7248 return WC_ERR_INVALID_CHARS;
7249 else
7250 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7251 return 0;
7252 }
7253 else if (code_page == CP_UTF7) {
7254 /* CP_UTF7 only supports flags=0 */
7255 return 0;
7256 }
7257 else {
7258 if (errors != NULL && strcmp(errors, "replace") == 0)
7259 return 0;
7260 else
7261 return WC_NO_BEST_FIT_CHARS;
7262 }
7263}
7264
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007265/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007266 * Encode a Unicode string to a Windows code page into a byte string in strict
7267 * mode.
7268 *
7269 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7270 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007271 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007272static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007273encode_code_page_strict(UINT code_page, PyObject **outbytes,
7274 const Py_UNICODE *p, const int size,
7275 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007276{
Victor Stinner554f3f02010-06-16 23:33:54 +00007277 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007278 BOOL *pusedDefaultChar = &usedDefaultChar;
7279 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007280 PyObject *exc = NULL;
Victor Stinner3a50e702011-10-18 21:21:00 +02007281 const DWORD flags = encode_code_page_flags(code_page, NULL);
7282 char *out;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007283
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 assert(size > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007285
Victor Stinner3a50e702011-10-18 21:21:00 +02007286 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007287 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007288 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007289 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007290
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007291 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007292 outsize = WideCharToMultiByte(code_page, flags,
7293 p, size,
7294 NULL, 0,
7295 NULL, pusedDefaultChar);
7296 if (outsize <= 0)
7297 goto error;
7298 /* If we used a default char, then we failed! */
7299 if (pusedDefaultChar && *pusedDefaultChar)
7300 return -2;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007301
Victor Stinner3a50e702011-10-18 21:21:00 +02007302 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007303 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007304 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7305 if (*outbytes == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007306 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007307 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007308 }
7309 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007310 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007311 const Py_ssize_t n = PyBytes_Size(*outbytes);
7312 if (outsize > PY_SSIZE_T_MAX - n) {
7313 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007314 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007315 }
7316 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7317 return -1;
7318 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007319 }
7320
7321 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007322 outsize = WideCharToMultiByte(code_page, flags,
7323 p, size,
7324 out, outsize,
7325 NULL, pusedDefaultChar);
7326 if (outsize <= 0)
7327 goto error;
7328 if (pusedDefaultChar && *pusedDefaultChar)
7329 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007330 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007331
Victor Stinner3a50e702011-10-18 21:21:00 +02007332error:
7333 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7334 return -2;
7335 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007336 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007337}
7338
Victor Stinner3a50e702011-10-18 21:21:00 +02007339/*
7340 * Encode a Unicode string to a Windows code page into a byte string using a
7341 * error handler.
7342 *
7343 * Returns consumed characters if succeed, or raise a WindowsError and returns
7344 * -1 on other error.
7345 */
7346static int
7347encode_code_page_errors(UINT code_page, PyObject **outbytes,
7348 const Py_UNICODE *in, const int insize,
7349 const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007350{
Victor Stinner3a50e702011-10-18 21:21:00 +02007351 const DWORD flags = encode_code_page_flags(code_page, errors);
7352 const Py_UNICODE *startin = in;
7353 const Py_UNICODE *endin = in + insize;
7354 /* Ideally, we should get reason from FormatMessage. This is the Windows
7355 2000 English version of the message. */
7356 const char *reason = "invalid character";
7357 /* 4=maximum length of a UTF-8 sequence */
7358 char buffer[4];
7359 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7360 Py_ssize_t outsize;
7361 char *out;
7362 int charsize;
7363 PyObject *errorHandler = NULL;
7364 PyObject *exc = NULL;
7365 PyObject *encoding_obj = NULL;
7366 char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 Py_ssize_t startpos, newpos, newoutsize;
7368 PyObject *rep;
7369 int ret = -1;
7370
7371 assert(insize > 0);
7372
7373 encoding = code_page_name(code_page, &encoding_obj);
7374 if (encoding == NULL)
7375 return -1;
7376
7377 if (errors == NULL || strcmp(errors, "strict") == 0) {
7378 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7379 then we raise a UnicodeEncodeError. */
7380 make_encode_exception(&exc, encoding, in, insize, 0, 0, reason);
7381 if (exc != NULL) {
7382 PyCodec_StrictErrors(exc);
7383 Py_DECREF(exc);
7384 }
7385 Py_XDECREF(encoding_obj);
7386 return -1;
7387 }
7388
7389 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7390 pusedDefaultChar = &usedDefaultChar;
7391 else
7392 pusedDefaultChar = NULL;
7393
7394 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7395 PyErr_NoMemory();
7396 goto error;
7397 }
7398 outsize = insize * Py_ARRAY_LENGTH(buffer);
7399
7400 if (*outbytes == NULL) {
7401 /* Create string object */
7402 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7403 if (*outbytes == NULL)
7404 goto error;
7405 out = PyBytes_AS_STRING(*outbytes);
7406 }
7407 else {
7408 /* Extend string object */
7409 Py_ssize_t n = PyBytes_Size(*outbytes);
7410 if (n > PY_SSIZE_T_MAX - outsize) {
7411 PyErr_NoMemory();
7412 goto error;
7413 }
7414 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7415 goto error;
7416 out = PyBytes_AS_STRING(*outbytes) + n;
7417 }
7418
7419 /* Encode the string character per character */
7420 while (in < endin)
7421 {
7422 if ((in + 2) <= endin
7423 && 0xD800 <= in[0] && in[0] <= 0xDBFF
7424 && 0xDC00 <= in[1] && in[1] <= 0xDFFF)
7425 charsize = 2;
7426 else
7427 charsize = 1;
7428
7429 outsize = WideCharToMultiByte(code_page, flags,
7430 in, charsize,
7431 buffer, Py_ARRAY_LENGTH(buffer),
7432 NULL, pusedDefaultChar);
7433 if (outsize > 0) {
7434 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7435 {
7436 in += charsize;
7437 memcpy(out, buffer, outsize);
7438 out += outsize;
7439 continue;
7440 }
7441 }
7442 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7443 PyErr_SetFromWindowsErr(0);
7444 goto error;
7445 }
7446
7447 charsize = Py_MAX(charsize - 1, 1);
7448 startpos = in - startin;
7449 rep = unicode_encode_call_errorhandler(
7450 errors, &errorHandler, encoding, reason,
7451 startin, insize, &exc,
7452 startpos, startpos + charsize, &newpos);
7453 if (rep == NULL)
7454 goto error;
7455 in = startin + newpos;
7456
7457 if (PyBytes_Check(rep)) {
7458 outsize = PyBytes_GET_SIZE(rep);
7459 if (outsize != 1) {
7460 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7461 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7462 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7463 Py_DECREF(rep);
7464 goto error;
7465 }
7466 out = PyBytes_AS_STRING(*outbytes) + offset;
7467 }
7468 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7469 out += outsize;
7470 }
7471 else {
7472 Py_ssize_t i;
7473 enum PyUnicode_Kind kind;
7474 void *data;
7475
7476 if (PyUnicode_READY(rep) < 0) {
7477 Py_DECREF(rep);
7478 goto error;
7479 }
7480
7481 outsize = PyUnicode_GET_LENGTH(rep);
7482 if (outsize != 1) {
7483 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7484 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7485 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7486 Py_DECREF(rep);
7487 goto error;
7488 }
7489 out = PyBytes_AS_STRING(*outbytes) + offset;
7490 }
7491 kind = PyUnicode_KIND(rep);
7492 data = PyUnicode_DATA(rep);
7493 for (i=0; i < outsize; i++) {
7494 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7495 if (ch > 127) {
7496 raise_encode_exception(&exc,
7497 encoding,
7498 startin, insize,
7499 startpos, startpos + charsize,
7500 "unable to encode error handler result to ASCII");
7501 Py_DECREF(rep);
7502 goto error;
7503 }
7504 *out = (unsigned char)ch;
7505 out++;
7506 }
7507 }
7508 Py_DECREF(rep);
7509 }
7510 /* write a NUL byte */
7511 *out = 0;
7512 outsize = out - PyBytes_AS_STRING(*outbytes);
7513 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7514 if (_PyBytes_Resize(outbytes, outsize) < 0)
7515 goto error;
7516 ret = 0;
7517
7518error:
7519 Py_XDECREF(encoding_obj);
7520 Py_XDECREF(errorHandler);
7521 Py_XDECREF(exc);
7522 return ret;
7523}
7524
7525/*
7526 * Encode a Unicode string to a Windows code page into a byte string.
7527 *
7528 * Returns consumed characters if succeed, or raise a WindowsError and returns
7529 * -1 on other error.
7530 */
7531static int
7532encode_code_page_chunk(UINT code_page, PyObject **outbytes,
7533 const Py_UNICODE *p, int size,
7534 const char* errors)
7535{
7536 int done;
7537
7538 if (size == 0) {
7539 if (*outbytes == NULL) {
7540 *outbytes = PyBytes_FromStringAndSize(NULL, 0);
7541 if (*outbytes == NULL)
7542 return -1;
7543 }
7544 return 0;
7545 }
7546
7547 done = encode_code_page_strict(code_page, outbytes, p, size, errors);
7548 if (done == -2)
7549 done = encode_code_page_errors(code_page, outbytes, p, size, errors);
7550 return done;
7551}
7552
7553static PyObject *
7554encode_code_page(int code_page,
7555 const Py_UNICODE *p, Py_ssize_t size,
7556 const char *errors)
7557{
7558 PyObject *outbytes = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007559 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007560
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 if (code_page < 0) {
7562 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7563 return NULL;
7564 }
7565
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007566#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007568 if (size > INT_MAX)
Victor Stinner3a50e702011-10-18 21:21:00 +02007569 ret = encode_code_page_chunk(code_page, &outbytes, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007570 else
7571#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007572 ret = encode_code_page_chunk(code_page, &outbytes, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007573
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007574 if (ret < 0) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007575 Py_XDECREF(outbytes);
Benjamin Peterson29060642009-01-31 22:14:21 +00007576 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007577 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007578
7579#ifdef NEED_RETRY
7580 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007581 p += INT_MAX;
7582 size -= INT_MAX;
7583 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007584 }
7585#endif
7586
Victor Stinner3a50e702011-10-18 21:21:00 +02007587 return outbytes;
7588}
7589
7590PyObject *
7591PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7592 Py_ssize_t size,
7593 const char *errors)
7594{
7595 return encode_code_page(CP_ACP, p, size, errors);
7596}
7597
7598PyObject *
7599PyUnicode_EncodeCodePage(int code_page,
7600 PyObject *unicode,
7601 const char *errors)
7602{
7603 const Py_UNICODE *p;
7604 Py_ssize_t size;
7605 p = PyUnicode_AsUnicodeAndSize(unicode, &size);
7606 if (p == NULL)
7607 return NULL;
7608 return encode_code_page(code_page, p, size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007609}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007610
Alexander Belopolsky40018472011-02-26 01:02:56 +00007611PyObject *
7612PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007613{
7614 if (!PyUnicode_Check(unicode)) {
7615 PyErr_BadArgument();
7616 return NULL;
7617 }
7618 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007619 PyUnicode_GET_SIZE(unicode),
7620 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007621}
7622
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007623#undef NEED_RETRY
7624
Victor Stinner99b95382011-07-04 14:23:54 +02007625#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007626
Guido van Rossumd57fd912000-03-10 22:53:23 +00007627/* --- Character Mapping Codec -------------------------------------------- */
7628
Alexander Belopolsky40018472011-02-26 01:02:56 +00007629PyObject *
7630PyUnicode_DecodeCharmap(const char *s,
7631 Py_ssize_t size,
7632 PyObject *mapping,
7633 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007634{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007635 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007636 Py_ssize_t startinpos;
7637 Py_ssize_t endinpos;
7638 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007639 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007640 PyUnicodeObject *v;
7641 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007642 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007643 PyObject *errorHandler = NULL;
7644 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007645 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007646 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007647
Guido van Rossumd57fd912000-03-10 22:53:23 +00007648 /* Default to Latin-1 */
7649 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007650 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007651
7652 v = _PyUnicode_New(size);
7653 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007654 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007655 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007656 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007657 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007658 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007659 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007660 mapstring = PyUnicode_AS_UNICODE(mapping);
7661 maplen = PyUnicode_GET_SIZE(mapping);
7662 while (s < e) {
7663 unsigned char ch = *s;
7664 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007665
Benjamin Peterson29060642009-01-31 22:14:21 +00007666 if (ch < maplen)
7667 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007668
Benjamin Peterson29060642009-01-31 22:14:21 +00007669 if (x == 0xfffe) {
7670 /* undefined mapping */
7671 outpos = p-PyUnicode_AS_UNICODE(v);
7672 startinpos = s-starts;
7673 endinpos = startinpos+1;
7674 if (unicode_decode_call_errorhandler(
7675 errors, &errorHandler,
7676 "charmap", "character maps to <undefined>",
7677 &starts, &e, &startinpos, &endinpos, &exc, &s,
7678 &v, &outpos, &p)) {
7679 goto onError;
7680 }
7681 continue;
7682 }
7683 *p++ = x;
7684 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007685 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007686 }
7687 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007688 while (s < e) {
7689 unsigned char ch = *s;
7690 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007691
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7693 w = PyLong_FromLong((long)ch);
7694 if (w == NULL)
7695 goto onError;
7696 x = PyObject_GetItem(mapping, w);
7697 Py_DECREF(w);
7698 if (x == NULL) {
7699 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7700 /* No mapping found means: mapping is undefined. */
7701 PyErr_Clear();
7702 x = Py_None;
7703 Py_INCREF(x);
7704 } else
7705 goto onError;
7706 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007707
Benjamin Peterson29060642009-01-31 22:14:21 +00007708 /* Apply mapping */
7709 if (PyLong_Check(x)) {
7710 long value = PyLong_AS_LONG(x);
7711 if (value < 0 || value > 65535) {
7712 PyErr_SetString(PyExc_TypeError,
7713 "character mapping must be in range(65536)");
7714 Py_DECREF(x);
7715 goto onError;
7716 }
7717 *p++ = (Py_UNICODE)value;
7718 }
7719 else if (x == Py_None) {
7720 /* undefined mapping */
7721 outpos = p-PyUnicode_AS_UNICODE(v);
7722 startinpos = s-starts;
7723 endinpos = startinpos+1;
7724 if (unicode_decode_call_errorhandler(
7725 errors, &errorHandler,
7726 "charmap", "character maps to <undefined>",
7727 &starts, &e, &startinpos, &endinpos, &exc, &s,
7728 &v, &outpos, &p)) {
7729 Py_DECREF(x);
7730 goto onError;
7731 }
7732 Py_DECREF(x);
7733 continue;
7734 }
7735 else if (PyUnicode_Check(x)) {
7736 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007737
Benjamin Peterson29060642009-01-31 22:14:21 +00007738 if (targetsize == 1)
7739 /* 1-1 mapping */
7740 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007741
Benjamin Peterson29060642009-01-31 22:14:21 +00007742 else if (targetsize > 1) {
7743 /* 1-n mapping */
7744 if (targetsize > extrachars) {
7745 /* resize first */
7746 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7747 Py_ssize_t needed = (targetsize - extrachars) + \
7748 (targetsize << 2);
7749 extrachars += needed;
7750 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007751 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007752 PyUnicode_GET_SIZE(v) + needed) < 0) {
7753 Py_DECREF(x);
7754 goto onError;
7755 }
7756 p = PyUnicode_AS_UNICODE(v) + oldpos;
7757 }
7758 Py_UNICODE_COPY(p,
7759 PyUnicode_AS_UNICODE(x),
7760 targetsize);
7761 p += targetsize;
7762 extrachars -= targetsize;
7763 }
7764 /* 1-0 mapping: skip the character */
7765 }
7766 else {
7767 /* wrong return value */
7768 PyErr_SetString(PyExc_TypeError,
7769 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007770 Py_DECREF(x);
7771 goto onError;
7772 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007773 Py_DECREF(x);
7774 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007775 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007776 }
7777 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007778 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007779 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007780 Py_XDECREF(errorHandler);
7781 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007782#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007783 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007784 Py_DECREF(v);
7785 return NULL;
7786 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007787#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007788 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007789 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007790
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007792 Py_XDECREF(errorHandler);
7793 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007794 Py_XDECREF(v);
7795 return NULL;
7796}
7797
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007798/* Charmap encoding: the lookup table */
7799
Alexander Belopolsky40018472011-02-26 01:02:56 +00007800struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007801 PyObject_HEAD
7802 unsigned char level1[32];
7803 int count2, count3;
7804 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007805};
7806
7807static PyObject*
7808encoding_map_size(PyObject *obj, PyObject* args)
7809{
7810 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007811 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007813}
7814
7815static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007816 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007817 PyDoc_STR("Return the size (in bytes) of this object") },
7818 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007819};
7820
7821static void
7822encoding_map_dealloc(PyObject* o)
7823{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007824 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007825}
7826
7827static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007828 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007829 "EncodingMap", /*tp_name*/
7830 sizeof(struct encoding_map), /*tp_basicsize*/
7831 0, /*tp_itemsize*/
7832 /* methods */
7833 encoding_map_dealloc, /*tp_dealloc*/
7834 0, /*tp_print*/
7835 0, /*tp_getattr*/
7836 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007837 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007838 0, /*tp_repr*/
7839 0, /*tp_as_number*/
7840 0, /*tp_as_sequence*/
7841 0, /*tp_as_mapping*/
7842 0, /*tp_hash*/
7843 0, /*tp_call*/
7844 0, /*tp_str*/
7845 0, /*tp_getattro*/
7846 0, /*tp_setattro*/
7847 0, /*tp_as_buffer*/
7848 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7849 0, /*tp_doc*/
7850 0, /*tp_traverse*/
7851 0, /*tp_clear*/
7852 0, /*tp_richcompare*/
7853 0, /*tp_weaklistoffset*/
7854 0, /*tp_iter*/
7855 0, /*tp_iternext*/
7856 encoding_map_methods, /*tp_methods*/
7857 0, /*tp_members*/
7858 0, /*tp_getset*/
7859 0, /*tp_base*/
7860 0, /*tp_dict*/
7861 0, /*tp_descr_get*/
7862 0, /*tp_descr_set*/
7863 0, /*tp_dictoffset*/
7864 0, /*tp_init*/
7865 0, /*tp_alloc*/
7866 0, /*tp_new*/
7867 0, /*tp_free*/
7868 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007869};
7870
7871PyObject*
7872PyUnicode_BuildEncodingMap(PyObject* string)
7873{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874 PyObject *result;
7875 struct encoding_map *mresult;
7876 int i;
7877 int need_dict = 0;
7878 unsigned char level1[32];
7879 unsigned char level2[512];
7880 unsigned char *mlevel1, *mlevel2, *mlevel3;
7881 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007882 int kind;
7883 void *data;
7884 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007886 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007887 PyErr_BadArgument();
7888 return NULL;
7889 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007890 kind = PyUnicode_KIND(string);
7891 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007892 memset(level1, 0xFF, sizeof level1);
7893 memset(level2, 0xFF, sizeof level2);
7894
7895 /* If there isn't a one-to-one mapping of NULL to \0,
7896 or if there are non-BMP characters, we need to use
7897 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007898 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007899 need_dict = 1;
7900 for (i = 1; i < 256; i++) {
7901 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007902 ch = PyUnicode_READ(kind, data, i);
7903 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007904 need_dict = 1;
7905 break;
7906 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007907 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007908 /* unmapped character */
7909 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007910 l1 = ch >> 11;
7911 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 if (level1[l1] == 0xFF)
7913 level1[l1] = count2++;
7914 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007915 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007916 }
7917
7918 if (count2 >= 0xFF || count3 >= 0xFF)
7919 need_dict = 1;
7920
7921 if (need_dict) {
7922 PyObject *result = PyDict_New();
7923 PyObject *key, *value;
7924 if (!result)
7925 return NULL;
7926 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007927 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007928 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007929 if (!key || !value)
7930 goto failed1;
7931 if (PyDict_SetItem(result, key, value) == -1)
7932 goto failed1;
7933 Py_DECREF(key);
7934 Py_DECREF(value);
7935 }
7936 return result;
7937 failed1:
7938 Py_XDECREF(key);
7939 Py_XDECREF(value);
7940 Py_DECREF(result);
7941 return NULL;
7942 }
7943
7944 /* Create a three-level trie */
7945 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7946 16*count2 + 128*count3 - 1);
7947 if (!result)
7948 return PyErr_NoMemory();
7949 PyObject_Init(result, &EncodingMapType);
7950 mresult = (struct encoding_map*)result;
7951 mresult->count2 = count2;
7952 mresult->count3 = count3;
7953 mlevel1 = mresult->level1;
7954 mlevel2 = mresult->level23;
7955 mlevel3 = mresult->level23 + 16*count2;
7956 memcpy(mlevel1, level1, 32);
7957 memset(mlevel2, 0xFF, 16*count2);
7958 memset(mlevel3, 0, 128*count3);
7959 count3 = 0;
7960 for (i = 1; i < 256; i++) {
7961 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007962 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007963 /* unmapped character */
7964 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007965 o1 = PyUnicode_READ(kind, data, i)>>11;
7966 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007967 i2 = 16*mlevel1[o1] + o2;
7968 if (mlevel2[i2] == 0xFF)
7969 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007970 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007971 i3 = 128*mlevel2[i2] + o3;
7972 mlevel3[i3] = i;
7973 }
7974 return result;
7975}
7976
7977static int
7978encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7979{
7980 struct encoding_map *map = (struct encoding_map*)mapping;
7981 int l1 = c>>11;
7982 int l2 = (c>>7) & 0xF;
7983 int l3 = c & 0x7F;
7984 int i;
7985
7986#ifdef Py_UNICODE_WIDE
7987 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007988 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007989 }
7990#endif
7991 if (c == 0)
7992 return 0;
7993 /* level 1*/
7994 i = map->level1[l1];
7995 if (i == 0xFF) {
7996 return -1;
7997 }
7998 /* level 2*/
7999 i = map->level23[16*i+l2];
8000 if (i == 0xFF) {
8001 return -1;
8002 }
8003 /* level 3 */
8004 i = map->level23[16*map->count2 + 128*i + l3];
8005 if (i == 0) {
8006 return -1;
8007 }
8008 return i;
8009}
8010
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008011/* Lookup the character ch in the mapping. If the character
8012 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008013 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008014static PyObject *
8015charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008016{
Christian Heimes217cfd12007-12-02 14:31:20 +00008017 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008018 PyObject *x;
8019
8020 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008021 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008022 x = PyObject_GetItem(mapping, w);
8023 Py_DECREF(w);
8024 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8026 /* No mapping found means: mapping is undefined. */
8027 PyErr_Clear();
8028 x = Py_None;
8029 Py_INCREF(x);
8030 return x;
8031 } else
8032 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008033 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008034 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008036 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008037 long value = PyLong_AS_LONG(x);
8038 if (value < 0 || value > 255) {
8039 PyErr_SetString(PyExc_TypeError,
8040 "character mapping must be in range(256)");
8041 Py_DECREF(x);
8042 return NULL;
8043 }
8044 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008045 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008046 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008047 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008048 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008049 /* wrong return value */
8050 PyErr_Format(PyExc_TypeError,
8051 "character mapping must return integer, bytes or None, not %.400s",
8052 x->ob_type->tp_name);
8053 Py_DECREF(x);
8054 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008055 }
8056}
8057
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008058static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008059charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008060{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008061 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8062 /* exponentially overallocate to minimize reallocations */
8063 if (requiredsize < 2*outsize)
8064 requiredsize = 2*outsize;
8065 if (_PyBytes_Resize(outobj, requiredsize))
8066 return -1;
8067 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008068}
8069
Benjamin Peterson14339b62009-01-31 16:36:08 +00008070typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008071 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008072} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008073/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008074 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075 space is available. Return a new reference to the object that
8076 was put in the output buffer, or Py_None, if the mapping was undefined
8077 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008078 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008079static charmapencode_result
8080charmapencode_output(Py_UNICODE c, PyObject *mapping,
8081 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008082{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008083 PyObject *rep;
8084 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008085 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008086
Christian Heimes90aa7642007-12-19 02:45:37 +00008087 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008089 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008090 if (res == -1)
8091 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008092 if (outsize<requiredsize)
8093 if (charmapencode_resize(outobj, outpos, requiredsize))
8094 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008095 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008096 outstart[(*outpos)++] = (char)res;
8097 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008098 }
8099
8100 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008101 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008103 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008104 Py_DECREF(rep);
8105 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008106 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 if (PyLong_Check(rep)) {
8108 Py_ssize_t requiredsize = *outpos+1;
8109 if (outsize<requiredsize)
8110 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8111 Py_DECREF(rep);
8112 return enc_EXCEPTION;
8113 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008114 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008115 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008116 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008117 else {
8118 const char *repchars = PyBytes_AS_STRING(rep);
8119 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8120 Py_ssize_t requiredsize = *outpos+repsize;
8121 if (outsize<requiredsize)
8122 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8123 Py_DECREF(rep);
8124 return enc_EXCEPTION;
8125 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008126 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 memcpy(outstart + *outpos, repchars, repsize);
8128 *outpos += repsize;
8129 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008130 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008131 Py_DECREF(rep);
8132 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133}
8134
8135/* handle an error in PyUnicode_EncodeCharmap
8136 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008137static int
8138charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00008139 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008140 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008141 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008142 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008143{
8144 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008145 Py_ssize_t repsize;
8146 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008147 Py_UNICODE *uni2;
8148 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008149 Py_ssize_t collstartpos = *inpos;
8150 Py_ssize_t collendpos = *inpos+1;
8151 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008152 char *encoding = "charmap";
8153 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008154 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008155
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008156 /* find all unencodable characters */
8157 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008158 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008159 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 int res = encoding_map_lookup(p[collendpos], mapping);
8161 if (res != -1)
8162 break;
8163 ++collendpos;
8164 continue;
8165 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008166
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 rep = charmapencode_lookup(p[collendpos], mapping);
8168 if (rep==NULL)
8169 return -1;
8170 else if (rep!=Py_None) {
8171 Py_DECREF(rep);
8172 break;
8173 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008174 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008176 }
8177 /* cache callback name lookup
8178 * (if not done yet, i.e. it's the first error) */
8179 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 if ((errors==NULL) || (!strcmp(errors, "strict")))
8181 *known_errorHandler = 1;
8182 else if (!strcmp(errors, "replace"))
8183 *known_errorHandler = 2;
8184 else if (!strcmp(errors, "ignore"))
8185 *known_errorHandler = 3;
8186 else if (!strcmp(errors, "xmlcharrefreplace"))
8187 *known_errorHandler = 4;
8188 else
8189 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190 }
8191 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192 case 1: /* strict */
8193 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8194 return -1;
8195 case 2: /* replace */
8196 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008197 x = charmapencode_output('?', mapping, res, respos);
8198 if (x==enc_EXCEPTION) {
8199 return -1;
8200 }
8201 else if (x==enc_FAILED) {
8202 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8203 return -1;
8204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008205 }
8206 /* fall through */
8207 case 3: /* ignore */
8208 *inpos = collendpos;
8209 break;
8210 case 4: /* xmlcharrefreplace */
8211 /* generate replacement (temporarily (mis)uses p) */
8212 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008213 char buffer[2+29+1+1];
8214 char *cp;
8215 sprintf(buffer, "&#%d;", (int)p[collpos]);
8216 for (cp = buffer; *cp; ++cp) {
8217 x = charmapencode_output(*cp, mapping, res, respos);
8218 if (x==enc_EXCEPTION)
8219 return -1;
8220 else if (x==enc_FAILED) {
8221 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8222 return -1;
8223 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008224 }
8225 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008226 *inpos = collendpos;
8227 break;
8228 default:
8229 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 encoding, reason, p, size, exceptionObject,
8231 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008233 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008234 if (PyBytes_Check(repunicode)) {
8235 /* Directly copy bytes result to output. */
8236 Py_ssize_t outsize = PyBytes_Size(*res);
8237 Py_ssize_t requiredsize;
8238 repsize = PyBytes_Size(repunicode);
8239 requiredsize = *respos + repsize;
8240 if (requiredsize > outsize)
8241 /* Make room for all additional bytes. */
8242 if (charmapencode_resize(res, respos, requiredsize)) {
8243 Py_DECREF(repunicode);
8244 return -1;
8245 }
8246 memcpy(PyBytes_AsString(*res) + *respos,
8247 PyBytes_AsString(repunicode), repsize);
8248 *respos += repsize;
8249 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008250 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008251 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008252 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008253 /* generate replacement */
8254 repsize = PyUnicode_GET_SIZE(repunicode);
8255 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008256 x = charmapencode_output(*uni2, mapping, res, respos);
8257 if (x==enc_EXCEPTION) {
8258 return -1;
8259 }
8260 else if (x==enc_FAILED) {
8261 Py_DECREF(repunicode);
8262 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8263 return -1;
8264 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008265 }
8266 *inpos = newpos;
8267 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008268 }
8269 return 0;
8270}
8271
Alexander Belopolsky40018472011-02-26 01:02:56 +00008272PyObject *
8273PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8274 Py_ssize_t size,
8275 PyObject *mapping,
8276 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008277{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008278 /* output object */
8279 PyObject *res = NULL;
8280 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008281 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008282 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008283 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284 PyObject *errorHandler = NULL;
8285 PyObject *exc = NULL;
8286 /* the following variable is used for caching string comparisons
8287 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8288 * 3=ignore, 4=xmlcharrefreplace */
8289 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290
8291 /* Default to Latin-1 */
8292 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008295 /* allocate enough for a simple encoding without
8296 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008297 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008298 if (res == NULL)
8299 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008300 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008301 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008302
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008303 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008304 /* try to encode it */
8305 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
8306 if (x==enc_EXCEPTION) /* error */
8307 goto onError;
8308 if (x==enc_FAILED) { /* unencodable character */
8309 if (charmap_encoding_error(p, size, &inpos, mapping,
8310 &exc,
8311 &known_errorHandler, &errorHandler, errors,
8312 &res, &respos)) {
8313 goto onError;
8314 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008315 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 else
8317 /* done with this character => adjust input position */
8318 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008320
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008321 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008322 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008323 if (_PyBytes_Resize(&res, respos) < 0)
8324 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008325
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008326 Py_XDECREF(exc);
8327 Py_XDECREF(errorHandler);
8328 return res;
8329
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008331 Py_XDECREF(res);
8332 Py_XDECREF(exc);
8333 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008334 return NULL;
8335}
8336
Alexander Belopolsky40018472011-02-26 01:02:56 +00008337PyObject *
8338PyUnicode_AsCharmapString(PyObject *unicode,
8339 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008340{
8341 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008342 PyErr_BadArgument();
8343 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008344 }
8345 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 PyUnicode_GET_SIZE(unicode),
8347 mapping,
8348 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008349}
8350
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008352static void
8353make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008354 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008355 Py_ssize_t startpos, Py_ssize_t endpos,
8356 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008357{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008359 *exceptionObject = _PyUnicodeTranslateError_Create(
8360 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008361 }
8362 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8364 goto onError;
8365 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8366 goto onError;
8367 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8368 goto onError;
8369 return;
8370 onError:
8371 Py_DECREF(*exceptionObject);
8372 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008373 }
8374}
8375
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008376/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008377static void
8378raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008379 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008380 Py_ssize_t startpos, Py_ssize_t endpos,
8381 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382{
8383 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008384 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008387}
8388
8389/* error handling callback helper:
8390 build arguments, call the callback and check the arguments,
8391 put the result into newpos and return the replacement string, which
8392 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008393static PyObject *
8394unicode_translate_call_errorhandler(const char *errors,
8395 PyObject **errorHandler,
8396 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008397 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008398 Py_ssize_t startpos, Py_ssize_t endpos,
8399 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008401 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008403 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 PyObject *restuple;
8405 PyObject *resunicode;
8406
8407 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008410 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008411 }
8412
8413 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008414 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008416 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008417
8418 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008419 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008420 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008422 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008423 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008424 Py_DECREF(restuple);
8425 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008426 }
8427 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008428 &resunicode, &i_newpos)) {
8429 Py_DECREF(restuple);
8430 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008431 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008432 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008433 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008434 else
8435 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008436 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008437 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8438 Py_DECREF(restuple);
8439 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008440 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008441 Py_INCREF(resunicode);
8442 Py_DECREF(restuple);
8443 return resunicode;
8444}
8445
8446/* Lookup the character ch in the mapping and put the result in result,
8447 which must be decrefed by the caller.
8448 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008449static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008450charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008451{
Christian Heimes217cfd12007-12-02 14:31:20 +00008452 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453 PyObject *x;
8454
8455 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008456 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008457 x = PyObject_GetItem(mapping, w);
8458 Py_DECREF(w);
8459 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8461 /* No mapping found means: use 1:1 mapping. */
8462 PyErr_Clear();
8463 *result = NULL;
8464 return 0;
8465 } else
8466 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467 }
8468 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 *result = x;
8470 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008472 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008473 long value = PyLong_AS_LONG(x);
8474 long max = PyUnicode_GetMax();
8475 if (value < 0 || value > max) {
8476 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008477 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 Py_DECREF(x);
8479 return -1;
8480 }
8481 *result = x;
8482 return 0;
8483 }
8484 else if (PyUnicode_Check(x)) {
8485 *result = x;
8486 return 0;
8487 }
8488 else {
8489 /* wrong return value */
8490 PyErr_SetString(PyExc_TypeError,
8491 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008492 Py_DECREF(x);
8493 return -1;
8494 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495}
8496/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 if not reallocate and adjust various state variables.
8498 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008499static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008503 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008504 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 /* exponentially overallocate to minimize reallocations */
8506 if (requiredsize < 2 * oldsize)
8507 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008508 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8509 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 }
8513 return 0;
8514}
8515/* lookup the character, put the result in the output string and adjust
8516 various state variables. Return a new reference to the object that
8517 was put in the output buffer in *result, or Py_None, if the mapping was
8518 undefined (in which case no character was written).
8519 The called must decref result.
8520 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008521static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008522charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8523 PyObject *mapping, Py_UCS4 **output,
8524 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008525 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8528 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008530 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008531 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008532 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008533 }
8534 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008535 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008536 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008537 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539 }
8540 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 Py_ssize_t repsize;
8542 if (PyUnicode_READY(*res) == -1)
8543 return -1;
8544 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 if (repsize==1) {
8546 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008547 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 }
8549 else if (repsize!=0) {
8550 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551 Py_ssize_t requiredsize = *opos +
8552 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008554 Py_ssize_t i;
8555 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008557 for(i = 0; i < repsize; i++)
8558 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008559 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008560 }
8561 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008563 return 0;
8564}
8565
Alexander Belopolsky40018472011-02-26 01:02:56 +00008566PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567_PyUnicode_TranslateCharmap(PyObject *input,
8568 PyObject *mapping,
8569 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008570{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 /* input object */
8572 char *idata;
8573 Py_ssize_t size, i;
8574 int kind;
8575 /* output buffer */
8576 Py_UCS4 *output = NULL;
8577 Py_ssize_t osize;
8578 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008580 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008581 char *reason = "character maps to <undefined>";
8582 PyObject *errorHandler = NULL;
8583 PyObject *exc = NULL;
8584 /* the following variable is used for caching string comparisons
8585 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8586 * 3=ignore, 4=xmlcharrefreplace */
8587 int known_errorHandler = -1;
8588
Guido van Rossumd57fd912000-03-10 22:53:23 +00008589 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 PyErr_BadArgument();
8591 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008592 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008594 if (PyUnicode_READY(input) == -1)
8595 return NULL;
8596 idata = (char*)PyUnicode_DATA(input);
8597 kind = PyUnicode_KIND(input);
8598 size = PyUnicode_GET_LENGTH(input);
8599 i = 0;
8600
8601 if (size == 0) {
8602 Py_INCREF(input);
8603 return input;
8604 }
8605
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008606 /* allocate enough for a simple 1:1 translation without
8607 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008608 osize = size;
8609 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8610 opos = 0;
8611 if (output == NULL) {
8612 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008615
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 /* try to encode it */
8618 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 if (charmaptranslate_output(input, i, mapping,
8620 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 Py_XDECREF(x);
8622 goto onError;
8623 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008624 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 else { /* untranslatable character */
8628 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8629 Py_ssize_t repsize;
8630 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 Py_ssize_t collstart = i;
8634 Py_ssize_t collend = i+1;
8635 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008636
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 while (collend < size) {
8639 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 goto onError;
8641 Py_XDECREF(x);
8642 if (x!=Py_None)
8643 break;
8644 ++collend;
8645 }
8646 /* cache callback name lookup
8647 * (if not done yet, i.e. it's the first error) */
8648 if (known_errorHandler==-1) {
8649 if ((errors==NULL) || (!strcmp(errors, "strict")))
8650 known_errorHandler = 1;
8651 else if (!strcmp(errors, "replace"))
8652 known_errorHandler = 2;
8653 else if (!strcmp(errors, "ignore"))
8654 known_errorHandler = 3;
8655 else if (!strcmp(errors, "xmlcharrefreplace"))
8656 known_errorHandler = 4;
8657 else
8658 known_errorHandler = 0;
8659 }
8660 switch (known_errorHandler) {
8661 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008662 raise_translate_exception(&exc, input, collstart,
8663 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008664 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008665 case 2: /* replace */
8666 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008667 for (coll = collstart; coll<collend; coll++)
8668 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008669 /* fall through */
8670 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008671 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008672 break;
8673 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 /* generate replacement (temporarily (mis)uses i) */
8675 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008676 char buffer[2+29+1+1];
8677 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8679 if (charmaptranslate_makespace(&output, &osize,
8680 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008681 goto onError;
8682 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008683 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008684 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008685 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008686 break;
8687 default:
8688 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689 reason, input, &exc,
8690 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008691 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 goto onError;
8693 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 repsize = PyUnicode_GET_LENGTH(repunicode);
8695 if (charmaptranslate_makespace(&output, &osize,
8696 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 Py_DECREF(repunicode);
8698 goto onError;
8699 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008700 for (uni2 = 0; repsize-->0; ++uni2)
8701 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8702 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008704 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008705 }
8706 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008707 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8708 if (!res)
8709 goto onError;
8710 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008711 Py_XDECREF(exc);
8712 Py_XDECREF(errorHandler);
8713 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008714
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008717 Py_XDECREF(exc);
8718 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008719 return NULL;
8720}
8721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722/* Deprecated. Use PyUnicode_Translate instead. */
8723PyObject *
8724PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8725 Py_ssize_t size,
8726 PyObject *mapping,
8727 const char *errors)
8728{
8729 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8730 if (!unicode)
8731 return NULL;
8732 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8733}
8734
Alexander Belopolsky40018472011-02-26 01:02:56 +00008735PyObject *
8736PyUnicode_Translate(PyObject *str,
8737 PyObject *mapping,
8738 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008739{
8740 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008741
Guido van Rossumd57fd912000-03-10 22:53:23 +00008742 str = PyUnicode_FromObject(str);
8743 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008744 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008746 Py_DECREF(str);
8747 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008748
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008750 Py_XDECREF(str);
8751 return NULL;
8752}
Tim Petersced69f82003-09-16 20:30:58 +00008753
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008754static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008755fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756{
8757 /* No need to call PyUnicode_READY(self) because this function is only
8758 called as a callback from fixup() which does it already. */
8759 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8760 const int kind = PyUnicode_KIND(self);
8761 void *data = PyUnicode_DATA(self);
8762 Py_UCS4 maxchar = 0, ch, fixed;
8763 Py_ssize_t i;
8764
8765 for (i = 0; i < len; ++i) {
8766 ch = PyUnicode_READ(kind, data, i);
8767 fixed = 0;
8768 if (ch > 127) {
8769 if (Py_UNICODE_ISSPACE(ch))
8770 fixed = ' ';
8771 else {
8772 const int decimal = Py_UNICODE_TODECIMAL(ch);
8773 if (decimal >= 0)
8774 fixed = '0' + decimal;
8775 }
8776 if (fixed != 0) {
8777 if (fixed > maxchar)
8778 maxchar = fixed;
8779 PyUnicode_WRITE(kind, data, i, fixed);
8780 }
8781 else if (ch > maxchar)
8782 maxchar = ch;
8783 }
8784 else if (ch > maxchar)
8785 maxchar = ch;
8786 }
8787
8788 return maxchar;
8789}
8790
8791PyObject *
8792_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8793{
8794 if (!PyUnicode_Check(unicode)) {
8795 PyErr_BadInternalCall();
8796 return NULL;
8797 }
8798 if (PyUnicode_READY(unicode) == -1)
8799 return NULL;
8800 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8801 /* If the string is already ASCII, just return the same string */
8802 Py_INCREF(unicode);
8803 return unicode;
8804 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008805 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806}
8807
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008808PyObject *
8809PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8810 Py_ssize_t length)
8811{
8812 PyObject *result;
8813 Py_UNICODE *p; /* write pointer into result */
8814 Py_ssize_t i;
8815 /* Copy to a new string */
8816 result = (PyObject *)_PyUnicode_New(length);
8817 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8818 if (result == NULL)
8819 return result;
8820 p = PyUnicode_AS_UNICODE(result);
8821 /* Iterate over code points */
8822 for (i = 0; i < length; i++) {
8823 Py_UNICODE ch =s[i];
8824 if (ch > 127) {
8825 int decimal = Py_UNICODE_TODECIMAL(ch);
8826 if (decimal >= 0)
8827 p[i] = '0' + decimal;
8828 }
8829 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008830#ifndef DONT_MAKE_RESULT_READY
8831 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832 Py_DECREF(result);
8833 return NULL;
8834 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008835#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008836 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008837 return result;
8838}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008839/* --- Decimal Encoder ---------------------------------------------------- */
8840
Alexander Belopolsky40018472011-02-26 01:02:56 +00008841int
8842PyUnicode_EncodeDecimal(Py_UNICODE *s,
8843 Py_ssize_t length,
8844 char *output,
8845 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008846{
8847 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008848 PyObject *errorHandler = NULL;
8849 PyObject *exc = NULL;
8850 const char *encoding = "decimal";
8851 const char *reason = "invalid decimal Unicode string";
8852 /* the following variable is used for caching string comparisons
8853 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8854 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008855
8856 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 PyErr_BadArgument();
8858 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008859 }
8860
8861 p = s;
8862 end = s + length;
8863 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008864 register Py_UNICODE ch = *p;
8865 int decimal;
8866 PyObject *repunicode;
8867 Py_ssize_t repsize;
8868 Py_ssize_t newpos;
8869 Py_UNICODE *uni2;
8870 Py_UNICODE *collstart;
8871 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008872
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008874 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008875 ++p;
8876 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008877 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008878 decimal = Py_UNICODE_TODECIMAL(ch);
8879 if (decimal >= 0) {
8880 *output++ = '0' + decimal;
8881 ++p;
8882 continue;
8883 }
8884 if (0 < ch && ch < 256) {
8885 *output++ = (char)ch;
8886 ++p;
8887 continue;
8888 }
8889 /* All other characters are considered unencodable */
8890 collstart = p;
8891 collend = p+1;
8892 while (collend < end) {
8893 if ((0 < *collend && *collend < 256) ||
8894 !Py_UNICODE_ISSPACE(*collend) ||
8895 Py_UNICODE_TODECIMAL(*collend))
8896 break;
8897 }
8898 /* cache callback name lookup
8899 * (if not done yet, i.e. it's the first error) */
8900 if (known_errorHandler==-1) {
8901 if ((errors==NULL) || (!strcmp(errors, "strict")))
8902 known_errorHandler = 1;
8903 else if (!strcmp(errors, "replace"))
8904 known_errorHandler = 2;
8905 else if (!strcmp(errors, "ignore"))
8906 known_errorHandler = 3;
8907 else if (!strcmp(errors, "xmlcharrefreplace"))
8908 known_errorHandler = 4;
8909 else
8910 known_errorHandler = 0;
8911 }
8912 switch (known_errorHandler) {
8913 case 1: /* strict */
8914 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8915 goto onError;
8916 case 2: /* replace */
8917 for (p = collstart; p < collend; ++p)
8918 *output++ = '?';
8919 /* fall through */
8920 case 3: /* ignore */
8921 p = collend;
8922 break;
8923 case 4: /* xmlcharrefreplace */
8924 /* generate replacement (temporarily (mis)uses p) */
8925 for (p = collstart; p < collend; ++p)
8926 output += sprintf(output, "&#%d;", (int)*p);
8927 p = collend;
8928 break;
8929 default:
8930 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8931 encoding, reason, s, length, &exc,
8932 collstart-s, collend-s, &newpos);
8933 if (repunicode == NULL)
8934 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008935 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008936 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008937 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8938 Py_DECREF(repunicode);
8939 goto onError;
8940 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008941 /* generate replacement */
8942 repsize = PyUnicode_GET_SIZE(repunicode);
8943 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8944 Py_UNICODE ch = *uni2;
8945 if (Py_UNICODE_ISSPACE(ch))
8946 *output++ = ' ';
8947 else {
8948 decimal = Py_UNICODE_TODECIMAL(ch);
8949 if (decimal >= 0)
8950 *output++ = '0' + decimal;
8951 else if (0 < ch && ch < 256)
8952 *output++ = (char)ch;
8953 else {
8954 Py_DECREF(repunicode);
8955 raise_encode_exception(&exc, encoding,
8956 s, length, collstart-s, collend-s, reason);
8957 goto onError;
8958 }
8959 }
8960 }
8961 p = s + newpos;
8962 Py_DECREF(repunicode);
8963 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008964 }
8965 /* 0-terminate the output string */
8966 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008967 Py_XDECREF(exc);
8968 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008969 return 0;
8970
Benjamin Peterson29060642009-01-31 22:14:21 +00008971 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008972 Py_XDECREF(exc);
8973 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008974 return -1;
8975}
8976
Guido van Rossumd57fd912000-03-10 22:53:23 +00008977/* --- Helpers ------------------------------------------------------------ */
8978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008979static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008980any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008981 Py_ssize_t start,
8982 Py_ssize_t end)
8983{
8984 int kind1, kind2, kind;
8985 void *buf1, *buf2;
8986 Py_ssize_t len1, len2, result;
8987
8988 kind1 = PyUnicode_KIND(s1);
8989 kind2 = PyUnicode_KIND(s2);
8990 kind = kind1 > kind2 ? kind1 : kind2;
8991 buf1 = PyUnicode_DATA(s1);
8992 buf2 = PyUnicode_DATA(s2);
8993 if (kind1 != kind)
8994 buf1 = _PyUnicode_AsKind(s1, kind);
8995 if (!buf1)
8996 return -2;
8997 if (kind2 != kind)
8998 buf2 = _PyUnicode_AsKind(s2, kind);
8999 if (!buf2) {
9000 if (kind1 != kind) PyMem_Free(buf1);
9001 return -2;
9002 }
9003 len1 = PyUnicode_GET_LENGTH(s1);
9004 len2 = PyUnicode_GET_LENGTH(s2);
9005
Victor Stinner794d5672011-10-10 03:21:36 +02009006 if (direction > 0) {
9007 switch(kind) {
9008 case PyUnicode_1BYTE_KIND:
9009 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9010 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9011 else
9012 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9013 break;
9014 case PyUnicode_2BYTE_KIND:
9015 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9016 break;
9017 case PyUnicode_4BYTE_KIND:
9018 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9019 break;
9020 default:
9021 assert(0); result = -2;
9022 }
9023 }
9024 else {
9025 switch(kind) {
9026 case PyUnicode_1BYTE_KIND:
9027 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9028 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9029 else
9030 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9031 break;
9032 case PyUnicode_2BYTE_KIND:
9033 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9034 break;
9035 case PyUnicode_4BYTE_KIND:
9036 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9037 break;
9038 default:
9039 assert(0); result = -2;
9040 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009041 }
9042
9043 if (kind1 != kind)
9044 PyMem_Free(buf1);
9045 if (kind2 != kind)
9046 PyMem_Free(buf2);
9047
9048 return result;
9049}
9050
9051Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009052_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 Py_ssize_t n_buffer,
9054 void *digits, Py_ssize_t n_digits,
9055 Py_ssize_t min_width,
9056 const char *grouping,
9057 const char *thousands_sep)
9058{
9059 switch(kind) {
9060 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009061 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9062 return _PyUnicode_ascii_InsertThousandsGrouping(
9063 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9064 min_width, grouping, thousands_sep);
9065 else
9066 return _PyUnicode_ucs1_InsertThousandsGrouping(
9067 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9068 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069 case PyUnicode_2BYTE_KIND:
9070 return _PyUnicode_ucs2_InsertThousandsGrouping(
9071 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9072 min_width, grouping, thousands_sep);
9073 case PyUnicode_4BYTE_KIND:
9074 return _PyUnicode_ucs4_InsertThousandsGrouping(
9075 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9076 min_width, grouping, thousands_sep);
9077 }
9078 assert(0);
9079 return -1;
9080}
9081
9082
Thomas Wouters477c8d52006-05-27 19:21:47 +00009083/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009084#define ADJUST_INDICES(start, end, len) \
9085 if (end > len) \
9086 end = len; \
9087 else if (end < 0) { \
9088 end += len; \
9089 if (end < 0) \
9090 end = 0; \
9091 } \
9092 if (start < 0) { \
9093 start += len; \
9094 if (start < 0) \
9095 start = 0; \
9096 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009097
Alexander Belopolsky40018472011-02-26 01:02:56 +00009098Py_ssize_t
9099PyUnicode_Count(PyObject *str,
9100 PyObject *substr,
9101 Py_ssize_t start,
9102 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009103{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009104 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009105 PyObject* str_obj;
9106 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009107 int kind1, kind2, kind;
9108 void *buf1 = NULL, *buf2 = NULL;
9109 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009110
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009111 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009112 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009113 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009114 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009115 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009116 Py_DECREF(str_obj);
9117 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009118 }
Tim Petersced69f82003-09-16 20:30:58 +00009119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 kind1 = PyUnicode_KIND(str_obj);
9121 kind2 = PyUnicode_KIND(sub_obj);
9122 kind = kind1 > kind2 ? kind1 : kind2;
9123 buf1 = PyUnicode_DATA(str_obj);
9124 if (kind1 != kind)
9125 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
9126 if (!buf1)
9127 goto onError;
9128 buf2 = PyUnicode_DATA(sub_obj);
9129 if (kind2 != kind)
9130 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
9131 if (!buf2)
9132 goto onError;
9133 len1 = PyUnicode_GET_LENGTH(str_obj);
9134 len2 = PyUnicode_GET_LENGTH(sub_obj);
9135
9136 ADJUST_INDICES(start, end, len1);
9137 switch(kind) {
9138 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009139 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9140 result = asciilib_count(
9141 ((Py_UCS1*)buf1) + start, end - start,
9142 buf2, len2, PY_SSIZE_T_MAX
9143 );
9144 else
9145 result = ucs1lib_count(
9146 ((Py_UCS1*)buf1) + start, end - start,
9147 buf2, len2, PY_SSIZE_T_MAX
9148 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009149 break;
9150 case PyUnicode_2BYTE_KIND:
9151 result = ucs2lib_count(
9152 ((Py_UCS2*)buf1) + start, end - start,
9153 buf2, len2, PY_SSIZE_T_MAX
9154 );
9155 break;
9156 case PyUnicode_4BYTE_KIND:
9157 result = ucs4lib_count(
9158 ((Py_UCS4*)buf1) + start, end - start,
9159 buf2, len2, PY_SSIZE_T_MAX
9160 );
9161 break;
9162 default:
9163 assert(0); result = 0;
9164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009165
9166 Py_DECREF(sub_obj);
9167 Py_DECREF(str_obj);
9168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 if (kind1 != kind)
9170 PyMem_Free(buf1);
9171 if (kind2 != kind)
9172 PyMem_Free(buf2);
9173
Guido van Rossumd57fd912000-03-10 22:53:23 +00009174 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175 onError:
9176 Py_DECREF(sub_obj);
9177 Py_DECREF(str_obj);
9178 if (kind1 != kind && buf1)
9179 PyMem_Free(buf1);
9180 if (kind2 != kind && buf2)
9181 PyMem_Free(buf2);
9182 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009183}
9184
Alexander Belopolsky40018472011-02-26 01:02:56 +00009185Py_ssize_t
9186PyUnicode_Find(PyObject *str,
9187 PyObject *sub,
9188 Py_ssize_t start,
9189 Py_ssize_t end,
9190 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009191{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009192 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009193
Guido van Rossumd57fd912000-03-10 22:53:23 +00009194 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009196 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009197 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009198 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009199 Py_DECREF(str);
9200 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009201 }
Tim Petersced69f82003-09-16 20:30:58 +00009202
Victor Stinner794d5672011-10-10 03:21:36 +02009203 result = any_find_slice(direction,
9204 str, sub, start, end
9205 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009206
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009208 Py_DECREF(sub);
9209
Guido van Rossumd57fd912000-03-10 22:53:23 +00009210 return result;
9211}
9212
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213Py_ssize_t
9214PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9215 Py_ssize_t start, Py_ssize_t end,
9216 int direction)
9217{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009219 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 if (PyUnicode_READY(str) == -1)
9221 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009222 if (start < 0 || end < 0) {
9223 PyErr_SetString(PyExc_IndexError, "string index out of range");
9224 return -2;
9225 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009226 if (end > PyUnicode_GET_LENGTH(str))
9227 end = PyUnicode_GET_LENGTH(str);
9228 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009229 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9230 kind, end-start, ch, direction);
9231 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009233 else
9234 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235}
9236
Alexander Belopolsky40018472011-02-26 01:02:56 +00009237static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009238tailmatch(PyObject *self,
9239 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009240 Py_ssize_t start,
9241 Py_ssize_t end,
9242 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009243{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 int kind_self;
9245 int kind_sub;
9246 void *data_self;
9247 void *data_sub;
9248 Py_ssize_t offset;
9249 Py_ssize_t i;
9250 Py_ssize_t end_sub;
9251
9252 if (PyUnicode_READY(self) == -1 ||
9253 PyUnicode_READY(substring) == -1)
9254 return 0;
9255
9256 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257 return 1;
9258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9260 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009262 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 kind_self = PyUnicode_KIND(self);
9265 data_self = PyUnicode_DATA(self);
9266 kind_sub = PyUnicode_KIND(substring);
9267 data_sub = PyUnicode_DATA(substring);
9268 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9269
9270 if (direction > 0)
9271 offset = end;
9272 else
9273 offset = start;
9274
9275 if (PyUnicode_READ(kind_self, data_self, offset) ==
9276 PyUnicode_READ(kind_sub, data_sub, 0) &&
9277 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9278 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9279 /* If both are of the same kind, memcmp is sufficient */
9280 if (kind_self == kind_sub) {
9281 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009282 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 data_sub,
9284 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009285 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286 }
9287 /* otherwise we have to compare each character by first accesing it */
9288 else {
9289 /* We do not need to compare 0 and len(substring)-1 because
9290 the if statement above ensured already that they are equal
9291 when we end up here. */
9292 // TODO: honor direction and do a forward or backwards search
9293 for (i = 1; i < end_sub; ++i) {
9294 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9295 PyUnicode_READ(kind_sub, data_sub, i))
9296 return 0;
9297 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009298 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009299 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 }
9301
9302 return 0;
9303}
9304
Alexander Belopolsky40018472011-02-26 01:02:56 +00009305Py_ssize_t
9306PyUnicode_Tailmatch(PyObject *str,
9307 PyObject *substr,
9308 Py_ssize_t start,
9309 Py_ssize_t end,
9310 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009311{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009312 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009313
Guido van Rossumd57fd912000-03-10 22:53:23 +00009314 str = PyUnicode_FromObject(str);
9315 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009316 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009317 substr = PyUnicode_FromObject(substr);
9318 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009319 Py_DECREF(str);
9320 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009321 }
Tim Petersced69f82003-09-16 20:30:58 +00009322
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009323 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009324 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325 Py_DECREF(str);
9326 Py_DECREF(substr);
9327 return result;
9328}
9329
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330/* Apply fixfct filter to the Unicode object self and return a
9331 reference to the modified object */
9332
Alexander Belopolsky40018472011-02-26 01:02:56 +00009333static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009334fixup(PyObject *self,
9335 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009336{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 PyObject *u;
9338 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 if (PyUnicode_READY(self) == -1)
9341 return NULL;
9342 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9343 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9344 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009346 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009349 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 /* fix functions return the new maximum character in a string,
9352 if the kind of the resulting unicode object does not change,
9353 everything is fine. Otherwise we need to change the string kind
9354 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009355 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 if (maxchar_new == 0)
9357 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9358 else if (maxchar_new <= 127)
9359 maxchar_new = 127;
9360 else if (maxchar_new <= 255)
9361 maxchar_new = 255;
9362 else if (maxchar_new <= 65535)
9363 maxchar_new = 65535;
9364 else
9365 maxchar_new = 1114111; /* 0x10ffff */
9366
9367 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 /* fixfct should return TRUE if it modified the buffer. If
9369 FALSE, return a reference to the original buffer instead
9370 (to save space, not time) */
9371 Py_INCREF(self);
9372 Py_DECREF(u);
9373 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 else if (maxchar_new == maxchar_old) {
9376 return u;
9377 }
9378 else {
9379 /* In case the maximum character changed, we need to
9380 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009381 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 if (v == NULL) {
9383 Py_DECREF(u);
9384 return NULL;
9385 }
9386 if (maxchar_new > maxchar_old) {
9387 /* If the maxchar increased so that the kind changed, not all
9388 characters are representable anymore and we need to fix the
9389 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009390 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009391 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9393 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009394 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009395 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009396 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397
9398 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009399 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 return v;
9401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009402}
9403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009405fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 /* No need to call PyUnicode_READY(self) because this function is only
9408 called as a callback from fixup() which does it already. */
9409 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9410 const int kind = PyUnicode_KIND(self);
9411 void *data = PyUnicode_DATA(self);
9412 int touched = 0;
9413 Py_UCS4 maxchar = 0;
9414 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 for (i = 0; i < len; ++i) {
9417 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9418 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9419 if (up != ch) {
9420 if (up > maxchar)
9421 maxchar = up;
9422 PyUnicode_WRITE(kind, data, i, up);
9423 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009424 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 else if (ch > maxchar)
9426 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009427 }
9428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 if (touched)
9430 return maxchar;
9431 else
9432 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433}
9434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009435static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009436fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009437{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9439 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9440 const int kind = PyUnicode_KIND(self);
9441 void *data = PyUnicode_DATA(self);
9442 int touched = 0;
9443 Py_UCS4 maxchar = 0;
9444 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 for(i = 0; i < len; ++i) {
9447 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9448 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9449 if (lo != ch) {
9450 if (lo > maxchar)
9451 maxchar = lo;
9452 PyUnicode_WRITE(kind, data, i, lo);
9453 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 else if (ch > maxchar)
9456 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457 }
9458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 if (touched)
9460 return maxchar;
9461 else
9462 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463}
9464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009466fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9469 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9470 const int kind = PyUnicode_KIND(self);
9471 void *data = PyUnicode_DATA(self);
9472 int touched = 0;
9473 Py_UCS4 maxchar = 0;
9474 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 for(i = 0; i < len; ++i) {
9477 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9478 Py_UCS4 nu = 0;
9479
9480 if (Py_UNICODE_ISUPPER(ch))
9481 nu = Py_UNICODE_TOLOWER(ch);
9482 else if (Py_UNICODE_ISLOWER(ch))
9483 nu = Py_UNICODE_TOUPPER(ch);
9484
9485 if (nu != 0) {
9486 if (nu > maxchar)
9487 maxchar = nu;
9488 PyUnicode_WRITE(kind, data, i, nu);
9489 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 else if (ch > maxchar)
9492 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493 }
9494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 if (touched)
9496 return maxchar;
9497 else
9498 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499}
9500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009502fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9505 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9506 const int kind = PyUnicode_KIND(self);
9507 void *data = PyUnicode_DATA(self);
9508 int touched = 0;
9509 Py_UCS4 maxchar = 0;
9510 Py_ssize_t i = 0;
9511 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009512
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009513 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009514 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515
9516 ch = PyUnicode_READ(kind, data, i);
9517 if (!Py_UNICODE_ISUPPER(ch)) {
9518 maxchar = Py_UNICODE_TOUPPER(ch);
9519 PyUnicode_WRITE(kind, data, i, maxchar);
9520 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 ++i;
9523 for(; i < len; ++i) {
9524 ch = PyUnicode_READ(kind, data, i);
9525 if (!Py_UNICODE_ISLOWER(ch)) {
9526 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9527 if (lo > maxchar)
9528 maxchar = lo;
9529 PyUnicode_WRITE(kind, data, i, lo);
9530 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009531 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532 else if (ch > maxchar)
9533 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009534 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535
9536 if (touched)
9537 return maxchar;
9538 else
9539 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540}
9541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009543fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9546 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9547 const int kind = PyUnicode_KIND(self);
9548 void *data = PyUnicode_DATA(self);
9549 Py_UCS4 maxchar = 0;
9550 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551 int previous_is_cased;
9552
9553 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 if (len == 1) {
9555 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9556 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9557 if (ti != ch) {
9558 PyUnicode_WRITE(kind, data, i, ti);
9559 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009560 }
9561 else
9562 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 for(; i < len; ++i) {
9566 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9567 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009568
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009571 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 nu = Py_UNICODE_TOTITLE(ch);
9573
9574 if (nu > maxchar)
9575 maxchar = nu;
9576 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009577
Benjamin Peterson29060642009-01-31 22:14:21 +00009578 if (Py_UNICODE_ISLOWER(ch) ||
9579 Py_UNICODE_ISUPPER(ch) ||
9580 Py_UNICODE_ISTITLE(ch))
9581 previous_is_cased = 1;
9582 else
9583 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009584 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009586}
9587
Tim Peters8ce9f162004-08-27 01:49:32 +00009588PyObject *
9589PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009592 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009594 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009595 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9596 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009597 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009599 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009601 int use_memcpy;
9602 unsigned char *res_data = NULL, *sep_data = NULL;
9603 PyObject *last_obj;
9604 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605
Tim Peters05eba1f2004-08-27 21:32:02 +00009606 fseq = PySequence_Fast(seq, "");
9607 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009608 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009609 }
9610
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009611 /* NOTE: the following code can't call back into Python code,
9612 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009613 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009614
Tim Peters05eba1f2004-08-27 21:32:02 +00009615 seqlen = PySequence_Fast_GET_SIZE(fseq);
9616 /* If empty sequence, return u"". */
9617 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009618 Py_DECREF(fseq);
9619 Py_INCREF(unicode_empty);
9620 res = unicode_empty;
9621 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009622 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009623
Tim Peters05eba1f2004-08-27 21:32:02 +00009624 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009625 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009626 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009627 if (seqlen == 1) {
9628 if (PyUnicode_CheckExact(items[0])) {
9629 res = items[0];
9630 Py_INCREF(res);
9631 Py_DECREF(fseq);
9632 return res;
9633 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009634 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009635 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009636 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009637 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009638 /* Set up sep and seplen */
9639 if (separator == NULL) {
9640 /* fall back to a blank space separator */
9641 sep = PyUnicode_FromOrdinal(' ');
9642 if (!sep)
9643 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009644 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009645 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009646 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009647 else {
9648 if (!PyUnicode_Check(separator)) {
9649 PyErr_Format(PyExc_TypeError,
9650 "separator: expected str instance,"
9651 " %.80s found",
9652 Py_TYPE(separator)->tp_name);
9653 goto onError;
9654 }
9655 if (PyUnicode_READY(separator))
9656 goto onError;
9657 sep = separator;
9658 seplen = PyUnicode_GET_LENGTH(separator);
9659 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9660 /* inc refcount to keep this code path symmetric with the
9661 above case of a blank separator */
9662 Py_INCREF(sep);
9663 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009664 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009665 }
9666
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009667 /* There are at least two things to join, or else we have a subclass
9668 * of str in the sequence.
9669 * Do a pre-pass to figure out the total amount of space we'll
9670 * need (sz), and see whether all argument are strings.
9671 */
9672 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009673#ifdef Py_DEBUG
9674 use_memcpy = 0;
9675#else
9676 use_memcpy = 1;
9677#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009678 for (i = 0; i < seqlen; i++) {
9679 const Py_ssize_t old_sz = sz;
9680 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009681 if (!PyUnicode_Check(item)) {
9682 PyErr_Format(PyExc_TypeError,
9683 "sequence item %zd: expected str instance,"
9684 " %.80s found",
9685 i, Py_TYPE(item)->tp_name);
9686 goto onError;
9687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009688 if (PyUnicode_READY(item) == -1)
9689 goto onError;
9690 sz += PyUnicode_GET_LENGTH(item);
9691 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009692 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 if (i != 0)
9694 sz += seplen;
9695 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9696 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009697 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009698 goto onError;
9699 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009700 if (use_memcpy && last_obj != NULL) {
9701 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9702 use_memcpy = 0;
9703 }
9704 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009705 }
Tim Petersced69f82003-09-16 20:30:58 +00009706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009708 if (res == NULL)
9709 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009710
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009711 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009712#ifdef Py_DEBUG
9713 use_memcpy = 0;
9714#else
9715 if (use_memcpy) {
9716 res_data = PyUnicode_1BYTE_DATA(res);
9717 kind = PyUnicode_KIND(res);
9718 if (seplen != 0)
9719 sep_data = PyUnicode_1BYTE_DATA(sep);
9720 }
9721#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009722 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009723 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009724 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009725 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009726 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 if (use_memcpy) {
9728 Py_MEMCPY(res_data,
9729 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009730 kind * seplen);
9731 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009732 }
9733 else {
9734 copy_characters(res, res_offset, sep, 0, seplen);
9735 res_offset += seplen;
9736 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009737 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009738 itemlen = PyUnicode_GET_LENGTH(item);
9739 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 if (use_memcpy) {
9741 Py_MEMCPY(res_data,
9742 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009743 kind * itemlen);
9744 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009745 }
9746 else {
9747 copy_characters(res, res_offset, item, 0, itemlen);
9748 res_offset += itemlen;
9749 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009750 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009751 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009752 if (use_memcpy)
9753 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009754 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009755 else
9756 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009757
Tim Peters05eba1f2004-08-27 21:32:02 +00009758 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009760 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009761 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762
Benjamin Peterson29060642009-01-31 22:14:21 +00009763 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009764 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009766 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009767 return NULL;
9768}
9769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770#define FILL(kind, data, value, start, length) \
9771 do { \
9772 Py_ssize_t i_ = 0; \
9773 assert(kind != PyUnicode_WCHAR_KIND); \
9774 switch ((kind)) { \
9775 case PyUnicode_1BYTE_KIND: { \
9776 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9777 memset(to_, (unsigned char)value, length); \
9778 break; \
9779 } \
9780 case PyUnicode_2BYTE_KIND: { \
9781 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9782 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9783 break; \
9784 } \
9785 default: { \
9786 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9787 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9788 break; \
9789 } \
9790 } \
9791 } while (0)
9792
Victor Stinner9310abb2011-10-05 00:59:23 +02009793static PyObject *
9794pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009795 Py_ssize_t left,
9796 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009799 PyObject *u;
9800 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009801 int kind;
9802 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803
9804 if (left < 0)
9805 left = 0;
9806 if (right < 0)
9807 right = 0;
9808
Tim Peters7a29bd52001-09-12 03:03:31 +00009809 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009810 Py_INCREF(self);
9811 return self;
9812 }
9813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9815 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009816 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9817 return NULL;
9818 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009819 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9820 if (fill > maxchar)
9821 maxchar = fill;
9822 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009823 if (!u)
9824 return NULL;
9825
9826 kind = PyUnicode_KIND(u);
9827 data = PyUnicode_DATA(u);
9828 if (left)
9829 FILL(kind, data, fill, 0, left);
9830 if (right)
9831 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009832 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009833 assert(_PyUnicode_CheckConsistency(u, 1));
9834 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009837
Alexander Belopolsky40018472011-02-26 01:02:56 +00009838PyObject *
9839PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009841 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009842
9843 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009845 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 switch(PyUnicode_KIND(string)) {
9848 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009849 if (PyUnicode_IS_ASCII(string))
9850 list = asciilib_splitlines(
9851 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9852 PyUnicode_GET_LENGTH(string), keepends);
9853 else
9854 list = ucs1lib_splitlines(
9855 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9856 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009857 break;
9858 case PyUnicode_2BYTE_KIND:
9859 list = ucs2lib_splitlines(
9860 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9861 PyUnicode_GET_LENGTH(string), keepends);
9862 break;
9863 case PyUnicode_4BYTE_KIND:
9864 list = ucs4lib_splitlines(
9865 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9866 PyUnicode_GET_LENGTH(string), keepends);
9867 break;
9868 default:
9869 assert(0);
9870 list = 0;
9871 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009872 Py_DECREF(string);
9873 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874}
9875
Alexander Belopolsky40018472011-02-26 01:02:56 +00009876static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009877split(PyObject *self,
9878 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009879 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 int kind1, kind2, kind;
9882 void *buf1, *buf2;
9883 Py_ssize_t len1, len2;
9884 PyObject* out;
9885
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009887 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 if (PyUnicode_READY(self) == -1)
9890 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 if (substring == NULL)
9893 switch(PyUnicode_KIND(self)) {
9894 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009895 if (PyUnicode_IS_ASCII(self))
9896 return asciilib_split_whitespace(
9897 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9898 PyUnicode_GET_LENGTH(self), maxcount
9899 );
9900 else
9901 return ucs1lib_split_whitespace(
9902 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9903 PyUnicode_GET_LENGTH(self), maxcount
9904 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 case PyUnicode_2BYTE_KIND:
9906 return ucs2lib_split_whitespace(
9907 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9908 PyUnicode_GET_LENGTH(self), maxcount
9909 );
9910 case PyUnicode_4BYTE_KIND:
9911 return ucs4lib_split_whitespace(
9912 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9913 PyUnicode_GET_LENGTH(self), maxcount
9914 );
9915 default:
9916 assert(0);
9917 return NULL;
9918 }
9919
9920 if (PyUnicode_READY(substring) == -1)
9921 return NULL;
9922
9923 kind1 = PyUnicode_KIND(self);
9924 kind2 = PyUnicode_KIND(substring);
9925 kind = kind1 > kind2 ? kind1 : kind2;
9926 buf1 = PyUnicode_DATA(self);
9927 buf2 = PyUnicode_DATA(substring);
9928 if (kind1 != kind)
9929 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9930 if (!buf1)
9931 return NULL;
9932 if (kind2 != kind)
9933 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9934 if (!buf2) {
9935 if (kind1 != kind) PyMem_Free(buf1);
9936 return NULL;
9937 }
9938 len1 = PyUnicode_GET_LENGTH(self);
9939 len2 = PyUnicode_GET_LENGTH(substring);
9940
9941 switch(kind) {
9942 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009943 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9944 out = asciilib_split(
9945 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9946 else
9947 out = ucs1lib_split(
9948 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 break;
9950 case PyUnicode_2BYTE_KIND:
9951 out = ucs2lib_split(
9952 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9953 break;
9954 case PyUnicode_4BYTE_KIND:
9955 out = ucs4lib_split(
9956 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9957 break;
9958 default:
9959 out = NULL;
9960 }
9961 if (kind1 != kind)
9962 PyMem_Free(buf1);
9963 if (kind2 != kind)
9964 PyMem_Free(buf2);
9965 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966}
9967
Alexander Belopolsky40018472011-02-26 01:02:56 +00009968static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009969rsplit(PyObject *self,
9970 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009971 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009972{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 int kind1, kind2, kind;
9974 void *buf1, *buf2;
9975 Py_ssize_t len1, len2;
9976 PyObject* out;
9977
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009978 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009979 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 if (PyUnicode_READY(self) == -1)
9982 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 if (substring == NULL)
9985 switch(PyUnicode_KIND(self)) {
9986 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009987 if (PyUnicode_IS_ASCII(self))
9988 return asciilib_rsplit_whitespace(
9989 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9990 PyUnicode_GET_LENGTH(self), maxcount
9991 );
9992 else
9993 return ucs1lib_rsplit_whitespace(
9994 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9995 PyUnicode_GET_LENGTH(self), maxcount
9996 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 case PyUnicode_2BYTE_KIND:
9998 return ucs2lib_rsplit_whitespace(
9999 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10000 PyUnicode_GET_LENGTH(self), maxcount
10001 );
10002 case PyUnicode_4BYTE_KIND:
10003 return ucs4lib_rsplit_whitespace(
10004 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10005 PyUnicode_GET_LENGTH(self), maxcount
10006 );
10007 default:
10008 assert(0);
10009 return NULL;
10010 }
10011
10012 if (PyUnicode_READY(substring) == -1)
10013 return NULL;
10014
10015 kind1 = PyUnicode_KIND(self);
10016 kind2 = PyUnicode_KIND(substring);
10017 kind = kind1 > kind2 ? kind1 : kind2;
10018 buf1 = PyUnicode_DATA(self);
10019 buf2 = PyUnicode_DATA(substring);
10020 if (kind1 != kind)
10021 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10022 if (!buf1)
10023 return NULL;
10024 if (kind2 != kind)
10025 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10026 if (!buf2) {
10027 if (kind1 != kind) PyMem_Free(buf1);
10028 return NULL;
10029 }
10030 len1 = PyUnicode_GET_LENGTH(self);
10031 len2 = PyUnicode_GET_LENGTH(substring);
10032
10033 switch(kind) {
10034 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010035 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10036 out = asciilib_rsplit(
10037 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10038 else
10039 out = ucs1lib_rsplit(
10040 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 break;
10042 case PyUnicode_2BYTE_KIND:
10043 out = ucs2lib_rsplit(
10044 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10045 break;
10046 case PyUnicode_4BYTE_KIND:
10047 out = ucs4lib_rsplit(
10048 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10049 break;
10050 default:
10051 out = NULL;
10052 }
10053 if (kind1 != kind)
10054 PyMem_Free(buf1);
10055 if (kind2 != kind)
10056 PyMem_Free(buf2);
10057 return out;
10058}
10059
10060static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010061anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10062 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063{
10064 switch(kind) {
10065 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010066 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10067 return asciilib_find(buf1, len1, buf2, len2, offset);
10068 else
10069 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 case PyUnicode_2BYTE_KIND:
10071 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10072 case PyUnicode_4BYTE_KIND:
10073 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10074 }
10075 assert(0);
10076 return -1;
10077}
10078
10079static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010080anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10081 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082{
10083 switch(kind) {
10084 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010085 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10086 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10087 else
10088 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 case PyUnicode_2BYTE_KIND:
10090 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10091 case PyUnicode_4BYTE_KIND:
10092 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10093 }
10094 assert(0);
10095 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010096}
10097
Alexander Belopolsky40018472011-02-26 01:02:56 +000010098static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099replace(PyObject *self, PyObject *str1,
10100 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 PyObject *u;
10103 char *sbuf = PyUnicode_DATA(self);
10104 char *buf1 = PyUnicode_DATA(str1);
10105 char *buf2 = PyUnicode_DATA(str2);
10106 int srelease = 0, release1 = 0, release2 = 0;
10107 int skind = PyUnicode_KIND(self);
10108 int kind1 = PyUnicode_KIND(str1);
10109 int kind2 = PyUnicode_KIND(str2);
10110 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10111 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10112 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010113 int mayshrink;
10114 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115
10116 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010117 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010119 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010120
Victor Stinner59de0ee2011-10-07 10:01:28 +020010121 if (str1 == str2)
10122 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 if (skind < kind1)
10124 /* substring too wide to be present */
10125 goto nothing;
10126
Victor Stinner49a0a212011-10-12 23:46:10 +020010127 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10128 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10129 /* Replacing str1 with str2 may cause a maxchar reduction in the
10130 result string. */
10131 mayshrink = (maxchar_str2 < maxchar);
10132 maxchar = Py_MAX(maxchar, maxchar_str2);
10133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010135 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010136 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010138 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010140 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010141 Py_UCS4 u1, u2;
10142 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010144 if (findchar(sbuf, PyUnicode_KIND(self),
10145 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010146 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010149 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010151 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 rkind = PyUnicode_KIND(u);
10153 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10154 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010155 if (--maxcount < 0)
10156 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010158 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010159 }
10160 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 int rkind = skind;
10162 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 if (kind1 < rkind) {
10165 /* widen substring */
10166 buf1 = _PyUnicode_AsKind(str1, rkind);
10167 if (!buf1) goto error;
10168 release1 = 1;
10169 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010170 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010171 if (i < 0)
10172 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 if (rkind > kind2) {
10174 /* widen replacement */
10175 buf2 = _PyUnicode_AsKind(str2, rkind);
10176 if (!buf2) goto error;
10177 release2 = 1;
10178 }
10179 else if (rkind < kind2) {
10180 /* widen self and buf1 */
10181 rkind = kind2;
10182 if (release1) PyMem_Free(buf1);
10183 sbuf = _PyUnicode_AsKind(self, rkind);
10184 if (!sbuf) goto error;
10185 srelease = 1;
10186 buf1 = _PyUnicode_AsKind(str1, rkind);
10187 if (!buf1) goto error;
10188 release1 = 1;
10189 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010190 u = PyUnicode_New(slen, maxchar);
10191 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010193 assert(PyUnicode_KIND(u) == rkind);
10194 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010195
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010196 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010197 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010198 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010200 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010202
10203 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010204 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010205 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010207 if (i == -1)
10208 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010209 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010211 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010213 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010215 }
10216 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 Py_ssize_t n, i, j, ires;
10218 Py_ssize_t product, new_size;
10219 int rkind = skind;
10220 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010223 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 buf1 = _PyUnicode_AsKind(str1, rkind);
10225 if (!buf1) goto error;
10226 release1 = 1;
10227 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010228 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229 if (n == 0)
10230 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010232 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 buf2 = _PyUnicode_AsKind(str2, rkind);
10234 if (!buf2) goto error;
10235 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010238 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 rkind = kind2;
10240 sbuf = _PyUnicode_AsKind(self, rkind);
10241 if (!sbuf) goto error;
10242 srelease = 1;
10243 if (release1) PyMem_Free(buf1);
10244 buf1 = _PyUnicode_AsKind(str1, rkind);
10245 if (!buf1) goto error;
10246 release1 = 1;
10247 }
10248 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10249 PyUnicode_GET_LENGTH(str1))); */
10250 product = n * (len2-len1);
10251 if ((product / (len2-len1)) != n) {
10252 PyErr_SetString(PyExc_OverflowError,
10253 "replace string is too long");
10254 goto error;
10255 }
10256 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010257 if (new_size == 0) {
10258 Py_INCREF(unicode_empty);
10259 u = unicode_empty;
10260 goto done;
10261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10263 PyErr_SetString(PyExc_OverflowError,
10264 "replace string is too long");
10265 goto error;
10266 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010267 u = PyUnicode_New(new_size, maxchar);
10268 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010270 assert(PyUnicode_KIND(u) == rkind);
10271 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 ires = i = 0;
10273 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010274 while (n-- > 0) {
10275 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010278 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010279 if (j == -1)
10280 break;
10281 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010283 memcpy(res + rkind * ires,
10284 sbuf + rkind * i,
10285 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010287 }
10288 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010290 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010292 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010294 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010298 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010299 memcpy(res + rkind * ires,
10300 sbuf + rkind * i,
10301 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010302 }
10303 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010304 /* interleave */
10305 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010306 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010308 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010310 if (--n <= 0)
10311 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010312 memcpy(res + rkind * ires,
10313 sbuf + rkind * i,
10314 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 ires++;
10316 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010317 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010318 memcpy(res + rkind * ires,
10319 sbuf + rkind * i,
10320 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010321 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010322 }
10323
10324 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010325 unicode_adjust_maxchar(&u);
10326 if (u == NULL)
10327 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010328 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010329
10330 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 if (srelease)
10332 PyMem_FREE(sbuf);
10333 if (release1)
10334 PyMem_FREE(buf1);
10335 if (release2)
10336 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010337 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010339
Benjamin Peterson29060642009-01-31 22:14:21 +000010340 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010341 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 if (srelease)
10343 PyMem_FREE(sbuf);
10344 if (release1)
10345 PyMem_FREE(buf1);
10346 if (release2)
10347 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010348 if (PyUnicode_CheckExact(self)) {
10349 Py_INCREF(self);
10350 return (PyObject *) self;
10351 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010352 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 error:
10354 if (srelease && sbuf)
10355 PyMem_FREE(sbuf);
10356 if (release1 && buf1)
10357 PyMem_FREE(buf1);
10358 if (release2 && buf2)
10359 PyMem_FREE(buf2);
10360 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361}
10362
10363/* --- Unicode Object Methods --------------------------------------------- */
10364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010365PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010366 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367\n\
10368Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010369characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370
10371static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010372unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374 return fixup(self, fixtitle);
10375}
10376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010377PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010378 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379\n\
10380Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010381have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382
10383static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010384unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386 return fixup(self, fixcapitalize);
10387}
10388
10389#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010390PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010391 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392\n\
10393Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010394normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395
10396static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010397unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398{
10399 PyObject *list;
10400 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010401 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403 /* Split into words */
10404 list = split(self, NULL, -1);
10405 if (!list)
10406 return NULL;
10407
10408 /* Capitalize each word */
10409 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010410 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010411 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412 if (item == NULL)
10413 goto onError;
10414 Py_DECREF(PyList_GET_ITEM(list, i));
10415 PyList_SET_ITEM(list, i, item);
10416 }
10417
10418 /* Join the words to form a new string */
10419 item = PyUnicode_Join(NULL, list);
10420
Benjamin Peterson29060642009-01-31 22:14:21 +000010421 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010422 Py_DECREF(list);
10423 return (PyObject *)item;
10424}
10425#endif
10426
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010427/* Argument converter. Coerces to a single unicode character */
10428
10429static int
10430convert_uc(PyObject *obj, void *addr)
10431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010433 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010434
Benjamin Peterson14339b62009-01-31 16:36:08 +000010435 uniobj = PyUnicode_FromObject(obj);
10436 if (uniobj == NULL) {
10437 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010438 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010439 return 0;
10440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010442 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010443 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010444 Py_DECREF(uniobj);
10445 return 0;
10446 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010448 Py_DECREF(uniobj);
10449 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010450}
10451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010452PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010453 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010454\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010455Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010456done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010457
10458static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010459unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010461 Py_ssize_t marg, left;
10462 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 Py_UCS4 fillchar = ' ';
10464
Victor Stinnere9a29352011-10-01 02:14:59 +020010465 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467
Victor Stinnere9a29352011-10-01 02:14:59 +020010468 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469 return NULL;
10470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472 Py_INCREF(self);
10473 return (PyObject*) self;
10474 }
10475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477 left = marg / 2 + (marg & width & 1);
10478
Victor Stinner9310abb2011-10-05 00:59:23 +020010479 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480}
10481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482/* This function assumes that str1 and str2 are readied by the caller. */
10483
Marc-André Lemburge5034372000-08-08 08:04:29 +000010484static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010485unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010486{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 int kind1, kind2;
10488 void *data1, *data2;
10489 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 kind1 = PyUnicode_KIND(str1);
10492 kind2 = PyUnicode_KIND(str2);
10493 data1 = PyUnicode_DATA(str1);
10494 data2 = PyUnicode_DATA(str2);
10495 len1 = PyUnicode_GET_LENGTH(str1);
10496 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 for (i = 0; i < len1 && i < len2; ++i) {
10499 Py_UCS4 c1, c2;
10500 c1 = PyUnicode_READ(kind1, data1, i);
10501 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010502
10503 if (c1 != c2)
10504 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010505 }
10506
10507 return (len1 < len2) ? -1 : (len1 != len2);
10508}
10509
Alexander Belopolsky40018472011-02-26 01:02:56 +000010510int
10511PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10514 if (PyUnicode_READY(left) == -1 ||
10515 PyUnicode_READY(right) == -1)
10516 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010517 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010518 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010519 PyErr_Format(PyExc_TypeError,
10520 "Can't compare %.100s and %.100s",
10521 left->ob_type->tp_name,
10522 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010523 return -1;
10524}
10525
Martin v. Löwis5b222132007-06-10 09:51:05 +000010526int
10527PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10528{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010529 Py_ssize_t i;
10530 int kind;
10531 void *data;
10532 Py_UCS4 chr;
10533
Victor Stinner910337b2011-10-03 03:20:16 +020010534 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010535 if (PyUnicode_READY(uni) == -1)
10536 return -1;
10537 kind = PyUnicode_KIND(uni);
10538 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010539 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010540 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10541 if (chr != str[i])
10542 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010543 /* This check keeps Python strings that end in '\0' from comparing equal
10544 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010545 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010546 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010547 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010548 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010549 return 0;
10550}
10551
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010552
Benjamin Peterson29060642009-01-31 22:14:21 +000010553#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010554 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010555
Alexander Belopolsky40018472011-02-26 01:02:56 +000010556PyObject *
10557PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010558{
10559 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010560
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010561 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10562 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 if (PyUnicode_READY(left) == -1 ||
10564 PyUnicode_READY(right) == -1)
10565 return NULL;
10566 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10567 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010568 if (op == Py_EQ) {
10569 Py_INCREF(Py_False);
10570 return Py_False;
10571 }
10572 if (op == Py_NE) {
10573 Py_INCREF(Py_True);
10574 return Py_True;
10575 }
10576 }
10577 if (left == right)
10578 result = 0;
10579 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010580 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010581
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010582 /* Convert the return value to a Boolean */
10583 switch (op) {
10584 case Py_EQ:
10585 v = TEST_COND(result == 0);
10586 break;
10587 case Py_NE:
10588 v = TEST_COND(result != 0);
10589 break;
10590 case Py_LE:
10591 v = TEST_COND(result <= 0);
10592 break;
10593 case Py_GE:
10594 v = TEST_COND(result >= 0);
10595 break;
10596 case Py_LT:
10597 v = TEST_COND(result == -1);
10598 break;
10599 case Py_GT:
10600 v = TEST_COND(result == 1);
10601 break;
10602 default:
10603 PyErr_BadArgument();
10604 return NULL;
10605 }
10606 Py_INCREF(v);
10607 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010608 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010609
Brian Curtindfc80e32011-08-10 20:28:54 -050010610 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010611}
10612
Alexander Belopolsky40018472011-02-26 01:02:56 +000010613int
10614PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010615{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010616 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 int kind1, kind2, kind;
10618 void *buf1, *buf2;
10619 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010620 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010621
10622 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010623 sub = PyUnicode_FromObject(element);
10624 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010625 PyErr_Format(PyExc_TypeError,
10626 "'in <string>' requires string as left operand, not %s",
10627 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010628 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010629 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 if (PyUnicode_READY(sub) == -1)
10631 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010632
Thomas Wouters477c8d52006-05-27 19:21:47 +000010633 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010634 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010635 Py_DECREF(sub);
10636 return -1;
10637 }
10638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010639 kind1 = PyUnicode_KIND(str);
10640 kind2 = PyUnicode_KIND(sub);
10641 kind = kind1 > kind2 ? kind1 : kind2;
10642 buf1 = PyUnicode_DATA(str);
10643 buf2 = PyUnicode_DATA(sub);
10644 if (kind1 != kind)
10645 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10646 if (!buf1) {
10647 Py_DECREF(sub);
10648 return -1;
10649 }
10650 if (kind2 != kind)
10651 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10652 if (!buf2) {
10653 Py_DECREF(sub);
10654 if (kind1 != kind) PyMem_Free(buf1);
10655 return -1;
10656 }
10657 len1 = PyUnicode_GET_LENGTH(str);
10658 len2 = PyUnicode_GET_LENGTH(sub);
10659
10660 switch(kind) {
10661 case PyUnicode_1BYTE_KIND:
10662 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10663 break;
10664 case PyUnicode_2BYTE_KIND:
10665 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10666 break;
10667 case PyUnicode_4BYTE_KIND:
10668 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10669 break;
10670 default:
10671 result = -1;
10672 assert(0);
10673 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010674
10675 Py_DECREF(str);
10676 Py_DECREF(sub);
10677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 if (kind1 != kind)
10679 PyMem_Free(buf1);
10680 if (kind2 != kind)
10681 PyMem_Free(buf2);
10682
Guido van Rossum403d68b2000-03-13 15:55:09 +000010683 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010684}
10685
Guido van Rossumd57fd912000-03-10 22:53:23 +000010686/* Concat to string or Unicode object giving a new Unicode object. */
10687
Alexander Belopolsky40018472011-02-26 01:02:56 +000010688PyObject *
10689PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010690{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010691 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010692 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010693
10694 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010695 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010696 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010697 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010699 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010700 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701
10702 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010703 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010704 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010705 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010706 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010707 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010708 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010709 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010710 }
10711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010712 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010713 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10714 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010715
Guido van Rossumd57fd912000-03-10 22:53:23 +000010716 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717 w = PyUnicode_New(
10718 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10719 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010720 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010721 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010722 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10723 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010724 Py_DECREF(u);
10725 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010726 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010727 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010728
Benjamin Peterson29060642009-01-31 22:14:21 +000010729 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730 Py_XDECREF(u);
10731 Py_XDECREF(v);
10732 return NULL;
10733}
10734
Victor Stinnerb0923652011-10-04 01:17:31 +020010735static void
10736unicode_append_inplace(PyObject **p_left, PyObject *right)
10737{
10738 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010739
10740 assert(PyUnicode_IS_READY(*p_left));
10741 assert(PyUnicode_IS_READY(right));
10742
10743 left_len = PyUnicode_GET_LENGTH(*p_left);
10744 right_len = PyUnicode_GET_LENGTH(right);
10745 if (left_len > PY_SSIZE_T_MAX - right_len) {
10746 PyErr_SetString(PyExc_OverflowError,
10747 "strings are too large to concat");
10748 goto error;
10749 }
10750 new_len = left_len + right_len;
10751
10752 /* Now we own the last reference to 'left', so we can resize it
10753 * in-place.
10754 */
10755 if (unicode_resize(p_left, new_len) != 0) {
10756 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10757 * deallocated so it cannot be put back into
10758 * 'variable'. The MemoryError is raised when there
10759 * is no value in 'variable', which might (very
10760 * remotely) be a cause of incompatibilities.
10761 */
10762 goto error;
10763 }
10764 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010765 copy_characters(*p_left, left_len, right, 0, right_len);
10766 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010767 return;
10768
10769error:
10770 Py_DECREF(*p_left);
10771 *p_left = NULL;
10772}
10773
Walter Dörwald1ab83302007-05-18 17:15:44 +000010774void
Victor Stinner23e56682011-10-03 03:54:37 +020010775PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010776{
Victor Stinner23e56682011-10-03 03:54:37 +020010777 PyObject *left, *res;
10778
10779 if (p_left == NULL) {
10780 if (!PyErr_Occurred())
10781 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010782 return;
10783 }
Victor Stinner23e56682011-10-03 03:54:37 +020010784 left = *p_left;
10785 if (right == NULL || !PyUnicode_Check(left)) {
10786 if (!PyErr_Occurred())
10787 PyErr_BadInternalCall();
10788 goto error;
10789 }
10790
Victor Stinnere1335c72011-10-04 20:53:03 +020010791 if (PyUnicode_READY(left))
10792 goto error;
10793 if (PyUnicode_READY(right))
10794 goto error;
10795
Victor Stinner23e56682011-10-03 03:54:37 +020010796 if (PyUnicode_CheckExact(left) && left != unicode_empty
10797 && PyUnicode_CheckExact(right) && right != unicode_empty
10798 && unicode_resizable(left)
10799 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10800 || _PyUnicode_WSTR(left) != NULL))
10801 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010802 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10803 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010804 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010805 not so different than duplicating the string. */
10806 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010807 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010808 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010809 if (p_left != NULL)
10810 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010811 return;
10812 }
10813 }
10814
10815 res = PyUnicode_Concat(left, right);
10816 if (res == NULL)
10817 goto error;
10818 Py_DECREF(left);
10819 *p_left = res;
10820 return;
10821
10822error:
10823 Py_DECREF(*p_left);
10824 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010825}
10826
10827void
10828PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10829{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010830 PyUnicode_Append(pleft, right);
10831 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010832}
10833
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010834PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010835 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010836\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010837Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010838string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010839interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010840
10841static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010842unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010843{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010844 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010845 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010846 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010848 int kind1, kind2, kind;
10849 void *buf1, *buf2;
10850 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010851
Jesus Ceaac451502011-04-20 17:09:23 +020010852 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10853 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010854 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010855
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010856 kind1 = PyUnicode_KIND(self);
10857 kind2 = PyUnicode_KIND(substring);
10858 kind = kind1 > kind2 ? kind1 : kind2;
10859 buf1 = PyUnicode_DATA(self);
10860 buf2 = PyUnicode_DATA(substring);
10861 if (kind1 != kind)
10862 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10863 if (!buf1) {
10864 Py_DECREF(substring);
10865 return NULL;
10866 }
10867 if (kind2 != kind)
10868 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10869 if (!buf2) {
10870 Py_DECREF(substring);
10871 if (kind1 != kind) PyMem_Free(buf1);
10872 return NULL;
10873 }
10874 len1 = PyUnicode_GET_LENGTH(self);
10875 len2 = PyUnicode_GET_LENGTH(substring);
10876
10877 ADJUST_INDICES(start, end, len1);
10878 switch(kind) {
10879 case PyUnicode_1BYTE_KIND:
10880 iresult = ucs1lib_count(
10881 ((Py_UCS1*)buf1) + start, end - start,
10882 buf2, len2, PY_SSIZE_T_MAX
10883 );
10884 break;
10885 case PyUnicode_2BYTE_KIND:
10886 iresult = ucs2lib_count(
10887 ((Py_UCS2*)buf1) + start, end - start,
10888 buf2, len2, PY_SSIZE_T_MAX
10889 );
10890 break;
10891 case PyUnicode_4BYTE_KIND:
10892 iresult = ucs4lib_count(
10893 ((Py_UCS4*)buf1) + start, end - start,
10894 buf2, len2, PY_SSIZE_T_MAX
10895 );
10896 break;
10897 default:
10898 assert(0); iresult = 0;
10899 }
10900
10901 result = PyLong_FromSsize_t(iresult);
10902
10903 if (kind1 != kind)
10904 PyMem_Free(buf1);
10905 if (kind2 != kind)
10906 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010907
10908 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010909
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910 return result;
10911}
10912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010913PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010914 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010916Encode S using the codec registered for encoding. Default encoding\n\
10917is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010918handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010919a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10920'xmlcharrefreplace' as well as any other name registered with\n\
10921codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010922
10923static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010924unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010926 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927 char *encoding = NULL;
10928 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010929
Benjamin Peterson308d6372009-09-18 21:42:35 +000010930 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10931 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010933 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010934}
10935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010936PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010937 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938\n\
10939Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010940If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941
10942static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010943unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 Py_ssize_t i, j, line_pos, src_len, incr;
10946 Py_UCS4 ch;
10947 PyObject *u;
10948 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010950 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010951 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952
10953 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010954 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955
Antoine Pitrou22425222011-10-04 19:10:51 +020010956 if (PyUnicode_READY(self) == -1)
10957 return NULL;
10958
Thomas Wouters7e474022000-07-16 12:04:32 +000010959 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010960 src_len = PyUnicode_GET_LENGTH(self);
10961 i = j = line_pos = 0;
10962 kind = PyUnicode_KIND(self);
10963 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010964 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010965 for (; i < src_len; i++) {
10966 ch = PyUnicode_READ(kind, src_data, i);
10967 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010968 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010969 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010970 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010971 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010972 goto overflow;
10973 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010974 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010975 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010976 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010977 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010978 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010979 goto overflow;
10980 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010982 if (ch == '\n' || ch == '\r')
10983 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010984 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010985 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010986 if (!found && PyUnicode_CheckExact(self)) {
10987 Py_INCREF((PyObject *) self);
10988 return (PyObject *) self;
10989 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010990
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010992 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993 if (!u)
10994 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010995 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996
Antoine Pitroue71d5742011-10-04 15:55:09 +020010997 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998
Antoine Pitroue71d5742011-10-04 15:55:09 +020010999 for (; i < src_len; i++) {
11000 ch = PyUnicode_READ(kind, src_data, i);
11001 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011002 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011003 incr = tabsize - (line_pos % tabsize);
11004 line_pos += incr;
11005 while (incr--) {
11006 PyUnicode_WRITE(kind, dest_data, j, ' ');
11007 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011008 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011009 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011010 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011011 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011012 line_pos++;
11013 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011014 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011015 if (ch == '\n' || ch == '\r')
11016 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011018 }
11019 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011020#ifndef DONT_MAKE_RESULT_READY
11021 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 Py_DECREF(u);
11023 return NULL;
11024 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011025#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011026 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011028
Antoine Pitroue71d5742011-10-04 15:55:09 +020011029 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011030 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11031 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032}
11033
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011034PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011035 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011036\n\
11037Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011038such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039arguments start and end are interpreted as in slice notation.\n\
11040\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011041Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011042
11043static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011044unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011046 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011047 Py_ssize_t start;
11048 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011049 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050
Jesus Ceaac451502011-04-20 17:09:23 +020011051 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11052 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011053 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011055 if (PyUnicode_READY(self) == -1)
11056 return NULL;
11057 if (PyUnicode_READY(substring) == -1)
11058 return NULL;
11059
Victor Stinner794d5672011-10-10 03:21:36 +020011060 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011061 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011062 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063
11064 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011066 if (result == -2)
11067 return NULL;
11068
Christian Heimes217cfd12007-12-02 14:31:20 +000011069 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070}
11071
11072static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011073unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011074{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011075 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11076 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011077 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011078 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079}
11080
Guido van Rossumc2504932007-09-18 19:42:40 +000011081/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011082 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011083static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011084unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085{
Guido van Rossumc2504932007-09-18 19:42:40 +000011086 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011087 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011089 if (_PyUnicode_HASH(self) != -1)
11090 return _PyUnicode_HASH(self);
11091 if (PyUnicode_READY(self) == -1)
11092 return -1;
11093 len = PyUnicode_GET_LENGTH(self);
11094
11095 /* The hash function as a macro, gets expanded three times below. */
11096#define HASH(P) \
11097 x = (Py_uhash_t)*P << 7; \
11098 while (--len >= 0) \
11099 x = (1000003*x) ^ (Py_uhash_t)*P++;
11100
11101 switch (PyUnicode_KIND(self)) {
11102 case PyUnicode_1BYTE_KIND: {
11103 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11104 HASH(c);
11105 break;
11106 }
11107 case PyUnicode_2BYTE_KIND: {
11108 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11109 HASH(s);
11110 break;
11111 }
11112 default: {
11113 Py_UCS4 *l;
11114 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11115 "Impossible switch case in unicode_hash");
11116 l = PyUnicode_4BYTE_DATA(self);
11117 HASH(l);
11118 break;
11119 }
11120 }
11121 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11122
Guido van Rossumc2504932007-09-18 19:42:40 +000011123 if (x == -1)
11124 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011125 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011126 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011127}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011131 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011133Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134
11135static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011136unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011138 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011139 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011140 Py_ssize_t start;
11141 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142
Jesus Ceaac451502011-04-20 17:09:23 +020011143 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11144 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (PyUnicode_READY(self) == -1)
11148 return NULL;
11149 if (PyUnicode_READY(substring) == -1)
11150 return NULL;
11151
Victor Stinner794d5672011-10-10 03:21:36 +020011152 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011153 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011154 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155
11156 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 if (result == -2)
11159 return NULL;
11160
Guido van Rossumd57fd912000-03-10 22:53:23 +000011161 if (result < 0) {
11162 PyErr_SetString(PyExc_ValueError, "substring not found");
11163 return NULL;
11164 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011165
Christian Heimes217cfd12007-12-02 14:31:20 +000011166 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011167}
11168
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011169PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011170 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011171\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011172Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011173at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174
11175static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011176unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 Py_ssize_t i, length;
11179 int kind;
11180 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181 int cased;
11182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (PyUnicode_READY(self) == -1)
11184 return NULL;
11185 length = PyUnicode_GET_LENGTH(self);
11186 kind = PyUnicode_KIND(self);
11187 data = PyUnicode_DATA(self);
11188
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 if (length == 1)
11191 return PyBool_FromLong(
11192 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011193
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011194 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011196 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011197
Guido van Rossumd57fd912000-03-10 22:53:23 +000011198 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011199 for (i = 0; i < length; i++) {
11200 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011201
Benjamin Peterson29060642009-01-31 22:14:21 +000011202 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11203 return PyBool_FromLong(0);
11204 else if (!cased && Py_UNICODE_ISLOWER(ch))
11205 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011207 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208}
11209
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011210PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011211 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011212\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011213Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011214at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215
11216static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011217unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011219 Py_ssize_t i, length;
11220 int kind;
11221 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222 int cased;
11223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011224 if (PyUnicode_READY(self) == -1)
11225 return NULL;
11226 length = PyUnicode_GET_LENGTH(self);
11227 kind = PyUnicode_KIND(self);
11228 data = PyUnicode_DATA(self);
11229
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 if (length == 1)
11232 return PyBool_FromLong(
11233 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011235 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011236 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011237 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011238
Guido van Rossumd57fd912000-03-10 22:53:23 +000011239 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011240 for (i = 0; i < length; i++) {
11241 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011242
Benjamin Peterson29060642009-01-31 22:14:21 +000011243 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11244 return PyBool_FromLong(0);
11245 else if (!cased && Py_UNICODE_ISUPPER(ch))
11246 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011248 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249}
11250
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011251PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011252 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011254Return True if S is a titlecased string and there is at least one\n\
11255character in S, i.e. upper- and titlecase characters may only\n\
11256follow uncased characters and lowercase characters only cased ones.\n\
11257Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011258
11259static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011260unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011262 Py_ssize_t i, length;
11263 int kind;
11264 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011265 int cased, previous_is_cased;
11266
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 if (PyUnicode_READY(self) == -1)
11268 return NULL;
11269 length = PyUnicode_GET_LENGTH(self);
11270 kind = PyUnicode_KIND(self);
11271 data = PyUnicode_DATA(self);
11272
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 if (length == 1) {
11275 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11276 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11277 (Py_UNICODE_ISUPPER(ch) != 0));
11278 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011280 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011281 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011282 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011283
Guido van Rossumd57fd912000-03-10 22:53:23 +000011284 cased = 0;
11285 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011286 for (i = 0; i < length; i++) {
11287 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011288
Benjamin Peterson29060642009-01-31 22:14:21 +000011289 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11290 if (previous_is_cased)
11291 return PyBool_FromLong(0);
11292 previous_is_cased = 1;
11293 cased = 1;
11294 }
11295 else if (Py_UNICODE_ISLOWER(ch)) {
11296 if (!previous_is_cased)
11297 return PyBool_FromLong(0);
11298 previous_is_cased = 1;
11299 cased = 1;
11300 }
11301 else
11302 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011303 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011304 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305}
11306
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011307PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011308 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011310Return True if all characters in S are whitespace\n\
11311and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312
11313static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011314unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011315{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011316 Py_ssize_t i, length;
11317 int kind;
11318 void *data;
11319
11320 if (PyUnicode_READY(self) == -1)
11321 return NULL;
11322 length = PyUnicode_GET_LENGTH(self);
11323 kind = PyUnicode_KIND(self);
11324 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011325
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011327 if (length == 1)
11328 return PyBool_FromLong(
11329 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011330
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011331 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011332 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011334
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 for (i = 0; i < length; i++) {
11336 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011337 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011338 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011340 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341}
11342
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011343PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011344 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011345\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011346Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011347and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011348
11349static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011350unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 Py_ssize_t i, length;
11353 int kind;
11354 void *data;
11355
11356 if (PyUnicode_READY(self) == -1)
11357 return NULL;
11358 length = PyUnicode_GET_LENGTH(self);
11359 kind = PyUnicode_KIND(self);
11360 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011361
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011362 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 if (length == 1)
11364 return PyBool_FromLong(
11365 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011366
11367 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011369 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011370
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 for (i = 0; i < length; i++) {
11372 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011374 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011375 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011376}
11377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011378PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011379 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011380\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011381Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011382and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011383
11384static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011385unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011386{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 int kind;
11388 void *data;
11389 Py_ssize_t len, i;
11390
11391 if (PyUnicode_READY(self) == -1)
11392 return NULL;
11393
11394 kind = PyUnicode_KIND(self);
11395 data = PyUnicode_DATA(self);
11396 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011397
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011398 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011399 if (len == 1) {
11400 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11401 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11402 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011403
11404 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011406 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011407
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408 for (i = 0; i < len; i++) {
11409 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011410 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011411 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011412 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011413 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011414}
11415
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011416PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011419Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011420False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
11422static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011423unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011424{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 Py_ssize_t i, length;
11426 int kind;
11427 void *data;
11428
11429 if (PyUnicode_READY(self) == -1)
11430 return NULL;
11431 length = PyUnicode_GET_LENGTH(self);
11432 kind = PyUnicode_KIND(self);
11433 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
Guido van Rossumd57fd912000-03-10 22:53:23 +000011435 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011436 if (length == 1)
11437 return PyBool_FromLong(
11438 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011439
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011440 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011442 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 for (i = 0; i < length; i++) {
11445 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011446 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011448 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449}
11450
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011451PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011453\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011454Return True if all characters in S are digits\n\
11455and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456
11457static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011458unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011460 Py_ssize_t i, length;
11461 int kind;
11462 void *data;
11463
11464 if (PyUnicode_READY(self) == -1)
11465 return NULL;
11466 length = PyUnicode_GET_LENGTH(self);
11467 kind = PyUnicode_KIND(self);
11468 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011469
Guido van Rossumd57fd912000-03-10 22:53:23 +000011470 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011471 if (length == 1) {
11472 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11473 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11474 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011476 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011478 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011480 for (i = 0; i < length; i++) {
11481 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011482 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011483 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011484 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485}
11486
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011487PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011489\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011490Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011491False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011492
11493static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011494unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011495{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 Py_ssize_t i, length;
11497 int kind;
11498 void *data;
11499
11500 if (PyUnicode_READY(self) == -1)
11501 return NULL;
11502 length = PyUnicode_GET_LENGTH(self);
11503 kind = PyUnicode_KIND(self);
11504 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011505
Guido van Rossumd57fd912000-03-10 22:53:23 +000011506 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 if (length == 1)
11508 return PyBool_FromLong(
11509 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011511 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011512 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011513 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 for (i = 0; i < length; i++) {
11516 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011519 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520}
11521
Martin v. Löwis47383402007-08-15 07:32:56 +000011522int
11523PyUnicode_IsIdentifier(PyObject *self)
11524{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 int kind;
11526 void *data;
11527 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011528 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011529
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 if (PyUnicode_READY(self) == -1) {
11531 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011532 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 }
11534
11535 /* Special case for empty strings */
11536 if (PyUnicode_GET_LENGTH(self) == 0)
11537 return 0;
11538 kind = PyUnicode_KIND(self);
11539 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011540
11541 /* PEP 3131 says that the first character must be in
11542 XID_Start and subsequent characters in XID_Continue,
11543 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011544 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011545 letters, digits, underscore). However, given the current
11546 definition of XID_Start and XID_Continue, it is sufficient
11547 to check just for these, except that _ must be allowed
11548 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011550 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011551 return 0;
11552
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011553 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011554 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011555 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011556 return 1;
11557}
11558
11559PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011560 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011561\n\
11562Return True if S is a valid identifier according\n\
11563to the language definition.");
11564
11565static PyObject*
11566unicode_isidentifier(PyObject *self)
11567{
11568 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11569}
11570
Georg Brandl559e5d72008-06-11 18:37:52 +000011571PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011572 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011573\n\
11574Return True if all characters in S are considered\n\
11575printable in repr() or S is empty, False otherwise.");
11576
11577static PyObject*
11578unicode_isprintable(PyObject *self)
11579{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011580 Py_ssize_t i, length;
11581 int kind;
11582 void *data;
11583
11584 if (PyUnicode_READY(self) == -1)
11585 return NULL;
11586 length = PyUnicode_GET_LENGTH(self);
11587 kind = PyUnicode_KIND(self);
11588 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011589
11590 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 if (length == 1)
11592 return PyBool_FromLong(
11593 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011594
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011595 for (i = 0; i < length; i++) {
11596 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011597 Py_RETURN_FALSE;
11598 }
11599 }
11600 Py_RETURN_TRUE;
11601}
11602
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011603PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011604 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011605\n\
11606Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011607iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608
11609static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011610unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011612 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613}
11614
Martin v. Löwis18e16552006-02-15 17:27:45 +000011615static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011616unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011617{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 if (PyUnicode_READY(self) == -1)
11619 return -1;
11620 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011621}
11622
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011623PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011624 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011625\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011626Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011627done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011628
11629static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011630unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011631{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011632 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 Py_UCS4 fillchar = ' ';
11634
11635 if (PyUnicode_READY(self) == -1)
11636 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011637
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011638 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011639 return NULL;
11640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011641 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011642 Py_INCREF(self);
11643 return (PyObject*) self;
11644 }
11645
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011646 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011647}
11648
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011649PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011651\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011652Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011653
11654static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011655unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011656{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011657 return fixup(self, fixlower);
11658}
11659
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011660#define LEFTSTRIP 0
11661#define RIGHTSTRIP 1
11662#define BOTHSTRIP 2
11663
11664/* Arrays indexed by above */
11665static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11666
11667#define STRIPNAME(i) (stripformat[i]+3)
11668
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011669/* externally visible for str.strip(unicode) */
11670PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011671_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011672{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673 void *data;
11674 int kind;
11675 Py_ssize_t i, j, len;
11676 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11679 return NULL;
11680
11681 kind = PyUnicode_KIND(self);
11682 data = PyUnicode_DATA(self);
11683 len = PyUnicode_GET_LENGTH(self);
11684 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11685 PyUnicode_DATA(sepobj),
11686 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011687
Benjamin Peterson14339b62009-01-31 16:36:08 +000011688 i = 0;
11689 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690 while (i < len &&
11691 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011692 i++;
11693 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011694 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011695
Benjamin Peterson14339b62009-01-31 16:36:08 +000011696 j = len;
11697 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011698 do {
11699 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700 } while (j >= i &&
11701 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011702 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011703 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011704
Victor Stinner12bab6d2011-10-01 01:53:49 +020011705 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011706}
11707
11708PyObject*
11709PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11710{
11711 unsigned char *data;
11712 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011713 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011714
Victor Stinnerde636f32011-10-01 03:55:54 +020011715 if (PyUnicode_READY(self) == -1)
11716 return NULL;
11717
11718 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11719
Victor Stinner12bab6d2011-10-01 01:53:49 +020011720 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011721 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011722 if (PyUnicode_CheckExact(self)) {
11723 Py_INCREF(self);
11724 return self;
11725 }
11726 else
11727 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011728 }
11729
Victor Stinner12bab6d2011-10-01 01:53:49 +020011730 length = end - start;
11731 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011732 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011733
Victor Stinnerde636f32011-10-01 03:55:54 +020011734 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011735 PyErr_SetString(PyExc_IndexError, "string index out of range");
11736 return NULL;
11737 }
11738
Victor Stinnerb9275c12011-10-05 14:01:42 +020011739 if (PyUnicode_IS_ASCII(self)) {
11740 kind = PyUnicode_KIND(self);
11741 data = PyUnicode_1BYTE_DATA(self);
11742 return unicode_fromascii(data + start, length);
11743 }
11744 else {
11745 kind = PyUnicode_KIND(self);
11746 data = PyUnicode_1BYTE_DATA(self);
11747 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011748 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011749 length);
11750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011751}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011752
11753static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011754do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011755{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011756 int kind;
11757 void *data;
11758 Py_ssize_t len, i, j;
11759
11760 if (PyUnicode_READY(self) == -1)
11761 return NULL;
11762
11763 kind = PyUnicode_KIND(self);
11764 data = PyUnicode_DATA(self);
11765 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766
Benjamin Peterson14339b62009-01-31 16:36:08 +000011767 i = 0;
11768 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011770 i++;
11771 }
11772 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011773
Benjamin Peterson14339b62009-01-31 16:36:08 +000011774 j = len;
11775 if (striptype != LEFTSTRIP) {
11776 do {
11777 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011779 j++;
11780 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011781
Victor Stinner12bab6d2011-10-01 01:53:49 +020011782 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011783}
11784
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011785
11786static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011787do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011789 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11792 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011793
Benjamin Peterson14339b62009-01-31 16:36:08 +000011794 if (sep != NULL && sep != Py_None) {
11795 if (PyUnicode_Check(sep))
11796 return _PyUnicode_XStrip(self, striptype, sep);
11797 else {
11798 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011799 "%s arg must be None or str",
11800 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011801 return NULL;
11802 }
11803 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011804
Benjamin Peterson14339b62009-01-31 16:36:08 +000011805 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011806}
11807
11808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011809PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011810 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811\n\
11812Return a copy of the string S with leading and trailing\n\
11813whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011814If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011815
11816static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011817unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011818{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011819 if (PyTuple_GET_SIZE(args) == 0)
11820 return do_strip(self, BOTHSTRIP); /* Common case */
11821 else
11822 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011823}
11824
11825
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011826PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011827 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011828\n\
11829Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011830If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011831
11832static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011833unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011834{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011835 if (PyTuple_GET_SIZE(args) == 0)
11836 return do_strip(self, LEFTSTRIP); /* Common case */
11837 else
11838 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011839}
11840
11841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011842PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011843 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011844\n\
11845Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011846If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011847
11848static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011849unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011850{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011851 if (PyTuple_GET_SIZE(args) == 0)
11852 return do_strip(self, RIGHTSTRIP); /* Common case */
11853 else
11854 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011855}
11856
11857
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011859unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011861 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011863
Georg Brandl222de0f2009-04-12 12:01:50 +000011864 if (len < 1) {
11865 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011866 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011867 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011868
Tim Peters7a29bd52001-09-12 03:03:31 +000011869 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870 /* no repeat, return original string */
11871 Py_INCREF(str);
11872 return (PyObject*) str;
11873 }
Tim Peters8f422462000-09-09 06:13:41 +000011874
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 if (PyUnicode_READY(str) == -1)
11876 return NULL;
11877
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011878 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011879 PyErr_SetString(PyExc_OverflowError,
11880 "repeated string is too long");
11881 return NULL;
11882 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011883 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011884
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011885 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011886 if (!u)
11887 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011888 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011890 if (PyUnicode_GET_LENGTH(str) == 1) {
11891 const int kind = PyUnicode_KIND(str);
11892 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11893 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011894 if (kind == PyUnicode_1BYTE_KIND)
11895 memset(to, (unsigned char)fill_char, len);
11896 else {
11897 for (n = 0; n < len; ++n)
11898 PyUnicode_WRITE(kind, to, n, fill_char);
11899 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011900 }
11901 else {
11902 /* number of characters copied this far */
11903 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011904 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011905 char *to = (char *) PyUnicode_DATA(u);
11906 Py_MEMCPY(to, PyUnicode_DATA(str),
11907 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011908 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011909 n = (done <= nchars-done) ? done : nchars-done;
11910 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011911 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011912 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011913 }
11914
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011915 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011916 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917}
11918
Alexander Belopolsky40018472011-02-26 01:02:56 +000011919PyObject *
11920PyUnicode_Replace(PyObject *obj,
11921 PyObject *subobj,
11922 PyObject *replobj,
11923 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924{
11925 PyObject *self;
11926 PyObject *str1;
11927 PyObject *str2;
11928 PyObject *result;
11929
11930 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011931 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011933 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011934 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011935 Py_DECREF(self);
11936 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937 }
11938 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011939 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011940 Py_DECREF(self);
11941 Py_DECREF(str1);
11942 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011943 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945 Py_DECREF(self);
11946 Py_DECREF(str1);
11947 Py_DECREF(str2);
11948 return result;
11949}
11950
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011951PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011952 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953\n\
11954Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011955old replaced by new. If the optional argument count is\n\
11956given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957
11958static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961 PyObject *str1;
11962 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011963 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964 PyObject *result;
11965
Martin v. Löwis18e16552006-02-15 17:27:45 +000011966 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011967 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011969 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 str1 = PyUnicode_FromObject(str1);
11971 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11972 return NULL;
11973 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011974 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011975 Py_DECREF(str1);
11976 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978
11979 result = replace(self, str1, str2, maxcount);
11980
11981 Py_DECREF(str1);
11982 Py_DECREF(str2);
11983 return result;
11984}
11985
Alexander Belopolsky40018472011-02-26 01:02:56 +000011986static PyObject *
11987unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011988{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011989 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 Py_ssize_t isize;
11991 Py_ssize_t osize, squote, dquote, i, o;
11992 Py_UCS4 max, quote;
11993 int ikind, okind;
11994 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011997 return NULL;
11998
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 isize = PyUnicode_GET_LENGTH(unicode);
12000 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012001
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012002 /* Compute length of output, quote characters, and
12003 maximum character */
12004 osize = 2; /* quotes */
12005 max = 127;
12006 squote = dquote = 0;
12007 ikind = PyUnicode_KIND(unicode);
12008 for (i = 0; i < isize; i++) {
12009 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12010 switch (ch) {
12011 case '\'': squote++; osize++; break;
12012 case '"': dquote++; osize++; break;
12013 case '\\': case '\t': case '\r': case '\n':
12014 osize += 2; break;
12015 default:
12016 /* Fast-path ASCII */
12017 if (ch < ' ' || ch == 0x7f)
12018 osize += 4; /* \xHH */
12019 else if (ch < 0x7f)
12020 osize++;
12021 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12022 osize++;
12023 max = ch > max ? ch : max;
12024 }
12025 else if (ch < 0x100)
12026 osize += 4; /* \xHH */
12027 else if (ch < 0x10000)
12028 osize += 6; /* \uHHHH */
12029 else
12030 osize += 10; /* \uHHHHHHHH */
12031 }
12032 }
12033
12034 quote = '\'';
12035 if (squote) {
12036 if (dquote)
12037 /* Both squote and dquote present. Use squote,
12038 and escape them */
12039 osize += squote;
12040 else
12041 quote = '"';
12042 }
12043
12044 repr = PyUnicode_New(osize, max);
12045 if (repr == NULL)
12046 return NULL;
12047 okind = PyUnicode_KIND(repr);
12048 odata = PyUnicode_DATA(repr);
12049
12050 PyUnicode_WRITE(okind, odata, 0, quote);
12051 PyUnicode_WRITE(okind, odata, osize-1, quote);
12052
12053 for (i = 0, o = 1; i < isize; i++) {
12054 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012055
12056 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 if ((ch == quote) || (ch == '\\')) {
12058 PyUnicode_WRITE(okind, odata, o++, '\\');
12059 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012060 continue;
12061 }
12062
Benjamin Peterson29060642009-01-31 22:14:21 +000012063 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012064 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012065 PyUnicode_WRITE(okind, odata, o++, '\\');
12066 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012067 }
12068 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 PyUnicode_WRITE(okind, odata, o++, '\\');
12070 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012071 }
12072 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012073 PyUnicode_WRITE(okind, odata, o++, '\\');
12074 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012075 }
12076
12077 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012078 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 PyUnicode_WRITE(okind, odata, o++, '\\');
12080 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012081 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12082 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012083 }
12084
Georg Brandl559e5d72008-06-11 18:37:52 +000012085 /* Copy ASCII characters as-is */
12086 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012087 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012088 }
12089
Benjamin Peterson29060642009-01-31 22:14:21 +000012090 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012091 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012092 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012093 (categories Z* and C* except ASCII space)
12094 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012096 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 if (ch <= 0xff) {
12098 PyUnicode_WRITE(okind, odata, o++, '\\');
12099 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012100 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12101 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012102 }
12103 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104 else if (ch >= 0x10000) {
12105 PyUnicode_WRITE(okind, odata, o++, '\\');
12106 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012107 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12108 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12109 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12110 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12111 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12112 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12114 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012115 }
12116 /* Map 16-bit characters to '\uxxxx' */
12117 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012118 PyUnicode_WRITE(okind, odata, o++, '\\');
12119 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012120 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12121 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12122 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12123 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012124 }
12125 }
12126 /* Copy characters as-is */
12127 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012128 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012129 }
12130 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012131 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012132 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012133 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012134 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012135}
12136
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012137PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012138 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012139\n\
12140Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012141such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142arguments start and end are interpreted as in slice notation.\n\
12143\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012144Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145
12146static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012148{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012149 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012150 Py_ssize_t start;
12151 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012152 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153
Jesus Ceaac451502011-04-20 17:09:23 +020012154 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12155 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012156 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158 if (PyUnicode_READY(self) == -1)
12159 return NULL;
12160 if (PyUnicode_READY(substring) == -1)
12161 return NULL;
12162
Victor Stinner794d5672011-10-10 03:21:36 +020012163 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012164 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012165 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166
12167 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012168
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 if (result == -2)
12170 return NULL;
12171
Christian Heimes217cfd12007-12-02 14:31:20 +000012172 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173}
12174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012175PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012176 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012178Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179
12180static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012181unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012183 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012184 Py_ssize_t start;
12185 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012186 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012187
Jesus Ceaac451502011-04-20 17:09:23 +020012188 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12189 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012190 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012192 if (PyUnicode_READY(self) == -1)
12193 return NULL;
12194 if (PyUnicode_READY(substring) == -1)
12195 return NULL;
12196
Victor Stinner794d5672011-10-10 03:21:36 +020012197 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012198 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012199 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012200
12201 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 if (result == -2)
12204 return NULL;
12205
Guido van Rossumd57fd912000-03-10 22:53:23 +000012206 if (result < 0) {
12207 PyErr_SetString(PyExc_ValueError, "substring not found");
12208 return NULL;
12209 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210
Christian Heimes217cfd12007-12-02 14:31:20 +000012211 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212}
12213
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012214PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012215 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012216\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012217Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012218done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012219
12220static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012221unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012222{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012223 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012224 Py_UCS4 fillchar = ' ';
12225
Victor Stinnere9a29352011-10-01 02:14:59 +020012226 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012227 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012228
Victor Stinnere9a29352011-10-01 02:14:59 +020012229 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230 return NULL;
12231
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012232 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012233 Py_INCREF(self);
12234 return (PyObject*) self;
12235 }
12236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012237 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238}
12239
Alexander Belopolsky40018472011-02-26 01:02:56 +000012240PyObject *
12241PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242{
12243 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012244
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245 s = PyUnicode_FromObject(s);
12246 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012247 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012248 if (sep != NULL) {
12249 sep = PyUnicode_FromObject(sep);
12250 if (sep == NULL) {
12251 Py_DECREF(s);
12252 return NULL;
12253 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254 }
12255
Victor Stinner9310abb2011-10-05 00:59:23 +020012256 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012257
12258 Py_DECREF(s);
12259 Py_XDECREF(sep);
12260 return result;
12261}
12262
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012263PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012264 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012265\n\
12266Return a list of the words in S, using sep as the\n\
12267delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012268splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012269whitespace string is a separator and empty strings are\n\
12270removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271
12272static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012273unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012274{
12275 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012276 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277
Martin v. Löwis18e16552006-02-15 17:27:45 +000012278 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279 return NULL;
12280
12281 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012284 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012286 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287}
12288
Thomas Wouters477c8d52006-05-27 19:21:47 +000012289PyObject *
12290PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12291{
12292 PyObject* str_obj;
12293 PyObject* sep_obj;
12294 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 int kind1, kind2, kind;
12296 void *buf1 = NULL, *buf2 = NULL;
12297 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012298
12299 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012300 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012301 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012302 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012303 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012304 Py_DECREF(str_obj);
12305 return NULL;
12306 }
12307
Victor Stinner14f8f022011-10-05 20:58:25 +020012308 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012310 kind = Py_MAX(kind1, kind2);
12311 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012312 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012313 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 if (!buf1)
12315 goto onError;
12316 buf2 = PyUnicode_DATA(sep_obj);
12317 if (kind2 != kind)
12318 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12319 if (!buf2)
12320 goto onError;
12321 len1 = PyUnicode_GET_LENGTH(str_obj);
12322 len2 = PyUnicode_GET_LENGTH(sep_obj);
12323
Victor Stinner14f8f022011-10-05 20:58:25 +020012324 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012325 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012326 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12327 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12328 else
12329 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 break;
12331 case PyUnicode_2BYTE_KIND:
12332 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12333 break;
12334 case PyUnicode_4BYTE_KIND:
12335 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12336 break;
12337 default:
12338 assert(0);
12339 out = 0;
12340 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012341
12342 Py_DECREF(sep_obj);
12343 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012344 if (kind1 != kind)
12345 PyMem_Free(buf1);
12346 if (kind2 != kind)
12347 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012348
12349 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012350 onError:
12351 Py_DECREF(sep_obj);
12352 Py_DECREF(str_obj);
12353 if (kind1 != kind && buf1)
12354 PyMem_Free(buf1);
12355 if (kind2 != kind && buf2)
12356 PyMem_Free(buf2);
12357 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358}
12359
12360
12361PyObject *
12362PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12363{
12364 PyObject* str_obj;
12365 PyObject* sep_obj;
12366 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012367 int kind1, kind2, kind;
12368 void *buf1 = NULL, *buf2 = NULL;
12369 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012370
12371 str_obj = PyUnicode_FromObject(str_in);
12372 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012373 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012374 sep_obj = PyUnicode_FromObject(sep_in);
12375 if (!sep_obj) {
12376 Py_DECREF(str_obj);
12377 return NULL;
12378 }
12379
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012380 kind1 = PyUnicode_KIND(str_in);
12381 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012382 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012383 buf1 = PyUnicode_DATA(str_in);
12384 if (kind1 != kind)
12385 buf1 = _PyUnicode_AsKind(str_in, kind);
12386 if (!buf1)
12387 goto onError;
12388 buf2 = PyUnicode_DATA(sep_obj);
12389 if (kind2 != kind)
12390 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12391 if (!buf2)
12392 goto onError;
12393 len1 = PyUnicode_GET_LENGTH(str_obj);
12394 len2 = PyUnicode_GET_LENGTH(sep_obj);
12395
12396 switch(PyUnicode_KIND(str_in)) {
12397 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012398 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12399 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12400 else
12401 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 break;
12403 case PyUnicode_2BYTE_KIND:
12404 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12405 break;
12406 case PyUnicode_4BYTE_KIND:
12407 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12408 break;
12409 default:
12410 assert(0);
12411 out = 0;
12412 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012413
12414 Py_DECREF(sep_obj);
12415 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012416 if (kind1 != kind)
12417 PyMem_Free(buf1);
12418 if (kind2 != kind)
12419 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012420
12421 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012422 onError:
12423 Py_DECREF(sep_obj);
12424 Py_DECREF(str_obj);
12425 if (kind1 != kind && buf1)
12426 PyMem_Free(buf1);
12427 if (kind2 != kind && buf2)
12428 PyMem_Free(buf2);
12429 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012430}
12431
12432PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012433 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012434\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012435Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012437found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012438
12439static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012440unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012441{
Victor Stinner9310abb2011-10-05 00:59:23 +020012442 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012443}
12444
12445PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012446 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012448Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012449the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012450separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012451
12452static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012453unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454{
Victor Stinner9310abb2011-10-05 00:59:23 +020012455 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456}
12457
Alexander Belopolsky40018472011-02-26 01:02:56 +000012458PyObject *
12459PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012460{
12461 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012462
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012463 s = PyUnicode_FromObject(s);
12464 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012465 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012466 if (sep != NULL) {
12467 sep = PyUnicode_FromObject(sep);
12468 if (sep == NULL) {
12469 Py_DECREF(s);
12470 return NULL;
12471 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012472 }
12473
Victor Stinner9310abb2011-10-05 00:59:23 +020012474 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012475
12476 Py_DECREF(s);
12477 Py_XDECREF(sep);
12478 return result;
12479}
12480
12481PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012482 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012483\n\
12484Return a list of the words in S, using sep as the\n\
12485delimiter string, starting at the end of the string and\n\
12486working to the front. If maxsplit is given, at most maxsplit\n\
12487splits are done. If sep is not specified, any whitespace string\n\
12488is a separator.");
12489
12490static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012491unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012492{
12493 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012494 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012495
Martin v. Löwis18e16552006-02-15 17:27:45 +000012496 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012497 return NULL;
12498
12499 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012500 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012501 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012502 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012503 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012504 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012505}
12506
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012507PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012508 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509\n\
12510Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012511Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012512is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012513
12514static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012515unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012516{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012517 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012518 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012519
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012520 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12521 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012522 return NULL;
12523
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012524 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012525}
12526
12527static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012528PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012529{
Walter Dörwald346737f2007-05-31 10:44:43 +000012530 if (PyUnicode_CheckExact(self)) {
12531 Py_INCREF(self);
12532 return self;
12533 } else
12534 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012535 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012536}
12537
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012538PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012539 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012540\n\
12541Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012542and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012543
12544static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012545unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012546{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012547 return fixup(self, fixswapcase);
12548}
12549
Georg Brandlceee0772007-11-27 23:48:05 +000012550PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012551 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012552\n\
12553Return a translation table usable for str.translate().\n\
12554If there is only one argument, it must be a dictionary mapping Unicode\n\
12555ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012556Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012557If there are two arguments, they must be strings of equal length, and\n\
12558in the resulting dictionary, each character in x will be mapped to the\n\
12559character at the same position in y. If there is a third argument, it\n\
12560must be a string, whose characters will be mapped to None in the result.");
12561
12562static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012563unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012564{
12565 PyObject *x, *y = NULL, *z = NULL;
12566 PyObject *new = NULL, *key, *value;
12567 Py_ssize_t i = 0;
12568 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012569
Georg Brandlceee0772007-11-27 23:48:05 +000012570 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12571 return NULL;
12572 new = PyDict_New();
12573 if (!new)
12574 return NULL;
12575 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012576 int x_kind, y_kind, z_kind;
12577 void *x_data, *y_data, *z_data;
12578
Georg Brandlceee0772007-11-27 23:48:05 +000012579 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012580 if (!PyUnicode_Check(x)) {
12581 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12582 "be a string if there is a second argument");
12583 goto err;
12584 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012585 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012586 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12587 "arguments must have equal length");
12588 goto err;
12589 }
12590 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012591 x_kind = PyUnicode_KIND(x);
12592 y_kind = PyUnicode_KIND(y);
12593 x_data = PyUnicode_DATA(x);
12594 y_data = PyUnicode_DATA(y);
12595 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12596 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12597 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012598 if (!key || !value)
12599 goto err;
12600 res = PyDict_SetItem(new, key, value);
12601 Py_DECREF(key);
12602 Py_DECREF(value);
12603 if (res < 0)
12604 goto err;
12605 }
12606 /* create entries for deleting chars in z */
12607 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012608 z_kind = PyUnicode_KIND(z);
12609 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012610 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012611 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012612 if (!key)
12613 goto err;
12614 res = PyDict_SetItem(new, key, Py_None);
12615 Py_DECREF(key);
12616 if (res < 0)
12617 goto err;
12618 }
12619 }
12620 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012621 int kind;
12622 void *data;
12623
Georg Brandlceee0772007-11-27 23:48:05 +000012624 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012625 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012626 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12627 "to maketrans it must be a dict");
12628 goto err;
12629 }
12630 /* copy entries into the new dict, converting string keys to int keys */
12631 while (PyDict_Next(x, &i, &key, &value)) {
12632 if (PyUnicode_Check(key)) {
12633 /* convert string keys to integer keys */
12634 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012635 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012636 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12637 "table must be of length 1");
12638 goto err;
12639 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012640 kind = PyUnicode_KIND(key);
12641 data = PyUnicode_DATA(key);
12642 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012643 if (!newkey)
12644 goto err;
12645 res = PyDict_SetItem(new, newkey, value);
12646 Py_DECREF(newkey);
12647 if (res < 0)
12648 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012649 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012650 /* just keep integer keys */
12651 if (PyDict_SetItem(new, key, value) < 0)
12652 goto err;
12653 } else {
12654 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12655 "be strings or integers");
12656 goto err;
12657 }
12658 }
12659 }
12660 return new;
12661 err:
12662 Py_DECREF(new);
12663 return NULL;
12664}
12665
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012666PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012667 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012668\n\
12669Return a copy of the string S, where all characters have been mapped\n\
12670through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012671Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012672Unmapped characters are left untouched. Characters mapped to None\n\
12673are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674
12675static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679}
12680
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012681PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012682 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012683\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012684Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685
12686static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012687unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012689 return fixup(self, fixupper);
12690}
12691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012692PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012693 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012694\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012695Pad a numeric string S with zeros on the left, to fill a field\n\
12696of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697
12698static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012699unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012700{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012701 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012702 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012703 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012704 int kind;
12705 void *data;
12706 Py_UCS4 chr;
12707
12708 if (PyUnicode_READY(self) == -1)
12709 return NULL;
12710
Martin v. Löwis18e16552006-02-15 17:27:45 +000012711 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712 return NULL;
12713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012714 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012715 if (PyUnicode_CheckExact(self)) {
12716 Py_INCREF(self);
12717 return (PyObject*) self;
12718 }
12719 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012720 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012721 }
12722
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012723 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012724
12725 u = pad(self, fill, 0, '0');
12726
Walter Dörwald068325e2002-04-15 13:36:47 +000012727 if (u == NULL)
12728 return NULL;
12729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012730 kind = PyUnicode_KIND(u);
12731 data = PyUnicode_DATA(u);
12732 chr = PyUnicode_READ(kind, data, fill);
12733
12734 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012736 PyUnicode_WRITE(kind, data, 0, chr);
12737 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012738 }
12739
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012740 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012741 return (PyObject*) u;
12742}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743
12744#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012745static PyObject *
12746unicode__decimal2ascii(PyObject *self)
12747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012748 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012749}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750#endif
12751
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012752PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012753 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012755Return True if S starts with the specified prefix, False otherwise.\n\
12756With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012757With optional end, stop comparing S at that position.\n\
12758prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012759
12760static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012761unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012762 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012764 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012765 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012766 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012767 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012768 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769
Jesus Ceaac451502011-04-20 17:09:23 +020012770 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012772 if (PyTuple_Check(subobj)) {
12773 Py_ssize_t i;
12774 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012775 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012776 if (substring == NULL)
12777 return NULL;
12778 result = tailmatch(self, substring, start, end, -1);
12779 Py_DECREF(substring);
12780 if (result) {
12781 Py_RETURN_TRUE;
12782 }
12783 }
12784 /* nothing matched */
12785 Py_RETURN_FALSE;
12786 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012787 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012788 if (substring == NULL) {
12789 if (PyErr_ExceptionMatches(PyExc_TypeError))
12790 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12791 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012792 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012793 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012794 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012796 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012797}
12798
12799
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012800PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012801 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012803Return True if S ends with the specified suffix, False otherwise.\n\
12804With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012805With optional end, stop comparing S at that position.\n\
12806suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012807
12808static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012809unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012810 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012811{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012812 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012813 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012814 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012815 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012816 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817
Jesus Ceaac451502011-04-20 17:09:23 +020012818 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012819 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012820 if (PyTuple_Check(subobj)) {
12821 Py_ssize_t i;
12822 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012823 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012824 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012825 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012826 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012827 result = tailmatch(self, substring, start, end, +1);
12828 Py_DECREF(substring);
12829 if (result) {
12830 Py_RETURN_TRUE;
12831 }
12832 }
12833 Py_RETURN_FALSE;
12834 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012835 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012836 if (substring == NULL) {
12837 if (PyErr_ExceptionMatches(PyExc_TypeError))
12838 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12839 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012840 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012841 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012842 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012844 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012845}
12846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012847#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012848
12849PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012850 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012851\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012852Return a formatted version of S, using substitutions from args and kwargs.\n\
12853The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012854
Eric Smith27bbca62010-11-04 17:06:58 +000012855PyDoc_STRVAR(format_map__doc__,
12856 "S.format_map(mapping) -> str\n\
12857\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012858Return a formatted version of S, using substitutions from mapping.\n\
12859The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012860
Eric Smith4a7d76d2008-05-30 18:10:19 +000012861static PyObject *
12862unicode__format__(PyObject* self, PyObject* args)
12863{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012864 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012865
12866 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12867 return NULL;
12868
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012869 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012870 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012871 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012872}
12873
Eric Smith8c663262007-08-25 02:26:07 +000012874PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012875 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012876\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012877Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012878
12879static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012880unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012882 Py_ssize_t size;
12883
12884 /* If it's a compact object, account for base structure +
12885 character data. */
12886 if (PyUnicode_IS_COMPACT_ASCII(v))
12887 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12888 else if (PyUnicode_IS_COMPACT(v))
12889 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012890 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012891 else {
12892 /* If it is a two-block object, account for base object, and
12893 for character block if present. */
12894 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012895 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012896 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012897 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012898 }
12899 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012900 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012901 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012902 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012903 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012904 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905
12906 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012907}
12908
12909PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012910 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012911
12912static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012913unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012914{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012915 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012916 if (!copy)
12917 return NULL;
12918 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012919}
12920
Guido van Rossumd57fd912000-03-10 22:53:23 +000012921static PyMethodDef unicode_methods[] = {
12922
12923 /* Order is according to common usage: often used methods should
12924 appear first, since lookup is done sequentially. */
12925
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012926 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012927 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12928 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012929 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012930 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12931 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12932 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12933 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12934 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12935 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12936 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012937 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012938 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12939 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12940 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012941 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012942 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12943 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12944 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012945 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012946 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012947 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012948 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012949 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12950 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12951 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12952 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12953 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12954 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12955 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12956 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12957 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12958 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12959 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12960 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12961 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12962 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012963 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012964 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012965 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012966 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012967 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012968 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012969 {"maketrans", (PyCFunction) unicode_maketrans,
12970 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012971 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012972#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012973 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012974#endif
12975
12976#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012977 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012978 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012979#endif
12980
Benjamin Peterson14339b62009-01-31 16:36:08 +000012981 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012982 {NULL, NULL}
12983};
12984
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012985static PyObject *
12986unicode_mod(PyObject *v, PyObject *w)
12987{
Brian Curtindfc80e32011-08-10 20:28:54 -050012988 if (!PyUnicode_Check(v))
12989 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012990 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012991}
12992
12993static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012994 0, /*nb_add*/
12995 0, /*nb_subtract*/
12996 0, /*nb_multiply*/
12997 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012998};
12999
Guido van Rossumd57fd912000-03-10 22:53:23 +000013000static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013001 (lenfunc) unicode_length, /* sq_length */
13002 PyUnicode_Concat, /* sq_concat */
13003 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13004 (ssizeargfunc) unicode_getitem, /* sq_item */
13005 0, /* sq_slice */
13006 0, /* sq_ass_item */
13007 0, /* sq_ass_slice */
13008 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013009};
13010
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013011static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013012unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013013{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013014 if (PyUnicode_READY(self) == -1)
13015 return NULL;
13016
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013017 if (PyIndex_Check(item)) {
13018 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013019 if (i == -1 && PyErr_Occurred())
13020 return NULL;
13021 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013022 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013023 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013024 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013025 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013026 PyObject *result;
13027 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013028 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013029 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013030
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013031 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013032 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013033 return NULL;
13034 }
13035
13036 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013037 return PyUnicode_New(0, 0);
13038 } else if (start == 0 && step == 1 &&
13039 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013040 PyUnicode_CheckExact(self)) {
13041 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013042 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013043 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013044 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013045 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013046 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013047 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013048 src_kind = PyUnicode_KIND(self);
13049 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013050 if (!PyUnicode_IS_ASCII(self)) {
13051 kind_limit = kind_maxchar_limit(src_kind);
13052 max_char = 0;
13053 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13054 ch = PyUnicode_READ(src_kind, src_data, cur);
13055 if (ch > max_char) {
13056 max_char = ch;
13057 if (max_char >= kind_limit)
13058 break;
13059 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013060 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013061 }
Victor Stinner55c99112011-10-13 01:17:06 +020013062 else
13063 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013064 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013065 if (result == NULL)
13066 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013067 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013068 dest_data = PyUnicode_DATA(result);
13069
13070 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013071 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13072 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013073 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013074 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013075 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013076 } else {
13077 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13078 return NULL;
13079 }
13080}
13081
13082static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013083 (lenfunc)unicode_length, /* mp_length */
13084 (binaryfunc)unicode_subscript, /* mp_subscript */
13085 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013086};
13087
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089/* Helpers for PyUnicode_Format() */
13090
13091static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013092getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013094 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013095 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 (*p_argidx)++;
13097 if (arglen < 0)
13098 return args;
13099 else
13100 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013101 }
13102 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013103 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104 return NULL;
13105}
13106
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013107/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013108
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013109static PyObject *
13110formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013112 char *p;
13113 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013115
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116 x = PyFloat_AsDouble(v);
13117 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013118 return NULL;
13119
Guido van Rossumd57fd912000-03-10 22:53:23 +000013120 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013121 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013122
Eric Smith0923d1d2009-04-16 20:16:10 +000013123 p = PyOS_double_to_string(x, type, prec,
13124 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013125 if (p == NULL)
13126 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013128 PyMem_Free(p);
13129 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013130}
13131
Tim Peters38fd5b62000-09-21 05:43:11 +000013132static PyObject*
13133formatlong(PyObject *val, int flags, int prec, int type)
13134{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013135 char *buf;
13136 int len;
13137 PyObject *str; /* temporary string object. */
13138 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013139
Benjamin Peterson14339b62009-01-31 16:36:08 +000013140 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13141 if (!str)
13142 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013144 Py_DECREF(str);
13145 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013146}
13147
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013148static Py_UCS4
13149formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013150{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013151 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013152 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013153 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013154 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013155 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013156 goto onError;
13157 }
13158 else {
13159 /* Integer input truncated to a character */
13160 long x;
13161 x = PyLong_AsLong(v);
13162 if (x == -1 && PyErr_Occurred())
13163 goto onError;
13164
13165 if (x < 0 || x > 0x10ffff) {
13166 PyErr_SetString(PyExc_OverflowError,
13167 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013168 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013169 }
13170
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013171 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013172 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013173
Benjamin Peterson29060642009-01-31 22:14:21 +000013174 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013175 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013176 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013177 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178}
13179
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013180static int
13181repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13182{
13183 int r;
13184 assert(count > 0);
13185 assert(PyUnicode_Check(obj));
13186 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013187 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013188 if (repeated == NULL)
13189 return -1;
13190 r = _PyAccu_Accumulate(acc, repeated);
13191 Py_DECREF(repeated);
13192 return r;
13193 }
13194 else {
13195 do {
13196 if (_PyAccu_Accumulate(acc, obj))
13197 return -1;
13198 } while (--count);
13199 return 0;
13200 }
13201}
13202
Alexander Belopolsky40018472011-02-26 01:02:56 +000013203PyObject *
13204PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013206 void *fmt;
13207 int fmtkind;
13208 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013210 int r;
13211 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013212 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013213 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013214 PyObject *temp = NULL;
13215 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013216 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013217 _PyAccu acc;
13218 static PyObject *plus, *minus, *blank, *zero, *percent;
13219
13220 if (!plus && !(plus = get_latin1_char('+')))
13221 return NULL;
13222 if (!minus && !(minus = get_latin1_char('-')))
13223 return NULL;
13224 if (!blank && !(blank = get_latin1_char(' ')))
13225 return NULL;
13226 if (!zero && !(zero = get_latin1_char('0')))
13227 return NULL;
13228 if (!percent && !(percent = get_latin1_char('%')))
13229 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013230
Guido van Rossumd57fd912000-03-10 22:53:23 +000013231 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013232 PyErr_BadInternalCall();
13233 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013235 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013236 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013237 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013238 if (_PyAccu_Init(&acc))
13239 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013240 fmt = PyUnicode_DATA(uformat);
13241 fmtkind = PyUnicode_KIND(uformat);
13242 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13243 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013244
Guido van Rossumd57fd912000-03-10 22:53:23 +000013245 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 arglen = PyTuple_Size(args);
13247 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013248 }
13249 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013250 arglen = -1;
13251 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013252 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013253 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013254 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013255 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256
13257 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013258 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013259 PyObject *nonfmt;
13260 Py_ssize_t nonfmtpos;
13261 nonfmtpos = fmtpos++;
13262 while (fmtcnt >= 0 &&
13263 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13264 fmtpos++;
13265 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013266 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
13268 if (nonfmt == NULL)
13269 goto onError;
13270 r = _PyAccu_Accumulate(&acc, nonfmt);
13271 Py_DECREF(nonfmt);
13272 if (r)
13273 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013274 }
13275 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013276 /* Got a format specifier */
13277 int flags = 0;
13278 Py_ssize_t width = -1;
13279 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013280 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013281 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 int isnumok;
13283 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013284 void *pbuf = NULL;
13285 Py_ssize_t pindex, len;
13286 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013288 fmtpos++;
13289 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13290 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013291 Py_ssize_t keylen;
13292 PyObject *key;
13293 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013294
Benjamin Peterson29060642009-01-31 22:14:21 +000013295 if (dict == NULL) {
13296 PyErr_SetString(PyExc_TypeError,
13297 "format requires a mapping");
13298 goto onError;
13299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013300 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013301 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013302 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013303 /* Skip over balanced parentheses */
13304 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013305 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013306 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013307 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013308 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013309 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013310 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013312 if (fmtcnt < 0 || pcount > 0) {
13313 PyErr_SetString(PyExc_ValueError,
13314 "incomplete format key");
13315 goto onError;
13316 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020013317 key = PyUnicode_Substring((PyObject*)uformat,
13318 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 if (key == NULL)
13320 goto onError;
13321 if (args_owned) {
13322 Py_DECREF(args);
13323 args_owned = 0;
13324 }
13325 args = PyObject_GetItem(dict, key);
13326 Py_DECREF(key);
13327 if (args == NULL) {
13328 goto onError;
13329 }
13330 args_owned = 1;
13331 arglen = -1;
13332 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013333 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013334 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013335 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013336 case '-': flags |= F_LJUST; continue;
13337 case '+': flags |= F_SIGN; continue;
13338 case ' ': flags |= F_BLANK; continue;
13339 case '#': flags |= F_ALT; continue;
13340 case '0': flags |= F_ZERO; continue;
13341 }
13342 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013343 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 if (c == '*') {
13345 v = getnextarg(args, arglen, &argidx);
13346 if (v == NULL)
13347 goto onError;
13348 if (!PyLong_Check(v)) {
13349 PyErr_SetString(PyExc_TypeError,
13350 "* wants int");
13351 goto onError;
13352 }
13353 width = PyLong_AsLong(v);
13354 if (width == -1 && PyErr_Occurred())
13355 goto onError;
13356 if (width < 0) {
13357 flags |= F_LJUST;
13358 width = -width;
13359 }
13360 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013361 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013362 }
13363 else if (c >= '0' && c <= '9') {
13364 width = c - '0';
13365 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013366 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013367 if (c < '0' || c > '9')
13368 break;
13369 if ((width*10) / 10 != width) {
13370 PyErr_SetString(PyExc_ValueError,
13371 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013372 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013373 }
13374 width = width*10 + (c - '0');
13375 }
13376 }
13377 if (c == '.') {
13378 prec = 0;
13379 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013380 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 if (c == '*') {
13382 v = getnextarg(args, arglen, &argidx);
13383 if (v == NULL)
13384 goto onError;
13385 if (!PyLong_Check(v)) {
13386 PyErr_SetString(PyExc_TypeError,
13387 "* wants int");
13388 goto onError;
13389 }
13390 prec = PyLong_AsLong(v);
13391 if (prec == -1 && PyErr_Occurred())
13392 goto onError;
13393 if (prec < 0)
13394 prec = 0;
13395 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013396 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013397 }
13398 else if (c >= '0' && c <= '9') {
13399 prec = c - '0';
13400 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013401 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 if (c < '0' || c > '9')
13403 break;
13404 if ((prec*10) / 10 != prec) {
13405 PyErr_SetString(PyExc_ValueError,
13406 "prec too big");
13407 goto onError;
13408 }
13409 prec = prec*10 + (c - '0');
13410 }
13411 }
13412 } /* prec */
13413 if (fmtcnt >= 0) {
13414 if (c == 'h' || c == 'l' || c == 'L') {
13415 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013416 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 }
13418 }
13419 if (fmtcnt < 0) {
13420 PyErr_SetString(PyExc_ValueError,
13421 "incomplete format");
13422 goto onError;
13423 }
13424 if (c != '%') {
13425 v = getnextarg(args, arglen, &argidx);
13426 if (v == NULL)
13427 goto onError;
13428 }
13429 sign = 0;
13430 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013431 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013432 switch (c) {
13433
13434 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013435 _PyAccu_Accumulate(&acc, percent);
13436 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013437
13438 case 's':
13439 case 'r':
13440 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013441 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 temp = v;
13443 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013444 }
13445 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013446 if (c == 's')
13447 temp = PyObject_Str(v);
13448 else if (c == 'r')
13449 temp = PyObject_Repr(v);
13450 else
13451 temp = PyObject_ASCII(v);
13452 if (temp == NULL)
13453 goto onError;
13454 if (PyUnicode_Check(temp))
13455 /* nothing to do */;
13456 else {
13457 Py_DECREF(temp);
13458 PyErr_SetString(PyExc_TypeError,
13459 "%s argument has non-string str()");
13460 goto onError;
13461 }
13462 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013463 if (PyUnicode_READY(temp) == -1) {
13464 Py_CLEAR(temp);
13465 goto onError;
13466 }
13467 pbuf = PyUnicode_DATA(temp);
13468 kind = PyUnicode_KIND(temp);
13469 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 if (prec >= 0 && len > prec)
13471 len = prec;
13472 break;
13473
13474 case 'i':
13475 case 'd':
13476 case 'u':
13477 case 'o':
13478 case 'x':
13479 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013480 isnumok = 0;
13481 if (PyNumber_Check(v)) {
13482 PyObject *iobj=NULL;
13483
13484 if (PyLong_Check(v)) {
13485 iobj = v;
13486 Py_INCREF(iobj);
13487 }
13488 else {
13489 iobj = PyNumber_Long(v);
13490 }
13491 if (iobj!=NULL) {
13492 if (PyLong_Check(iobj)) {
13493 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013494 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 Py_DECREF(iobj);
13496 if (!temp)
13497 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013498 if (PyUnicode_READY(temp) == -1) {
13499 Py_CLEAR(temp);
13500 goto onError;
13501 }
13502 pbuf = PyUnicode_DATA(temp);
13503 kind = PyUnicode_KIND(temp);
13504 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 sign = 1;
13506 }
13507 else {
13508 Py_DECREF(iobj);
13509 }
13510 }
13511 }
13512 if (!isnumok) {
13513 PyErr_Format(PyExc_TypeError,
13514 "%%%c format: a number is required, "
13515 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13516 goto onError;
13517 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013518 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013519 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013520 fillobj = zero;
13521 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 break;
13523
13524 case 'e':
13525 case 'E':
13526 case 'f':
13527 case 'F':
13528 case 'g':
13529 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013530 temp = formatfloat(v, flags, prec, c);
13531 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 goto onError;
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 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013541 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013542 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013543 fillobj = zero;
13544 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 break;
13546
13547 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013548 {
13549 Py_UCS4 ch = formatchar(v);
13550 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013552 temp = _PyUnicode_FromUCS4(&ch, 1);
13553 if (temp == NULL)
13554 goto onError;
13555 pbuf = PyUnicode_DATA(temp);
13556 kind = PyUnicode_KIND(temp);
13557 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013558 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013559 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013560
13561 default:
13562 PyErr_Format(PyExc_ValueError,
13563 "unsupported format character '%c' (0x%x) "
13564 "at index %zd",
13565 (31<=c && c<=126) ? (char)c : '?',
13566 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013567 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013568 goto onError;
13569 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570 /* pbuf is initialized here. */
13571 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013572 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013573 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13574 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013575 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013576 pindex++;
13577 }
13578 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13579 signobj = plus;
13580 len--;
13581 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013582 }
13583 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013584 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013585 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013586 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 else
13588 sign = 0;
13589 }
13590 if (width < len)
13591 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013592 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013593 if (fill != ' ') {
13594 assert(signobj != NULL);
13595 if (_PyAccu_Accumulate(&acc, signobj))
13596 goto onError;
13597 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 if (width > len)
13599 width--;
13600 }
13601 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013602 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013603 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013605 second = get_latin1_char(
13606 PyUnicode_READ(kind, pbuf, pindex + 1));
13607 pindex += 2;
13608 if (second == NULL ||
13609 _PyAccu_Accumulate(&acc, zero) ||
13610 _PyAccu_Accumulate(&acc, second))
13611 goto onError;
13612 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013613 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013614 width -= 2;
13615 if (width < 0)
13616 width = 0;
13617 len -= 2;
13618 }
13619 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013620 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013621 if (repeat_accumulate(&acc, fillobj, width - len))
13622 goto onError;
13623 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 }
13625 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013626 if (sign) {
13627 assert(signobj != NULL);
13628 if (_PyAccu_Accumulate(&acc, signobj))
13629 goto onError;
13630 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013632 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13633 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013634 second = get_latin1_char(
13635 PyUnicode_READ(kind, pbuf, pindex + 1));
13636 pindex += 2;
13637 if (second == NULL ||
13638 _PyAccu_Accumulate(&acc, zero) ||
13639 _PyAccu_Accumulate(&acc, second))
13640 goto onError;
13641 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013642 }
13643 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013644 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013645 if (temp != NULL) {
13646 assert(pbuf == PyUnicode_DATA(temp));
13647 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013648 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013649 else {
13650 const char *p = (const char *) pbuf;
13651 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013652 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013653 v = PyUnicode_FromKindAndData(kind, p, len);
13654 }
13655 if (v == NULL)
13656 goto onError;
13657 r = _PyAccu_Accumulate(&acc, v);
13658 Py_DECREF(v);
13659 if (r)
13660 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013661 if (width > len && repeat_accumulate(&acc, blank, width - len))
13662 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013663 if (dict && (argidx < arglen) && c != '%') {
13664 PyErr_SetString(PyExc_TypeError,
13665 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 goto onError;
13667 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013668 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013670 } /* until end */
13671 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 PyErr_SetString(PyExc_TypeError,
13673 "not all arguments converted during string formatting");
13674 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013675 }
13676
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013677 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013678 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013679 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013680 }
13681 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013682 Py_XDECREF(temp);
13683 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013684 return (PyObject *)result;
13685
Benjamin Peterson29060642009-01-31 22:14:21 +000013686 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013687 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013688 Py_XDECREF(temp);
13689 Py_XDECREF(second);
13690 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013691 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013692 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013693 }
13694 return NULL;
13695}
13696
Jeremy Hylton938ace62002-07-17 16:30:39 +000013697static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013698unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13699
Tim Peters6d6c1a32001-08-02 04:15:00 +000013700static PyObject *
13701unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13702{
Benjamin Peterson29060642009-01-31 22:14:21 +000013703 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013704 static char *kwlist[] = {"object", "encoding", "errors", 0};
13705 char *encoding = NULL;
13706 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013707
Benjamin Peterson14339b62009-01-31 16:36:08 +000013708 if (type != &PyUnicode_Type)
13709 return unicode_subtype_new(type, args, kwds);
13710 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013711 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013712 return NULL;
13713 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013714 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013715 if (encoding == NULL && errors == NULL)
13716 return PyObject_Str(x);
13717 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013718 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013719}
13720
Guido van Rossume023fe02001-08-30 03:12:59 +000013721static PyObject *
13722unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13723{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013724 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013725 Py_ssize_t length, char_size;
13726 int share_wstr, share_utf8;
13727 unsigned int kind;
13728 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013729
Benjamin Peterson14339b62009-01-31 16:36:08 +000013730 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013731
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013732 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013733 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013734 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013735 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013736 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013737 return NULL;
13738
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013739 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013740 if (self == NULL) {
13741 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013742 return NULL;
13743 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013744 kind = PyUnicode_KIND(unicode);
13745 length = PyUnicode_GET_LENGTH(unicode);
13746
13747 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013748#ifdef Py_DEBUG
13749 _PyUnicode_HASH(self) = -1;
13750#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013751 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013752#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013753 _PyUnicode_STATE(self).interned = 0;
13754 _PyUnicode_STATE(self).kind = kind;
13755 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013756 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013757 _PyUnicode_STATE(self).ready = 1;
13758 _PyUnicode_WSTR(self) = NULL;
13759 _PyUnicode_UTF8_LENGTH(self) = 0;
13760 _PyUnicode_UTF8(self) = NULL;
13761 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013762 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013763
13764 share_utf8 = 0;
13765 share_wstr = 0;
13766 if (kind == PyUnicode_1BYTE_KIND) {
13767 char_size = 1;
13768 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13769 share_utf8 = 1;
13770 }
13771 else if (kind == PyUnicode_2BYTE_KIND) {
13772 char_size = 2;
13773 if (sizeof(wchar_t) == 2)
13774 share_wstr = 1;
13775 }
13776 else {
13777 assert(kind == PyUnicode_4BYTE_KIND);
13778 char_size = 4;
13779 if (sizeof(wchar_t) == 4)
13780 share_wstr = 1;
13781 }
13782
13783 /* Ensure we won't overflow the length. */
13784 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13785 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013786 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013787 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013788 data = PyObject_MALLOC((length + 1) * char_size);
13789 if (data == NULL) {
13790 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013791 goto onError;
13792 }
13793
Victor Stinnerc3c74152011-10-02 20:39:55 +020013794 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013795 if (share_utf8) {
13796 _PyUnicode_UTF8_LENGTH(self) = length;
13797 _PyUnicode_UTF8(self) = data;
13798 }
13799 if (share_wstr) {
13800 _PyUnicode_WSTR_LENGTH(self) = length;
13801 _PyUnicode_WSTR(self) = (wchar_t *)data;
13802 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013803
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013804 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013805 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013806 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013807#ifdef Py_DEBUG
13808 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13809#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013810 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013811 return (PyObject *)self;
13812
13813onError:
13814 Py_DECREF(unicode);
13815 Py_DECREF(self);
13816 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013817}
13818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013819PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013820 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013821\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013822Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013823encoding defaults to the current default string encoding.\n\
13824errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013825
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013826static PyObject *unicode_iter(PyObject *seq);
13827
Guido van Rossumd57fd912000-03-10 22:53:23 +000013828PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013829 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013830 "str", /* tp_name */
13831 sizeof(PyUnicodeObject), /* tp_size */
13832 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013833 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013834 (destructor)unicode_dealloc, /* tp_dealloc */
13835 0, /* tp_print */
13836 0, /* tp_getattr */
13837 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013838 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013839 unicode_repr, /* tp_repr */
13840 &unicode_as_number, /* tp_as_number */
13841 &unicode_as_sequence, /* tp_as_sequence */
13842 &unicode_as_mapping, /* tp_as_mapping */
13843 (hashfunc) unicode_hash, /* tp_hash*/
13844 0, /* tp_call*/
13845 (reprfunc) unicode_str, /* tp_str */
13846 PyObject_GenericGetAttr, /* tp_getattro */
13847 0, /* tp_setattro */
13848 0, /* tp_as_buffer */
13849 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013850 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013851 unicode_doc, /* tp_doc */
13852 0, /* tp_traverse */
13853 0, /* tp_clear */
13854 PyUnicode_RichCompare, /* tp_richcompare */
13855 0, /* tp_weaklistoffset */
13856 unicode_iter, /* tp_iter */
13857 0, /* tp_iternext */
13858 unicode_methods, /* tp_methods */
13859 0, /* tp_members */
13860 0, /* tp_getset */
13861 &PyBaseObject_Type, /* tp_base */
13862 0, /* tp_dict */
13863 0, /* tp_descr_get */
13864 0, /* tp_descr_set */
13865 0, /* tp_dictoffset */
13866 0, /* tp_init */
13867 0, /* tp_alloc */
13868 unicode_new, /* tp_new */
13869 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013870};
13871
13872/* Initialize the Unicode implementation */
13873
Victor Stinner3a50e702011-10-18 21:21:00 +020013874int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013875{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013876 int i;
13877
Thomas Wouters477c8d52006-05-27 19:21:47 +000013878 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013879 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013880 0x000A, /* LINE FEED */
13881 0x000D, /* CARRIAGE RETURN */
13882 0x001C, /* FILE SEPARATOR */
13883 0x001D, /* GROUP SEPARATOR */
13884 0x001E, /* RECORD SEPARATOR */
13885 0x0085, /* NEXT LINE */
13886 0x2028, /* LINE SEPARATOR */
13887 0x2029, /* PARAGRAPH SEPARATOR */
13888 };
13889
Fred Drakee4315f52000-05-09 19:53:39 +000013890 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013891 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013892 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013893 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013894 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013895
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013896 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013897 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013898 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013899 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013900
13901 /* initialize the linebreak bloom filter */
13902 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013903 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013904 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013905
13906 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013907
13908#ifdef HAVE_MBCS
13909 winver.dwOSVersionInfoSize = sizeof(winver);
13910 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13911 PyErr_SetFromWindowsErr(0);
13912 return -1;
13913 }
13914#endif
13915 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013916}
13917
13918/* Finalize the Unicode implementation */
13919
Christian Heimesa156e092008-02-16 07:38:31 +000013920int
13921PyUnicode_ClearFreeList(void)
13922{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013923 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013924}
13925
Guido van Rossumd57fd912000-03-10 22:53:23 +000013926void
Thomas Wouters78890102000-07-22 19:25:51 +000013927_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013928{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013929 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013930
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013931 Py_XDECREF(unicode_empty);
13932 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013933
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013934 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013935 if (unicode_latin1[i]) {
13936 Py_DECREF(unicode_latin1[i]);
13937 unicode_latin1[i] = NULL;
13938 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013939 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013940 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013941 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013942}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013943
Walter Dörwald16807132007-05-25 13:52:07 +000013944void
13945PyUnicode_InternInPlace(PyObject **p)
13946{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013947 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013948 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013949#ifdef Py_DEBUG
13950 assert(s != NULL);
13951 assert(_PyUnicode_CHECK(s));
13952#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013953 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013954 return;
13955#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 /* If it's a subclass, we don't really know what putting
13957 it in the interned dict might do. */
13958 if (!PyUnicode_CheckExact(s))
13959 return;
13960 if (PyUnicode_CHECK_INTERNED(s))
13961 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013962 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013963 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013964 return;
13965 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013966 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 if (interned == NULL) {
13968 interned = PyDict_New();
13969 if (interned == NULL) {
13970 PyErr_Clear(); /* Don't leave an exception */
13971 return;
13972 }
13973 }
13974 /* It might be that the GetItem call fails even
13975 though the key is present in the dictionary,
13976 namely when this happens during a stack overflow. */
13977 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013978 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013979 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013980
Benjamin Peterson29060642009-01-31 22:14:21 +000013981 if (t) {
13982 Py_INCREF(t);
13983 Py_DECREF(*p);
13984 *p = t;
13985 return;
13986 }
Walter Dörwald16807132007-05-25 13:52:07 +000013987
Benjamin Peterson14339b62009-01-31 16:36:08 +000013988 PyThreadState_GET()->recursion_critical = 1;
13989 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13990 PyErr_Clear();
13991 PyThreadState_GET()->recursion_critical = 0;
13992 return;
13993 }
13994 PyThreadState_GET()->recursion_critical = 0;
13995 /* The two references in interned are not counted by refcnt.
13996 The deallocator will take care of this */
13997 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013998 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013999}
14000
14001void
14002PyUnicode_InternImmortal(PyObject **p)
14003{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014004 PyUnicodeObject *u = (PyUnicodeObject *)*p;
14005
Benjamin Peterson14339b62009-01-31 16:36:08 +000014006 PyUnicode_InternInPlace(p);
14007 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014008 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014009 Py_INCREF(*p);
14010 }
Walter Dörwald16807132007-05-25 13:52:07 +000014011}
14012
14013PyObject *
14014PyUnicode_InternFromString(const char *cp)
14015{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014016 PyObject *s = PyUnicode_FromString(cp);
14017 if (s == NULL)
14018 return NULL;
14019 PyUnicode_InternInPlace(&s);
14020 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014021}
14022
Alexander Belopolsky40018472011-02-26 01:02:56 +000014023void
14024_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014025{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014026 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014027 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014028 Py_ssize_t i, n;
14029 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014030
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 if (interned == NULL || !PyDict_Check(interned))
14032 return;
14033 keys = PyDict_Keys(interned);
14034 if (keys == NULL || !PyList_Check(keys)) {
14035 PyErr_Clear();
14036 return;
14037 }
Walter Dörwald16807132007-05-25 13:52:07 +000014038
Benjamin Peterson14339b62009-01-31 16:36:08 +000014039 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14040 detector, interned unicode strings are not forcibly deallocated;
14041 rather, we give them their stolen references back, and then clear
14042 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014043
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 n = PyList_GET_SIZE(keys);
14045 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014046 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014047 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014048 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014049 if (PyUnicode_READY(s) == -1) {
14050 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014051 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014053 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014054 case SSTATE_NOT_INTERNED:
14055 /* XXX Shouldn't happen */
14056 break;
14057 case SSTATE_INTERNED_IMMORTAL:
14058 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014059 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014060 break;
14061 case SSTATE_INTERNED_MORTAL:
14062 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014063 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014064 break;
14065 default:
14066 Py_FatalError("Inconsistent interned string state.");
14067 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014068 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014069 }
14070 fprintf(stderr, "total size of all interned strings: "
14071 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14072 "mortal/immortal\n", mortal_size, immortal_size);
14073 Py_DECREF(keys);
14074 PyDict_Clear(interned);
14075 Py_DECREF(interned);
14076 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014077}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014078
14079
14080/********************* Unicode Iterator **************************/
14081
14082typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 PyObject_HEAD
14084 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014085 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014086} unicodeiterobject;
14087
14088static void
14089unicodeiter_dealloc(unicodeiterobject *it)
14090{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014091 _PyObject_GC_UNTRACK(it);
14092 Py_XDECREF(it->it_seq);
14093 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014094}
14095
14096static int
14097unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14098{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 Py_VISIT(it->it_seq);
14100 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014101}
14102
14103static PyObject *
14104unicodeiter_next(unicodeiterobject *it)
14105{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014106 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014107
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 assert(it != NULL);
14109 seq = it->it_seq;
14110 if (seq == NULL)
14111 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014112 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014113
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014114 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14115 int kind = PyUnicode_KIND(seq);
14116 void *data = PyUnicode_DATA(seq);
14117 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14118 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014119 if (item != NULL)
14120 ++it->it_index;
14121 return item;
14122 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014123
Benjamin Peterson14339b62009-01-31 16:36:08 +000014124 Py_DECREF(seq);
14125 it->it_seq = NULL;
14126 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014127}
14128
14129static PyObject *
14130unicodeiter_len(unicodeiterobject *it)
14131{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 Py_ssize_t len = 0;
14133 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014134 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014136}
14137
14138PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14139
14140static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014141 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014142 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014143 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014144};
14145
14146PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14148 "str_iterator", /* tp_name */
14149 sizeof(unicodeiterobject), /* tp_basicsize */
14150 0, /* tp_itemsize */
14151 /* methods */
14152 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14153 0, /* tp_print */
14154 0, /* tp_getattr */
14155 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014156 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014157 0, /* tp_repr */
14158 0, /* tp_as_number */
14159 0, /* tp_as_sequence */
14160 0, /* tp_as_mapping */
14161 0, /* tp_hash */
14162 0, /* tp_call */
14163 0, /* tp_str */
14164 PyObject_GenericGetAttr, /* tp_getattro */
14165 0, /* tp_setattro */
14166 0, /* tp_as_buffer */
14167 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14168 0, /* tp_doc */
14169 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14170 0, /* tp_clear */
14171 0, /* tp_richcompare */
14172 0, /* tp_weaklistoffset */
14173 PyObject_SelfIter, /* tp_iter */
14174 (iternextfunc)unicodeiter_next, /* tp_iternext */
14175 unicodeiter_methods, /* tp_methods */
14176 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014177};
14178
14179static PyObject *
14180unicode_iter(PyObject *seq)
14181{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014182 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014183
Benjamin Peterson14339b62009-01-31 16:36:08 +000014184 if (!PyUnicode_Check(seq)) {
14185 PyErr_BadInternalCall();
14186 return NULL;
14187 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014188 if (PyUnicode_READY(seq) == -1)
14189 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014190 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14191 if (it == NULL)
14192 return NULL;
14193 it->it_index = 0;
14194 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014195 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014196 _PyObject_GC_TRACK(it);
14197 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014198}
14199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014200#define UNIOP(x) Py_UNICODE_##x
14201#define UNIOP_t Py_UNICODE
14202#include "uniops.h"
14203#undef UNIOP
14204#undef UNIOP_t
14205#define UNIOP(x) Py_UCS4_##x
14206#define UNIOP_t Py_UCS4
14207#include "uniops.h"
14208#undef UNIOP
14209#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000014210
Victor Stinner71133ff2010-09-01 23:43:53 +000014211Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014212PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014213{
Victor Stinner577db2c2011-10-11 22:12:48 +020014214 Py_UNICODE *u, *copy;
Victor Stinner71133ff2010-09-01 23:43:53 +000014215 Py_ssize_t size;
14216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014217 if (!PyUnicode_Check(unicode)) {
14218 PyErr_BadArgument();
14219 return NULL;
14220 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014221 u = PyUnicode_AsUnicode(unicode);
Victor Stinner577db2c2011-10-11 22:12:48 +020014222 if (u == NULL)
14223 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014224 /* Ensure we won't overflow the size. */
14225 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
14226 PyErr_NoMemory();
14227 return NULL;
14228 }
14229 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
14230 size *= sizeof(Py_UNICODE);
14231 copy = PyMem_Malloc(size);
14232 if (copy == NULL) {
14233 PyErr_NoMemory();
14234 return NULL;
14235 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014236 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014237 return copy;
14238}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014239
Georg Brandl66c221e2010-10-14 07:04:07 +000014240/* A _string module, to export formatter_parser and formatter_field_name_split
14241 to the string.Formatter class implemented in Python. */
14242
14243static PyMethodDef _string_methods[] = {
14244 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14245 METH_O, PyDoc_STR("split the argument as a field name")},
14246 {"formatter_parser", (PyCFunction) formatter_parser,
14247 METH_O, PyDoc_STR("parse the argument as a format string")},
14248 {NULL, NULL}
14249};
14250
14251static struct PyModuleDef _string_module = {
14252 PyModuleDef_HEAD_INIT,
14253 "_string",
14254 PyDoc_STR("string helper module"),
14255 0,
14256 _string_methods,
14257 NULL,
14258 NULL,
14259 NULL,
14260 NULL
14261};
14262
14263PyMODINIT_FUNC
14264PyInit__string(void)
14265{
14266 return PyModule_Create(&_string_module);
14267}
14268
14269
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014270#ifdef __cplusplus
14271}
14272#endif