blob: 46b55909a64682302c50dcf37f6fbc31db6e41d6 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
119 _PyUnicode_Ready((PyObject *)(op))))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
257 const Py_UNICODE *unicode, Py_ssize_t size,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Martin v. Löwis9e816682011-11-02 12:45:42 +0100260static void
261raise_encode_exception_obj(PyObject **exceptionObject,
262 const char *encoding,
263 PyObject *unicode,
264 Py_ssize_t startpos, Py_ssize_t endpos,
265 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000266
Christian Heimes190d79e2008-01-30 11:58:22 +0000267/* Same for linebreaks */
268static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000271/* 0x000B, * LINE TABULATION */
272/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000273/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000274 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000275 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000276/* 0x001C, * FILE SEPARATOR */
277/* 0x001D, * GROUP SEPARATOR */
278/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 1, 1, 1, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000284
Benjamin Peterson14339b62009-01-31 16:36:08 +0000285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0,
287 0, 0, 0, 0, 0, 0, 0, 0,
288 0, 0, 0, 0, 0, 0, 0, 0,
289 0, 0, 0, 0, 0, 0, 0, 0,
290 0, 0, 0, 0, 0, 0, 0, 0,
291 0, 0, 0, 0, 0, 0, 0, 0,
292 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000293};
294
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300295/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
296 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000297Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000298PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000299{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000300#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000301 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000302#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000303 /* This is actually an illegal character, so it should
304 not be passed to unichr. */
305 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000306#endif
307}
308
Victor Stinner910337b2011-10-03 03:20:16 +0200309#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200310int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200311/* FIXME: use PyObject* type for op */
312_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200313{
314 PyASCIIObject *ascii;
315 unsigned int kind;
316
317 assert(PyUnicode_Check(op));
318
319 ascii = (PyASCIIObject *)op;
320 kind = ascii->state.kind;
321
Victor Stinnera3b334d2011-10-03 13:53:37 +0200322 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200324 assert(ascii->state.ready == 1);
325 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200326 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200327 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200328 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200329
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 if (ascii->state.compact == 1) {
331 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200332 assert(kind == PyUnicode_1BYTE_KIND
333 || kind == PyUnicode_2BYTE_KIND
334 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200335 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200336 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200337 assert (compact->utf8 != data);
338 } else {
339 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
340
341 data = unicode->data.any;
342 if (kind == PyUnicode_WCHAR_KIND) {
343 assert(ascii->state.compact == 0);
344 assert(ascii->state.ascii == 0);
345 assert(ascii->state.ready == 0);
346 assert(ascii->wstr != NULL);
347 assert(data == NULL);
348 assert(compact->utf8 == NULL);
349 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
350 }
351 else {
352 assert(kind == PyUnicode_1BYTE_KIND
353 || kind == PyUnicode_2BYTE_KIND
354 || kind == PyUnicode_4BYTE_KIND);
355 assert(ascii->state.compact == 0);
356 assert(ascii->state.ready == 1);
357 assert(data != NULL);
358 if (ascii->state.ascii) {
359 assert (compact->utf8 == data);
360 assert (compact->utf8_length == ascii->length);
361 }
362 else
363 assert (compact->utf8 != data);
364 }
365 }
366 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200367 if (
368#if SIZEOF_WCHAR_T == 2
369 kind == PyUnicode_2BYTE_KIND
370#else
371 kind == PyUnicode_4BYTE_KIND
372#endif
373 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200374 {
375 assert(ascii->wstr == data);
376 assert(compact->wstr_length == ascii->length);
377 } else
378 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200380
381 if (compact->utf8 == NULL)
382 assert(compact->utf8_length == 0);
383 if (ascii->wstr == NULL)
384 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200385 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200386 /* check that the best kind is used */
387 if (check_content && kind != PyUnicode_WCHAR_KIND)
388 {
389 Py_ssize_t i;
390 Py_UCS4 maxchar = 0;
391 void *data = PyUnicode_DATA(ascii);
392 for (i=0; i < ascii->length; i++)
393 {
394 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
395 if (ch > maxchar)
396 maxchar = ch;
397 }
398 if (kind == PyUnicode_1BYTE_KIND) {
399 if (ascii->state.ascii == 0)
400 assert(maxchar >= 128);
401 else
402 assert(maxchar < 128);
403 }
404 else if (kind == PyUnicode_2BYTE_KIND)
405 assert(maxchar >= 0x100);
406 else
407 assert(maxchar >= 0x10000);
408 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200409 if (check_content && !unicode_is_singleton((PyObject*)ascii))
410 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400411 return 1;
412}
Victor Stinner910337b2011-10-03 03:20:16 +0200413#endif
414
Victor Stinner3a50e702011-10-18 21:21:00 +0200415#ifdef HAVE_MBCS
416static OSVERSIONINFOEX winver;
417#endif
418
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419/* --- Bloom Filters ----------------------------------------------------- */
420
421/* stuff to implement simple "bloom filters" for Unicode characters.
422 to keep things simple, we use a single bitmask, using the least 5
423 bits from each unicode characters as the bit index. */
424
425/* the linebreak mask is set up by Unicode_Init below */
426
Antoine Pitrouf068f942010-01-13 14:19:12 +0000427#if LONG_BIT >= 128
428#define BLOOM_WIDTH 128
429#elif LONG_BIT >= 64
430#define BLOOM_WIDTH 64
431#elif LONG_BIT >= 32
432#define BLOOM_WIDTH 32
433#else
434#error "LONG_BIT is smaller than 32"
435#endif
436
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437#define BLOOM_MASK unsigned long
438
439static BLOOM_MASK bloom_linebreak;
440
Antoine Pitrouf068f942010-01-13 14:19:12 +0000441#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
442#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Benjamin Peterson29060642009-01-31 22:14:21 +0000444#define BLOOM_LINEBREAK(ch) \
445 ((ch) < 128U ? ascii_linebreak[(ch)] : \
446 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Alexander Belopolsky40018472011-02-26 01:02:56 +0000448Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200449make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450{
451 /* calculate simple bloom-style bitmask for a given unicode string */
452
Antoine Pitrouf068f942010-01-13 14:19:12 +0000453 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 Py_ssize_t i;
455
456 mask = 0;
457 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200458 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459
460 return mask;
461}
462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200463#define BLOOM_MEMBER(mask, chr, str) \
464 (BLOOM(mask, chr) \
465 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000466
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200467/* Compilation of templated routines */
468
469#include "stringlib/asciilib.h"
470#include "stringlib/fastsearch.h"
471#include "stringlib/partition.h"
472#include "stringlib/split.h"
473#include "stringlib/count.h"
474#include "stringlib/find.h"
475#include "stringlib/find_max_char.h"
476#include "stringlib/localeutil.h"
477#include "stringlib/undef.h"
478
479#include "stringlib/ucs1lib.h"
480#include "stringlib/fastsearch.h"
481#include "stringlib/partition.h"
482#include "stringlib/split.h"
483#include "stringlib/count.h"
484#include "stringlib/find.h"
485#include "stringlib/find_max_char.h"
486#include "stringlib/localeutil.h"
487#include "stringlib/undef.h"
488
489#include "stringlib/ucs2lib.h"
490#include "stringlib/fastsearch.h"
491#include "stringlib/partition.h"
492#include "stringlib/split.h"
493#include "stringlib/count.h"
494#include "stringlib/find.h"
495#include "stringlib/find_max_char.h"
496#include "stringlib/localeutil.h"
497#include "stringlib/undef.h"
498
499#include "stringlib/ucs4lib.h"
500#include "stringlib/fastsearch.h"
501#include "stringlib/partition.h"
502#include "stringlib/split.h"
503#include "stringlib/count.h"
504#include "stringlib/find.h"
505#include "stringlib/find_max_char.h"
506#include "stringlib/localeutil.h"
507#include "stringlib/undef.h"
508
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200509#include "stringlib/unicodedefs.h"
510#include "stringlib/fastsearch.h"
511#include "stringlib/count.h"
512#include "stringlib/find.h"
513
Guido van Rossumd57fd912000-03-10 22:53:23 +0000514/* --- Unicode Object ----------------------------------------------------- */
515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200516static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200517fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
520 Py_ssize_t size, Py_UCS4 ch,
521 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200522{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200523 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
524
525 switch (kind) {
526 case PyUnicode_1BYTE_KIND:
527 {
528 Py_UCS1 ch1 = (Py_UCS1) ch;
529 if (ch1 == ch)
530 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
531 else
532 return -1;
533 }
534 case PyUnicode_2BYTE_KIND:
535 {
536 Py_UCS2 ch2 = (Py_UCS2) ch;
537 if (ch2 == ch)
538 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
539 else
540 return -1;
541 }
542 case PyUnicode_4BYTE_KIND:
543 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
544 default:
545 assert(0);
546 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200547 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200548}
549
Victor Stinnerfe226c02011-10-03 03:52:20 +0200550static PyObject*
551resize_compact(PyObject *unicode, Py_ssize_t length)
552{
553 Py_ssize_t char_size;
554 Py_ssize_t struct_size;
555 Py_ssize_t new_size;
556 int share_wstr;
557
558 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200559 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200560 if (PyUnicode_IS_COMPACT_ASCII(unicode))
561 struct_size = sizeof(PyASCIIObject);
562 else
563 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200564 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200565
566 _Py_DEC_REFTOTAL;
567 _Py_ForgetReference(unicode);
568
569 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
570 PyErr_NoMemory();
571 return NULL;
572 }
573 new_size = (struct_size + (length + 1) * char_size);
574
575 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
576 if (unicode == NULL) {
577 PyObject_Del(unicode);
578 PyErr_NoMemory();
579 return NULL;
580 }
581 _Py_NewReference(unicode);
582 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200583 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200585 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
586 _PyUnicode_WSTR_LENGTH(unicode) = length;
587 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200588 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
589 length, 0);
590 return unicode;
591}
592
Alexander Belopolsky40018472011-02-26 01:02:56 +0000593static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200594resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000595{
Victor Stinner95663112011-10-04 01:03:50 +0200596 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200597 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200598 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000599
Victor Stinner95663112011-10-04 01:03:50 +0200600 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200601
602 if (PyUnicode_IS_READY(unicode)) {
603 Py_ssize_t char_size;
604 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200605 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200606 void *data;
607
608 data = _PyUnicode_DATA_ANY(unicode);
609 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200610 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200611 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
612 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200613 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
614 {
615 PyObject_DEL(_PyUnicode_UTF8(unicode));
616 _PyUnicode_UTF8(unicode) = NULL;
617 _PyUnicode_UTF8_LENGTH(unicode) = 0;
618 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200619
620 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
621 PyErr_NoMemory();
622 return -1;
623 }
624 new_size = (length + 1) * char_size;
625
626 data = (PyObject *)PyObject_REALLOC(data, new_size);
627 if (data == NULL) {
628 PyErr_NoMemory();
629 return -1;
630 }
631 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200632 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200633 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_WSTR_LENGTH(unicode) = length;
635 }
636 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200637 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200638 _PyUnicode_UTF8_LENGTH(unicode) = length;
639 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 _PyUnicode_LENGTH(unicode) = length;
641 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200642 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200643 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200644 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200645 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200646 }
Victor Stinner95663112011-10-04 01:03:50 +0200647 assert(_PyUnicode_WSTR(unicode) != NULL);
648
649 /* check for integer overflow */
650 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
651 PyErr_NoMemory();
652 return -1;
653 }
654 wstr = _PyUnicode_WSTR(unicode);
655 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
656 if (!wstr) {
657 PyErr_NoMemory();
658 return -1;
659 }
660 _PyUnicode_WSTR(unicode) = wstr;
661 _PyUnicode_WSTR(unicode)[length] = 0;
662 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200663 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000664 return 0;
665}
666
Victor Stinnerfe226c02011-10-03 03:52:20 +0200667static PyObject*
668resize_copy(PyObject *unicode, Py_ssize_t length)
669{
670 Py_ssize_t copy_length;
671 if (PyUnicode_IS_COMPACT(unicode)) {
672 PyObject *copy;
673 assert(PyUnicode_IS_READY(unicode));
674
675 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
676 if (copy == NULL)
677 return NULL;
678
679 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200680 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200682 }
683 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200684 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200685 assert(_PyUnicode_WSTR(unicode) != NULL);
686 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200687 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200688 if (w == NULL)
689 return NULL;
690 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
691 copy_length = Py_MIN(copy_length, length);
692 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
693 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200694 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 }
696}
697
Guido van Rossumd57fd912000-03-10 22:53:23 +0000698/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000699 Ux0000 terminated; some code (e.g. new_identifier)
700 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000701
702 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000703 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000704
705*/
706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200707#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200708static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709#endif
710
Alexander Belopolsky40018472011-02-26 01:02:56 +0000711static PyUnicodeObject *
712_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000713{
714 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200715 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000716
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000718 if (length == 0 && unicode_empty != NULL) {
719 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200720 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000721 }
722
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000723 /* Ensure we won't overflow the size. */
724 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
725 return (PyUnicodeObject *)PyErr_NoMemory();
726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200727 if (length < 0) {
728 PyErr_SetString(PyExc_SystemError,
729 "Negative size passed to _PyUnicode_New");
730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000731 }
732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200733#ifdef Py_DEBUG
734 ++unicode_old_new_calls;
735#endif
736
737 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
738 if (unicode == NULL)
739 return NULL;
740 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
741 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
742 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000743 PyErr_NoMemory();
744 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200746
Jeremy Hyltond8082792003-09-16 19:41:39 +0000747 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000748 * the caller fails before initializing str -- unicode_resize()
749 * reads str[0], and the Keep-Alive optimization can keep memory
750 * allocated for str alive across a call to unicode_dealloc(unicode).
751 * We don't want unicode_resize to read uninitialized memory in
752 * that case.
753 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200754 _PyUnicode_WSTR(unicode)[0] = 0;
755 _PyUnicode_WSTR(unicode)[length] = 0;
756 _PyUnicode_WSTR_LENGTH(unicode) = length;
757 _PyUnicode_HASH(unicode) = -1;
758 _PyUnicode_STATE(unicode).interned = 0;
759 _PyUnicode_STATE(unicode).kind = 0;
760 _PyUnicode_STATE(unicode).compact = 0;
761 _PyUnicode_STATE(unicode).ready = 0;
762 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200763 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200764 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200765 _PyUnicode_UTF8(unicode) = NULL;
766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner67072932011-10-18 22:10:14 +0200767 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000768 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769
Benjamin Peterson29060642009-01-31 22:14:21 +0000770 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000771 /* XXX UNREF/NEWREF interface should be more symmetrical */
772 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000773 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000774 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000776}
777
Victor Stinnerf42dc442011-10-02 23:33:16 +0200778static const char*
779unicode_kind_name(PyObject *unicode)
780{
Victor Stinner42dfd712011-10-03 14:41:45 +0200781 /* don't check consistency: unicode_kind_name() is called from
782 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200783 if (!PyUnicode_IS_COMPACT(unicode))
784 {
785 if (!PyUnicode_IS_READY(unicode))
786 return "wstr";
787 switch(PyUnicode_KIND(unicode))
788 {
789 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200790 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200791 return "legacy ascii";
792 else
793 return "legacy latin1";
794 case PyUnicode_2BYTE_KIND:
795 return "legacy UCS2";
796 case PyUnicode_4BYTE_KIND:
797 return "legacy UCS4";
798 default:
799 return "<legacy invalid kind>";
800 }
801 }
802 assert(PyUnicode_IS_READY(unicode));
803 switch(PyUnicode_KIND(unicode))
804 {
805 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200806 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200807 return "ascii";
808 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200811 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200812 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200813 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200814 default:
815 return "<invalid compact kind>";
816 }
817}
818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200820static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821
822/* Functions wrapping macros for use in debugger */
823char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200824 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200825}
826
827void *_PyUnicode_compact_data(void *unicode) {
828 return _PyUnicode_COMPACT_DATA(unicode);
829}
830void *_PyUnicode_data(void *unicode){
831 printf("obj %p\n", unicode);
832 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
833 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
834 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
835 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
836 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
837 return PyUnicode_DATA(unicode);
838}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200839
840void
841_PyUnicode_Dump(PyObject *op)
842{
843 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
845 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
846 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200847
Victor Stinnera849a4b2011-10-03 12:12:11 +0200848 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200849 {
850 if (ascii->state.ascii)
851 data = (ascii + 1);
852 else
853 data = (compact + 1);
854 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 else
856 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200857 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
858
Victor Stinnera849a4b2011-10-03 12:12:11 +0200859 if (ascii->wstr == data)
860 printf("shared ");
861 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200862
Victor Stinnera3b334d2011-10-03 13:53:37 +0200863 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200864 printf(" (%zu), ", compact->wstr_length);
865 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
866 printf("shared ");
867 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200868 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200869 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200870}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871#endif
872
873PyObject *
874PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
875{
876 PyObject *obj;
877 PyCompactUnicodeObject *unicode;
878 void *data;
879 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200880 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200881 Py_ssize_t char_size;
882 Py_ssize_t struct_size;
883
884 /* Optimization for empty strings */
885 if (size == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200888 }
889
890#ifdef Py_DEBUG
891 ++unicode_new_new_calls;
892#endif
893
Victor Stinner9e9d6892011-10-04 01:02:02 +0200894 is_ascii = 0;
895 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 struct_size = sizeof(PyCompactUnicodeObject);
897 if (maxchar < 128) {
898 kind_state = PyUnicode_1BYTE_KIND;
899 char_size = 1;
900 is_ascii = 1;
901 struct_size = sizeof(PyASCIIObject);
902 }
903 else if (maxchar < 256) {
904 kind_state = PyUnicode_1BYTE_KIND;
905 char_size = 1;
906 }
907 else if (maxchar < 65536) {
908 kind_state = PyUnicode_2BYTE_KIND;
909 char_size = 2;
910 if (sizeof(wchar_t) == 2)
911 is_sharing = 1;
912 }
913 else {
914 kind_state = PyUnicode_4BYTE_KIND;
915 char_size = 4;
916 if (sizeof(wchar_t) == 4)
917 is_sharing = 1;
918 }
919
920 /* Ensure we won't overflow the size. */
921 if (size < 0) {
922 PyErr_SetString(PyExc_SystemError,
923 "Negative size passed to PyUnicode_New");
924 return NULL;
925 }
926 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
927 return PyErr_NoMemory();
928
929 /* Duplicated allocation code from _PyObject_New() instead of a call to
930 * PyObject_New() so we are able to allocate space for the object and
931 * it's data buffer.
932 */
933 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
934 if (obj == NULL)
935 return PyErr_NoMemory();
936 obj = PyObject_INIT(obj, &PyUnicode_Type);
937 if (obj == NULL)
938 return NULL;
939
940 unicode = (PyCompactUnicodeObject *)obj;
941 if (is_ascii)
942 data = ((PyASCIIObject*)obj) + 1;
943 else
944 data = unicode + 1;
945 _PyUnicode_LENGTH(unicode) = size;
946 _PyUnicode_HASH(unicode) = -1;
947 _PyUnicode_STATE(unicode).interned = 0;
948 _PyUnicode_STATE(unicode).kind = kind_state;
949 _PyUnicode_STATE(unicode).compact = 1;
950 _PyUnicode_STATE(unicode).ready = 1;
951 _PyUnicode_STATE(unicode).ascii = is_ascii;
952 if (is_ascii) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 }
956 else if (kind_state == PyUnicode_1BYTE_KIND) {
957 ((char*)data)[size] = 0;
958 _PyUnicode_WSTR(unicode) = NULL;
959 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 }
963 else {
964 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200965 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200966 if (kind_state == PyUnicode_2BYTE_KIND)
967 ((Py_UCS2*)data)[size] = 0;
968 else /* kind_state == PyUnicode_4BYTE_KIND */
969 ((Py_UCS4*)data)[size] = 0;
970 if (is_sharing) {
971 _PyUnicode_WSTR_LENGTH(unicode) = size;
972 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
973 }
974 else {
975 _PyUnicode_WSTR_LENGTH(unicode) = 0;
976 _PyUnicode_WSTR(unicode) = NULL;
977 }
978 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200979 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 return obj;
981}
982
983#if SIZEOF_WCHAR_T == 2
984/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
985 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200986 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987
988 This function assumes that unicode can hold one more code point than wstr
989 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200990static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200991unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200992 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993{
994 const wchar_t *iter;
995 Py_UCS4 *ucs4_out;
996
Victor Stinner910337b2011-10-03 03:20:16 +0200997 assert(unicode != NULL);
998 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200999 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1000 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1001
1002 for (iter = begin; iter < end; ) {
1003 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1004 _PyUnicode_GET_LENGTH(unicode)));
1005 if (*iter >= 0xD800 && *iter <= 0xDBFF
1006 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1007 {
1008 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1009 iter += 2;
1010 }
1011 else {
1012 *ucs4_out++ = *iter;
1013 iter++;
1014 }
1015 }
1016 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1017 _PyUnicode_GET_LENGTH(unicode)));
1018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001019}
1020#endif
1021
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022static int
1023_PyUnicode_Dirty(PyObject *unicode)
1024{
Victor Stinner910337b2011-10-03 03:20:16 +02001025 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001026 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001027 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001028 "Cannot modify a string having more than 1 reference");
1029 return -1;
1030 }
1031 _PyUnicode_DIRTY(unicode);
1032 return 0;
1033}
1034
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001035static int
1036_copy_characters(PyObject *to, Py_ssize_t to_start,
1037 PyObject *from, Py_ssize_t from_start,
1038 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001040 unsigned int from_kind, to_kind;
1041 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001042 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001044 assert(PyUnicode_Check(from));
1045 assert(PyUnicode_Check(to));
1046 assert(PyUnicode_IS_READY(from));
1047 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001049 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1050 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1051 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001053 if (how_many == 0)
1054 return 0;
1055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001057 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001059 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001061#ifdef Py_DEBUG
1062 if (!check_maxchar
1063 && (from_kind > to_kind
1064 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001065 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001066 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1067 Py_UCS4 ch;
1068 Py_ssize_t i;
1069 for (i=0; i < how_many; i++) {
1070 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1071 assert(ch <= to_maxchar);
1072 }
1073 }
1074#endif
1075 fast = (from_kind == to_kind);
1076 if (check_maxchar
1077 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1078 {
1079 /* deny latin1 => ascii */
1080 fast = 0;
1081 }
1082
1083 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001084 Py_MEMCPY((char*)to_data + to_kind * to_start,
1085 (char*)from_data + from_kind * from_start,
1086 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001088 else if (from_kind == PyUnicode_1BYTE_KIND
1089 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001090 {
1091 _PyUnicode_CONVERT_BYTES(
1092 Py_UCS1, Py_UCS2,
1093 PyUnicode_1BYTE_DATA(from) + from_start,
1094 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1095 PyUnicode_2BYTE_DATA(to) + to_start
1096 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001097 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001098 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001099 && to_kind == PyUnicode_4BYTE_KIND)
1100 {
1101 _PyUnicode_CONVERT_BYTES(
1102 Py_UCS1, Py_UCS4,
1103 PyUnicode_1BYTE_DATA(from) + from_start,
1104 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1105 PyUnicode_4BYTE_DATA(to) + to_start
1106 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001107 }
1108 else if (from_kind == PyUnicode_2BYTE_KIND
1109 && to_kind == PyUnicode_4BYTE_KIND)
1110 {
1111 _PyUnicode_CONVERT_BYTES(
1112 Py_UCS2, Py_UCS4,
1113 PyUnicode_2BYTE_DATA(from) + from_start,
1114 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1115 PyUnicode_4BYTE_DATA(to) + to_start
1116 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001117 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001118 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 /* check if max_char(from substring) <= max_char(to) */
1120 if (from_kind > to_kind
1121 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001122 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001123 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001124 /* slow path to check for character overflow */
1125 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001126 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 Py_ssize_t i;
1128
Victor Stinner56c161a2011-10-06 02:47:11 +02001129#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001130 for (i=0; i < how_many; i++) {
1131 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001132 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001133 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1134 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001135#else
1136 if (!check_maxchar) {
1137 for (i=0; i < how_many; i++) {
1138 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1139 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1140 }
1141 }
1142 else {
1143 for (i=0; i < how_many; i++) {
1144 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1145 if (ch > to_maxchar)
1146 return 1;
1147 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1148 }
1149 }
1150#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001153 assert(0 && "inconsistent state");
1154 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001155 }
1156 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 return 0;
1158}
1159
1160static void
1161copy_characters(PyObject *to, Py_ssize_t to_start,
1162 PyObject *from, Py_ssize_t from_start,
1163 Py_ssize_t how_many)
1164{
1165 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1166}
1167
1168Py_ssize_t
1169PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1170 PyObject *from, Py_ssize_t from_start,
1171 Py_ssize_t how_many)
1172{
1173 int err;
1174
1175 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1176 PyErr_BadInternalCall();
1177 return -1;
1178 }
1179
1180 if (PyUnicode_READY(from))
1181 return -1;
1182 if (PyUnicode_READY(to))
1183 return -1;
1184
1185 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1186 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1187 PyErr_Format(PyExc_SystemError,
1188 "Cannot write %zi characters at %zi "
1189 "in a string of %zi characters",
1190 how_many, to_start, PyUnicode_GET_LENGTH(to));
1191 return -1;
1192 }
1193
1194 if (how_many == 0)
1195 return 0;
1196
1197 if (_PyUnicode_Dirty(to))
1198 return -1;
1199
1200 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1201 if (err) {
1202 PyErr_Format(PyExc_SystemError,
1203 "Cannot copy %s characters "
1204 "into a string of %s characters",
1205 unicode_kind_name(from),
1206 unicode_kind_name(to));
1207 return -1;
1208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210}
1211
Victor Stinner17222162011-09-28 22:15:37 +02001212/* Find the maximum code point and count the number of surrogate pairs so a
1213 correct string length can be computed before converting a string to UCS4.
1214 This function counts single surrogates as a character and not as a pair.
1215
1216 Return 0 on success, or -1 on error. */
1217static int
1218find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1219 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220{
1221 const wchar_t *iter;
1222
Victor Stinnerc53be962011-10-02 21:33:54 +02001223 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 *num_surrogates = 0;
1225 *maxchar = 0;
1226
1227 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001228 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001230#if SIZEOF_WCHAR_T != 2
1231 if (*maxchar >= 0x10000)
1232 return 0;
1233#endif
1234 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235#if SIZEOF_WCHAR_T == 2
1236 if (*iter >= 0xD800 && *iter <= 0xDBFF
1237 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1238 {
1239 Py_UCS4 surrogate_val;
1240 surrogate_val = (((iter[0] & 0x3FF)<<10)
1241 | (iter[1] & 0x3FF)) + 0x10000;
1242 ++(*num_surrogates);
1243 if (surrogate_val > *maxchar)
1244 *maxchar = surrogate_val;
1245 iter += 2;
1246 }
1247 else
1248 iter++;
1249#else
1250 iter++;
1251#endif
1252 }
1253 return 0;
1254}
1255
1256#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001257static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258#endif
1259
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001260static int
1261unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001263 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 wchar_t *end;
1265 Py_UCS4 maxchar = 0;
1266 Py_ssize_t num_surrogates;
1267#if SIZEOF_WCHAR_T == 2
1268 Py_ssize_t length_wo_surrogates;
1269#endif
1270
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001271 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001272 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001273
Georg Brandl7597add2011-10-05 16:36:47 +02001274 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001275 strings were created using _PyObject_New() and where no canonical
1276 representation (the str field) has been set yet aka strings
1277 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001278 assert(_PyUnicode_CHECK(unicode));
1279 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001280 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001281 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001282 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001283 /* Actually, it should neither be interned nor be anything else: */
1284 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285
1286#ifdef Py_DEBUG
1287 ++unicode_ready_calls;
1288#endif
1289
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001290#ifdef Py_DEBUG
1291 assert(!replace || Py_REFCNT(unicode) == 1);
1292#else
1293 if (replace && Py_REFCNT(unicode) != 1)
1294 replace = 0;
1295#endif
1296 if (replace) {
1297 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1298 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1299 /* Optimization for empty strings */
1300 if (len == 0) {
1301 Py_INCREF(unicode_empty);
1302 Py_DECREF(*p_obj);
1303 *p_obj = unicode_empty;
1304 return 0;
1305 }
1306 if (len == 1 && wstr[0] < 256) {
1307 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1308 if (latin1_char == NULL)
1309 return -1;
1310 Py_DECREF(*p_obj);
1311 *p_obj = latin1_char;
1312 return 0;
1313 }
1314 }
1315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001317 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001318 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320
1321 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001322 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1323 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 PyErr_NoMemory();
1325 return -1;
1326 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001327 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328 _PyUnicode_WSTR(unicode), end,
1329 PyUnicode_1BYTE_DATA(unicode));
1330 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1331 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1332 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1333 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001334 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001335 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337 }
1338 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001339 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001340 _PyUnicode_UTF8(unicode) = NULL;
1341 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 }
1343 PyObject_FREE(_PyUnicode_WSTR(unicode));
1344 _PyUnicode_WSTR(unicode) = NULL;
1345 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1346 }
1347 /* In this case we might have to convert down from 4-byte native
1348 wchar_t to 2-byte unicode. */
1349 else if (maxchar < 65536) {
1350 assert(num_surrogates == 0 &&
1351 "FindMaxCharAndNumSurrogatePairs() messed up");
1352
Victor Stinner506f5922011-09-28 22:34:18 +02001353#if SIZEOF_WCHAR_T == 2
1354 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001355 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001356 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1357 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1358 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001359 _PyUnicode_UTF8(unicode) = NULL;
1360 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001361#else
1362 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001363 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001364 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001365 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001366 PyErr_NoMemory();
1367 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 }
Victor Stinner506f5922011-09-28 22:34:18 +02001369 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1370 _PyUnicode_WSTR(unicode), end,
1371 PyUnicode_2BYTE_DATA(unicode));
1372 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1373 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1374 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001375 _PyUnicode_UTF8(unicode) = NULL;
1376 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001377 PyObject_FREE(_PyUnicode_WSTR(unicode));
1378 _PyUnicode_WSTR(unicode) = NULL;
1379 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1380#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 }
1382 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1383 else {
1384#if SIZEOF_WCHAR_T == 2
1385 /* in case the native representation is 2-bytes, we need to allocate a
1386 new normalized 4-byte version. */
1387 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1389 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 PyErr_NoMemory();
1391 return -1;
1392 }
1393 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1394 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001395 _PyUnicode_UTF8(unicode) = NULL;
1396 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001397 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1398 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001399 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 PyObject_FREE(_PyUnicode_WSTR(unicode));
1401 _PyUnicode_WSTR(unicode) = NULL;
1402 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1403#else
1404 assert(num_surrogates == 0);
1405
Victor Stinnerc3c74152011-10-02 20:39:55 +02001406 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001408 _PyUnicode_UTF8(unicode) = NULL;
1409 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1411#endif
1412 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1413 }
1414 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001415 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416 return 0;
1417}
1418
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001419int
1420_PyUnicode_ReadyReplace(PyObject **op)
1421{
1422 return unicode_ready(op, 1);
1423}
1424
1425int
1426_PyUnicode_Ready(PyObject *op)
1427{
1428 return unicode_ready(&op, 0);
1429}
1430
Alexander Belopolsky40018472011-02-26 01:02:56 +00001431static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001432unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001433{
Walter Dörwald16807132007-05-25 13:52:07 +00001434 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001435 case SSTATE_NOT_INTERNED:
1436 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001437
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 case SSTATE_INTERNED_MORTAL:
1439 /* revive dead object temporarily for DelItem */
1440 Py_REFCNT(unicode) = 3;
1441 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1442 Py_FatalError(
1443 "deletion of interned string failed");
1444 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001445
Benjamin Peterson29060642009-01-31 22:14:21 +00001446 case SSTATE_INTERNED_IMMORTAL:
1447 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001448
Benjamin Peterson29060642009-01-31 22:14:21 +00001449 default:
1450 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001451 }
1452
Victor Stinner03490912011-10-03 23:45:12 +02001453 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001454 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001455 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001456 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001457
1458 if (PyUnicode_IS_COMPACT(unicode)) {
1459 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001460 }
1461 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 if (_PyUnicode_DATA_ANY(unicode))
1463 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001464 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001465 }
1466}
1467
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001468#ifdef Py_DEBUG
1469static int
1470unicode_is_singleton(PyObject *unicode)
1471{
1472 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1473 if (unicode == unicode_empty)
1474 return 1;
1475 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1476 {
1477 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1478 if (ch < 256 && unicode_latin1[ch] == unicode)
1479 return 1;
1480 }
1481 return 0;
1482}
1483#endif
1484
Alexander Belopolsky40018472011-02-26 01:02:56 +00001485static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001486unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001487{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001488 if (Py_REFCNT(unicode) != 1)
1489 return 0;
1490 if (PyUnicode_CHECK_INTERNED(unicode))
1491 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001492#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001493 /* singleton refcount is greater than 1 */
1494 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001495#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001496 return 1;
1497}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001498
Victor Stinnerfe226c02011-10-03 03:52:20 +02001499static int
1500unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1501{
1502 PyObject *unicode;
1503 Py_ssize_t old_length;
1504
1505 assert(p_unicode != NULL);
1506 unicode = *p_unicode;
1507
1508 assert(unicode != NULL);
1509 assert(PyUnicode_Check(unicode));
1510 assert(0 <= length);
1511
Victor Stinner910337b2011-10-03 03:20:16 +02001512 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001513 old_length = PyUnicode_WSTR_LENGTH(unicode);
1514 else
1515 old_length = PyUnicode_GET_LENGTH(unicode);
1516 if (old_length == length)
1517 return 0;
1518
Victor Stinnerfe226c02011-10-03 03:52:20 +02001519 if (!unicode_resizable(unicode)) {
1520 PyObject *copy = resize_copy(unicode, length);
1521 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001522 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001523 Py_DECREF(*p_unicode);
1524 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001526 }
1527
Victor Stinnerfe226c02011-10-03 03:52:20 +02001528 if (PyUnicode_IS_COMPACT(unicode)) {
1529 *p_unicode = resize_compact(unicode, length);
1530 if (*p_unicode == NULL)
1531 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001532 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001533 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001534 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001535 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001536}
1537
Alexander Belopolsky40018472011-02-26 01:02:56 +00001538int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001539PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001540{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001541 PyObject *unicode;
1542 if (p_unicode == NULL) {
1543 PyErr_BadInternalCall();
1544 return -1;
1545 }
1546 unicode = *p_unicode;
1547 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1548 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1549 {
1550 PyErr_BadInternalCall();
1551 return -1;
1552 }
1553 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001554}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001555
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001556static PyObject*
1557get_latin1_char(unsigned char ch)
1558{
Victor Stinnera464fc12011-10-02 20:39:30 +02001559 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001560 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001561 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001562 if (!unicode)
1563 return NULL;
1564 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001565 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001566 unicode_latin1[ch] = unicode;
1567 }
1568 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001569 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001570}
1571
Alexander Belopolsky40018472011-02-26 01:02:56 +00001572PyObject *
1573PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001574{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001575 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001576 Py_UCS4 maxchar = 0;
1577 Py_ssize_t num_surrogates;
1578
1579 if (u == NULL)
1580 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001581
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001582 /* If the Unicode data is known at construction time, we can apply
1583 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001585 /* Optimization for empty strings */
1586 if (size == 0 && unicode_empty != NULL) {
1587 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001588 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001589 }
Tim Petersced69f82003-09-16 20:30:58 +00001590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001591 /* Single character Unicode objects in the Latin-1 range are
1592 shared when using this constructor */
1593 if (size == 1 && *u < 256)
1594 return get_latin1_char((unsigned char)*u);
1595
1596 /* If not empty and not single character, copy the Unicode data
1597 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001598 if (find_maxchar_surrogates(u, u + size,
1599 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001600 return NULL;
1601
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001602 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001604 if (!unicode)
1605 return NULL;
1606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001607 switch (PyUnicode_KIND(unicode)) {
1608 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001609 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001610 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1611 break;
1612 case PyUnicode_2BYTE_KIND:
1613#if Py_UNICODE_SIZE == 2
1614 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1615#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001616 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1618#endif
1619 break;
1620 case PyUnicode_4BYTE_KIND:
1621#if SIZEOF_WCHAR_T == 2
1622 /* This is the only case which has to process surrogates, thus
1623 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001624 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001625#else
1626 assert(num_surrogates == 0);
1627 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1628#endif
1629 break;
1630 default:
1631 assert(0 && "Impossible state");
1632 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001633
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001634 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001635 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636}
1637
Alexander Belopolsky40018472011-02-26 01:02:56 +00001638PyObject *
1639PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001640{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001641 if (size < 0) {
1642 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001643 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001644 return NULL;
1645 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001646
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001647 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001648 some optimizations which share commonly used objects.
1649 Also, this means the input must be UTF-8, so fall back to the
1650 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001651 if (u != NULL) {
1652
Benjamin Peterson29060642009-01-31 22:14:21 +00001653 /* Optimization for empty strings */
1654 if (size == 0 && unicode_empty != NULL) {
1655 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001656 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001657 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001658
1659 /* Single characters are shared when using this constructor.
1660 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001661 if (size == 1 && (unsigned char)*u < 128)
1662 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001663
1664 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001665 }
1666
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001672{
1673 size_t size = strlen(u);
1674 if (size > PY_SSIZE_T_MAX) {
1675 PyErr_SetString(PyExc_OverflowError, "input too long");
1676 return NULL;
1677 }
1678
1679 return PyUnicode_FromStringAndSize(u, size);
1680}
1681
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001682PyObject *
1683_PyUnicode_FromId(_Py_Identifier *id)
1684{
1685 if (!id->object) {
1686 id->object = PyUnicode_FromString(id->string);
1687 if (!id->object)
1688 return NULL;
1689 PyUnicode_InternInPlace(&id->object);
1690 assert(!id->next);
1691 id->next = static_strings;
1692 static_strings = id;
1693 }
1694 Py_INCREF(id->object);
1695 return id->object;
1696}
1697
1698void
1699_PyUnicode_ClearStaticStrings()
1700{
1701 _Py_Identifier *i;
1702 for (i = static_strings; i; i = i->next) {
1703 Py_DECREF(i->object);
1704 i->object = NULL;
1705 i->next = NULL;
1706 }
1707}
1708
Victor Stinnere57b1c02011-09-28 22:20:48 +02001709static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001710unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001711{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001712 PyObject *res;
1713#ifdef Py_DEBUG
1714 const unsigned char *p;
1715 const unsigned char *end = s + size;
1716 for (p=s; p < end; p++) {
1717 assert(*p < 128);
1718 }
1719#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001720 if (size == 1)
1721 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001722 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001723 if (!res)
1724 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001725 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001726 return res;
1727}
1728
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001729static Py_UCS4
1730kind_maxchar_limit(unsigned int kind)
1731{
1732 switch(kind) {
1733 case PyUnicode_1BYTE_KIND:
1734 return 0x80;
1735 case PyUnicode_2BYTE_KIND:
1736 return 0x100;
1737 case PyUnicode_4BYTE_KIND:
1738 return 0x10000;
1739 default:
1740 assert(0 && "invalid kind");
1741 return 0x10ffff;
1742 }
1743}
1744
Victor Stinner702c7342011-10-05 13:50:52 +02001745static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001746_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001747{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001749 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001750
1751 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001752 if (size == 1)
1753 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001754 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001755 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001756 if (!res)
1757 return NULL;
1758 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001759 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001760 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001761}
1762
Victor Stinnere57b1c02011-09-28 22:20:48 +02001763static PyObject*
1764_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001765{
1766 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001767 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001768
1769 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001770 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001771 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001772 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001773 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001774 if (!res)
1775 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001776 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001777 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001778 else {
1779 _PyUnicode_CONVERT_BYTES(
1780 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1781 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001782 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 return res;
1784}
1785
Victor Stinnere57b1c02011-09-28 22:20:48 +02001786static PyObject*
1787_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788{
1789 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001790 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001791
1792 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001793 if (size == 1 && u[0] < 256)
1794 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001795 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001796 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797 if (!res)
1798 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001799 if (max_char < 256)
1800 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1801 PyUnicode_1BYTE_DATA(res));
1802 else if (max_char < 0x10000)
1803 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1804 PyUnicode_2BYTE_DATA(res));
1805 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001807 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 return res;
1809}
1810
1811PyObject*
1812PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1813{
1814 switch(kind) {
1815 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001816 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001817 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001818 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001820 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 default:
1822 assert(0 && "invalid kind");
1823 PyErr_SetString(PyExc_SystemError, "invalid kind");
1824 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001826}
1827
Victor Stinner25a4b292011-10-06 12:31:55 +02001828/* Ensure that a string uses the most efficient storage, if it is not the
1829 case: create a new string with of the right kind. Write NULL into *p_unicode
1830 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001831static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001832unicode_adjust_maxchar(PyObject **p_unicode)
1833{
1834 PyObject *unicode, *copy;
1835 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001836 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001837 unsigned int kind;
1838
1839 assert(p_unicode != NULL);
1840 unicode = *p_unicode;
1841 assert(PyUnicode_IS_READY(unicode));
1842 if (PyUnicode_IS_ASCII(unicode))
1843 return;
1844
1845 len = PyUnicode_GET_LENGTH(unicode);
1846 kind = PyUnicode_KIND(unicode);
1847 if (kind == PyUnicode_1BYTE_KIND) {
1848 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001849 max_char = ucs1lib_find_max_char(u, u + len);
1850 if (max_char >= 128)
1851 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001852 }
1853 else if (kind == PyUnicode_2BYTE_KIND) {
1854 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001855 max_char = ucs2lib_find_max_char(u, u + len);
1856 if (max_char >= 256)
1857 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001858 }
1859 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001860 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001861 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001862 max_char = ucs4lib_find_max_char(u, u + len);
1863 if (max_char >= 0x10000)
1864 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001865 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001866 copy = PyUnicode_New(len, max_char);
1867 copy_characters(copy, 0, unicode, 0, len);
1868 Py_DECREF(unicode);
1869 *p_unicode = copy;
1870}
1871
Victor Stinner034f6cf2011-09-30 02:26:44 +02001872PyObject*
1873PyUnicode_Copy(PyObject *unicode)
1874{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001875 Py_ssize_t size;
1876 PyObject *copy;
1877 void *data;
1878
Victor Stinner034f6cf2011-09-30 02:26:44 +02001879 if (!PyUnicode_Check(unicode)) {
1880 PyErr_BadInternalCall();
1881 return NULL;
1882 }
1883 if (PyUnicode_READY(unicode))
1884 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001885
1886 size = PyUnicode_GET_LENGTH(unicode);
1887 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1888 if (!copy)
1889 return NULL;
1890 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1891
1892 data = PyUnicode_DATA(unicode);
1893 switch (PyUnicode_KIND(unicode))
1894 {
1895 case PyUnicode_1BYTE_KIND:
1896 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1897 break;
1898 case PyUnicode_2BYTE_KIND:
1899 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1900 break;
1901 case PyUnicode_4BYTE_KIND:
1902 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1903 break;
1904 default:
1905 assert(0);
1906 break;
1907 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001908 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001909 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001910}
1911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001912
Victor Stinnerbc603d12011-10-02 01:00:40 +02001913/* Widen Unicode objects to larger buffers. Don't write terminating null
1914 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001915
1916void*
1917_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1918{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001919 Py_ssize_t len;
1920 void *result;
1921 unsigned int skind;
1922
1923 if (PyUnicode_READY(s))
1924 return NULL;
1925
1926 len = PyUnicode_GET_LENGTH(s);
1927 skind = PyUnicode_KIND(s);
1928 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001929 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001930 return NULL;
1931 }
1932 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001933 case PyUnicode_2BYTE_KIND:
1934 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1935 if (!result)
1936 return PyErr_NoMemory();
1937 assert(skind == PyUnicode_1BYTE_KIND);
1938 _PyUnicode_CONVERT_BYTES(
1939 Py_UCS1, Py_UCS2,
1940 PyUnicode_1BYTE_DATA(s),
1941 PyUnicode_1BYTE_DATA(s) + len,
1942 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001944 case PyUnicode_4BYTE_KIND:
1945 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1946 if (!result)
1947 return PyErr_NoMemory();
1948 if (skind == PyUnicode_2BYTE_KIND) {
1949 _PyUnicode_CONVERT_BYTES(
1950 Py_UCS2, Py_UCS4,
1951 PyUnicode_2BYTE_DATA(s),
1952 PyUnicode_2BYTE_DATA(s) + len,
1953 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001954 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001955 else {
1956 assert(skind == PyUnicode_1BYTE_KIND);
1957 _PyUnicode_CONVERT_BYTES(
1958 Py_UCS1, Py_UCS4,
1959 PyUnicode_1BYTE_DATA(s),
1960 PyUnicode_1BYTE_DATA(s) + len,
1961 result);
1962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001963 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001964 default:
1965 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001966 }
Victor Stinner01698042011-10-04 00:04:26 +02001967 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001968 return NULL;
1969}
1970
1971static Py_UCS4*
1972as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1973 int copy_null)
1974{
1975 int kind;
1976 void *data;
1977 Py_ssize_t len, targetlen;
1978 if (PyUnicode_READY(string) == -1)
1979 return NULL;
1980 kind = PyUnicode_KIND(string);
1981 data = PyUnicode_DATA(string);
1982 len = PyUnicode_GET_LENGTH(string);
1983 targetlen = len;
1984 if (copy_null)
1985 targetlen++;
1986 if (!target) {
1987 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1988 PyErr_NoMemory();
1989 return NULL;
1990 }
1991 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1992 if (!target) {
1993 PyErr_NoMemory();
1994 return NULL;
1995 }
1996 }
1997 else {
1998 if (targetsize < targetlen) {
1999 PyErr_Format(PyExc_SystemError,
2000 "string is longer than the buffer");
2001 if (copy_null && 0 < targetsize)
2002 target[0] = 0;
2003 return NULL;
2004 }
2005 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002006 if (kind == PyUnicode_1BYTE_KIND) {
2007 Py_UCS1 *start = (Py_UCS1 *) data;
2008 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002009 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002010 else if (kind == PyUnicode_2BYTE_KIND) {
2011 Py_UCS2 *start = (Py_UCS2 *) data;
2012 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2013 }
2014 else {
2015 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002016 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002017 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002018 if (copy_null)
2019 target[len] = 0;
2020 return target;
2021}
2022
2023Py_UCS4*
2024PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2025 int copy_null)
2026{
2027 if (target == NULL || targetsize < 1) {
2028 PyErr_BadInternalCall();
2029 return NULL;
2030 }
2031 return as_ucs4(string, target, targetsize, copy_null);
2032}
2033
2034Py_UCS4*
2035PyUnicode_AsUCS4Copy(PyObject *string)
2036{
2037 return as_ucs4(string, NULL, 0, 1);
2038}
2039
2040#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002041
Alexander Belopolsky40018472011-02-26 01:02:56 +00002042PyObject *
2043PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002044{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002045 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002046 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002048 PyErr_BadInternalCall();
2049 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002050 }
2051
Martin v. Löwis790465f2008-04-05 20:41:37 +00002052 if (size == -1) {
2053 size = wcslen(w);
2054 }
2055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002056 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002057}
2058
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002059#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002060
Walter Dörwald346737f2007-05-31 10:44:43 +00002061static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002062makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2063 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002064{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002065 *fmt++ = '%';
2066 if (width) {
2067 if (zeropad)
2068 *fmt++ = '0';
2069 fmt += sprintf(fmt, "%d", width);
2070 }
2071 if (precision)
2072 fmt += sprintf(fmt, ".%d", precision);
2073 if (longflag)
2074 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002075 else if (longlongflag) {
2076 /* longlongflag should only ever be nonzero on machines with
2077 HAVE_LONG_LONG defined */
2078#ifdef HAVE_LONG_LONG
2079 char *f = PY_FORMAT_LONG_LONG;
2080 while (*f)
2081 *fmt++ = *f++;
2082#else
2083 /* we shouldn't ever get here */
2084 assert(0);
2085 *fmt++ = 'l';
2086#endif
2087 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002088 else if (size_tflag) {
2089 char *f = PY_FORMAT_SIZE_T;
2090 while (*f)
2091 *fmt++ = *f++;
2092 }
2093 *fmt++ = c;
2094 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002095}
2096
Victor Stinner96865452011-03-01 23:44:09 +00002097/* helper for PyUnicode_FromFormatV() */
2098
2099static const char*
2100parse_format_flags(const char *f,
2101 int *p_width, int *p_precision,
2102 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2103{
2104 int width, precision, longflag, longlongflag, size_tflag;
2105
2106 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2107 f++;
2108 width = 0;
2109 while (Py_ISDIGIT((unsigned)*f))
2110 width = (width*10) + *f++ - '0';
2111 precision = 0;
2112 if (*f == '.') {
2113 f++;
2114 while (Py_ISDIGIT((unsigned)*f))
2115 precision = (precision*10) + *f++ - '0';
2116 if (*f == '%') {
2117 /* "%.3%s" => f points to "3" */
2118 f--;
2119 }
2120 }
2121 if (*f == '\0') {
2122 /* bogus format "%.1" => go backward, f points to "1" */
2123 f--;
2124 }
2125 if (p_width != NULL)
2126 *p_width = width;
2127 if (p_precision != NULL)
2128 *p_precision = precision;
2129
2130 /* Handle %ld, %lu, %lld and %llu. */
2131 longflag = 0;
2132 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002133 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002134
2135 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002136 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002137 longflag = 1;
2138 ++f;
2139 }
2140#ifdef HAVE_LONG_LONG
2141 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002142 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002143 longlongflag = 1;
2144 f += 2;
2145 }
2146#endif
2147 }
2148 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002149 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002150 size_tflag = 1;
2151 ++f;
2152 }
2153 if (p_longflag != NULL)
2154 *p_longflag = longflag;
2155 if (p_longlongflag != NULL)
2156 *p_longlongflag = longlongflag;
2157 if (p_size_tflag != NULL)
2158 *p_size_tflag = size_tflag;
2159 return f;
2160}
2161
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002162/* maximum number of characters required for output of %ld. 21 characters
2163 allows for 64-bit integers (in decimal) and an optional sign. */
2164#define MAX_LONG_CHARS 21
2165/* maximum number of characters required for output of %lld.
2166 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2167 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2168#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2169
Walter Dörwaldd2034312007-05-18 16:29:38 +00002170PyObject *
2171PyUnicode_FromFormatV(const char *format, va_list vargs)
2172{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002173 va_list count;
2174 Py_ssize_t callcount = 0;
2175 PyObject **callresults = NULL;
2176 PyObject **callresult = NULL;
2177 Py_ssize_t n = 0;
2178 int width = 0;
2179 int precision = 0;
2180 int zeropad;
2181 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002182 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002183 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002184 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002185 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2186 Py_UCS4 argmaxchar;
2187 Py_ssize_t numbersize = 0;
2188 char *numberresults = NULL;
2189 char *numberresult = NULL;
2190 Py_ssize_t i;
2191 int kind;
2192 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002193
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002194 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002195 /* step 1: count the number of %S/%R/%A/%s format specifications
2196 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2197 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002198 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002199 * also estimate a upper bound for all the number formats in the string,
2200 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002201 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002202 for (f = format; *f; f++) {
2203 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002204 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002205 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2206 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2207 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2208 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002210 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002211#ifdef HAVE_LONG_LONG
2212 if (longlongflag) {
2213 if (width < MAX_LONG_LONG_CHARS)
2214 width = MAX_LONG_LONG_CHARS;
2215 }
2216 else
2217#endif
2218 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2219 including sign. Decimal takes the most space. This
2220 isn't enough for octal. If a width is specified we
2221 need more (which we allocate later). */
2222 if (width < MAX_LONG_CHARS)
2223 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002224
2225 /* account for the size + '\0' to separate numbers
2226 inside of the numberresults buffer */
2227 numbersize += (width + 1);
2228 }
2229 }
2230 else if ((unsigned char)*f > 127) {
2231 PyErr_Format(PyExc_ValueError,
2232 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2233 "string, got a non-ASCII byte: 0x%02x",
2234 (unsigned char)*f);
2235 return NULL;
2236 }
2237 }
2238 /* step 2: allocate memory for the results of
2239 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2240 if (callcount) {
2241 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2242 if (!callresults) {
2243 PyErr_NoMemory();
2244 return NULL;
2245 }
2246 callresult = callresults;
2247 }
2248 /* step 2.5: allocate memory for the results of formating numbers */
2249 if (numbersize) {
2250 numberresults = PyObject_Malloc(numbersize);
2251 if (!numberresults) {
2252 PyErr_NoMemory();
2253 goto fail;
2254 }
2255 numberresult = numberresults;
2256 }
2257
2258 /* step 3: format numbers and figure out how large a buffer we need */
2259 for (f = format; *f; f++) {
2260 if (*f == '%') {
2261 const char* p;
2262 int longflag;
2263 int longlongflag;
2264 int size_tflag;
2265 int numprinted;
2266
2267 p = f;
2268 zeropad = (f[1] == '0');
2269 f = parse_format_flags(f, &width, &precision,
2270 &longflag, &longlongflag, &size_tflag);
2271 switch (*f) {
2272 case 'c':
2273 {
2274 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002275 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002276 n++;
2277 break;
2278 }
2279 case '%':
2280 n++;
2281 break;
2282 case 'i':
2283 case 'd':
2284 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2285 width, precision, *f);
2286 if (longflag)
2287 numprinted = sprintf(numberresult, fmt,
2288 va_arg(count, long));
2289#ifdef HAVE_LONG_LONG
2290 else if (longlongflag)
2291 numprinted = sprintf(numberresult, fmt,
2292 va_arg(count, PY_LONG_LONG));
2293#endif
2294 else if (size_tflag)
2295 numprinted = sprintf(numberresult, fmt,
2296 va_arg(count, Py_ssize_t));
2297 else
2298 numprinted = sprintf(numberresult, fmt,
2299 va_arg(count, int));
2300 n += numprinted;
2301 /* advance by +1 to skip over the '\0' */
2302 numberresult += (numprinted + 1);
2303 assert(*(numberresult - 1) == '\0');
2304 assert(*(numberresult - 2) != '\0');
2305 assert(numprinted >= 0);
2306 assert(numberresult <= numberresults + numbersize);
2307 break;
2308 case 'u':
2309 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2310 width, precision, 'u');
2311 if (longflag)
2312 numprinted = sprintf(numberresult, fmt,
2313 va_arg(count, unsigned long));
2314#ifdef HAVE_LONG_LONG
2315 else if (longlongflag)
2316 numprinted = sprintf(numberresult, fmt,
2317 va_arg(count, unsigned PY_LONG_LONG));
2318#endif
2319 else if (size_tflag)
2320 numprinted = sprintf(numberresult, fmt,
2321 va_arg(count, size_t));
2322 else
2323 numprinted = sprintf(numberresult, fmt,
2324 va_arg(count, unsigned int));
2325 n += numprinted;
2326 numberresult += (numprinted + 1);
2327 assert(*(numberresult - 1) == '\0');
2328 assert(*(numberresult - 2) != '\0');
2329 assert(numprinted >= 0);
2330 assert(numberresult <= numberresults + numbersize);
2331 break;
2332 case 'x':
2333 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2334 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2335 n += numprinted;
2336 numberresult += (numprinted + 1);
2337 assert(*(numberresult - 1) == '\0');
2338 assert(*(numberresult - 2) != '\0');
2339 assert(numprinted >= 0);
2340 assert(numberresult <= numberresults + numbersize);
2341 break;
2342 case 'p':
2343 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2344 /* %p is ill-defined: ensure leading 0x. */
2345 if (numberresult[1] == 'X')
2346 numberresult[1] = 'x';
2347 else if (numberresult[1] != 'x') {
2348 memmove(numberresult + 2, numberresult,
2349 strlen(numberresult) + 1);
2350 numberresult[0] = '0';
2351 numberresult[1] = 'x';
2352 numprinted += 2;
2353 }
2354 n += numprinted;
2355 numberresult += (numprinted + 1);
2356 assert(*(numberresult - 1) == '\0');
2357 assert(*(numberresult - 2) != '\0');
2358 assert(numprinted >= 0);
2359 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002360 break;
2361 case 's':
2362 {
2363 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002364 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002365 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2366 if (!str)
2367 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002368 /* since PyUnicode_DecodeUTF8 returns already flexible
2369 unicode objects, there is no need to call ready on them */
2370 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002371 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002372 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002373 /* Remember the str and switch to the next slot */
2374 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002375 break;
2376 }
2377 case 'U':
2378 {
2379 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002380 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002381 if (PyUnicode_READY(obj) == -1)
2382 goto fail;
2383 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002384 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002385 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002386 break;
2387 }
2388 case 'V':
2389 {
2390 PyObject *obj = va_arg(count, PyObject *);
2391 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002392 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002393 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002394 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002395 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002396 if (PyUnicode_READY(obj) == -1)
2397 goto fail;
2398 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002399 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002400 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002401 *callresult++ = NULL;
2402 }
2403 else {
2404 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2405 if (!str_obj)
2406 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002407 if (PyUnicode_READY(str_obj)) {
2408 Py_DECREF(str_obj);
2409 goto fail;
2410 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002411 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002412 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002414 *callresult++ = str_obj;
2415 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002416 break;
2417 }
2418 case 'S':
2419 {
2420 PyObject *obj = va_arg(count, PyObject *);
2421 PyObject *str;
2422 assert(obj);
2423 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002424 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002425 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002426 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002427 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002429 /* Remember the str and switch to the next slot */
2430 *callresult++ = str;
2431 break;
2432 }
2433 case 'R':
2434 {
2435 PyObject *obj = va_arg(count, PyObject *);
2436 PyObject *repr;
2437 assert(obj);
2438 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002439 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002440 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002441 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002442 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002443 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002444 /* Remember the repr and switch to the next slot */
2445 *callresult++ = repr;
2446 break;
2447 }
2448 case 'A':
2449 {
2450 PyObject *obj = va_arg(count, PyObject *);
2451 PyObject *ascii;
2452 assert(obj);
2453 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002454 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002455 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002457 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002458 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002459 /* Remember the repr and switch to the next slot */
2460 *callresult++ = ascii;
2461 break;
2462 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002463 default:
2464 /* if we stumble upon an unknown
2465 formatting code, copy the rest of
2466 the format string to the output
2467 string. (we cannot just skip the
2468 code, since there's no way to know
2469 what's in the argument list) */
2470 n += strlen(p);
2471 goto expand;
2472 }
2473 } else
2474 n++;
2475 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002476 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002477 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 we don't have to resize the string.
2480 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002481 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002482 if (!string)
2483 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002484 kind = PyUnicode_KIND(string);
2485 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002488
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002491 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002492
2493 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002494 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2495 /* checking for == because the last argument could be a empty
2496 string, which causes i to point to end, the assert at the end of
2497 the loop */
2498 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002499
Benjamin Peterson14339b62009-01-31 16:36:08 +00002500 switch (*f) {
2501 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002502 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 const int ordinal = va_arg(vargs, int);
2504 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002505 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002506 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002507 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002511 case 'p':
2512 /* unused, since we already have the result */
2513 if (*f == 'p')
2514 (void) va_arg(vargs, void *);
2515 else
2516 (void) va_arg(vargs, int);
2517 /* extract the result from numberresults and append. */
2518 for (; *numberresult; ++i, ++numberresult)
2519 PyUnicode_WRITE(kind, data, i, *numberresult);
2520 /* skip over the separating '\0' */
2521 assert(*numberresult == '\0');
2522 numberresult++;
2523 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002524 break;
2525 case 's':
2526 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002527 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002528 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002529 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002530 size = PyUnicode_GET_LENGTH(*callresult);
2531 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002532 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002533 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002534 /* We're done with the unicode()/repr() => forget it */
2535 Py_DECREF(*callresult);
2536 /* switch to next unicode()/repr() result */
2537 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002538 break;
2539 }
2540 case 'U':
2541 {
2542 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002543 Py_ssize_t size;
2544 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2545 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002546 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002547 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002548 break;
2549 }
2550 case 'V':
2551 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002552 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002553 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002554 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002556 size = PyUnicode_GET_LENGTH(obj);
2557 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002558 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002560 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 size = PyUnicode_GET_LENGTH(*callresult);
2562 assert(PyUnicode_KIND(*callresult) <=
2563 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002564 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002565 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002566 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002567 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002568 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
2570 }
2571 case 'S':
2572 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002573 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002574 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002575 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002576 /* unused, since we already have the result */
2577 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002579 copy_characters(string, i, *callresult, 0, size);
2580 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002581 /* We're done with the unicode()/repr() => forget it */
2582 Py_DECREF(*callresult);
2583 /* switch to next unicode()/repr() result */
2584 ++callresult;
2585 break;
2586 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002587 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002588 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002589 break;
2590 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 for (; *p; ++p, ++i)
2592 PyUnicode_WRITE(kind, data, i, *p);
2593 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002594 goto end;
2595 }
Victor Stinner1205f272010-09-11 00:54:47 +00002596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 else {
2598 assert(i < PyUnicode_GET_LENGTH(string));
2599 PyUnicode_WRITE(kind, data, i++, *f);
2600 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002601 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002602 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002603
Benjamin Peterson29060642009-01-31 22:14:21 +00002604 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 if (callresults)
2606 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002607 if (numberresults)
2608 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002609 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002611 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 if (callresults) {
2613 PyObject **callresult2 = callresults;
2614 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002615 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002616 ++callresult2;
2617 }
2618 PyObject_Free(callresults);
2619 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 if (numberresults)
2621 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002623}
2624
Walter Dörwaldd2034312007-05-18 16:29:38 +00002625PyObject *
2626PyUnicode_FromFormat(const char *format, ...)
2627{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002628 PyObject* ret;
2629 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002630
2631#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002633#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002634 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002635#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 ret = PyUnicode_FromFormatV(format, vargs);
2637 va_end(vargs);
2638 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002639}
2640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002641#ifdef HAVE_WCHAR_H
2642
Victor Stinner5593d8a2010-10-02 11:11:27 +00002643/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2644 convert a Unicode object to a wide character string.
2645
Victor Stinnerd88d9832011-09-06 02:00:05 +02002646 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002647 character) required to convert the unicode object. Ignore size argument.
2648
Victor Stinnerd88d9832011-09-06 02:00:05 +02002649 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002650 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002651 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002652static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002653unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002654 wchar_t *w,
2655 Py_ssize_t size)
2656{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002657 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002658 const wchar_t *wstr;
2659
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002660 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 if (wstr == NULL)
2662 return -1;
2663
Victor Stinner5593d8a2010-10-02 11:11:27 +00002664 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002665 if (size > res)
2666 size = res + 1;
2667 else
2668 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002669 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002670 return res;
2671 }
2672 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002674}
2675
2676Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002677PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002678 wchar_t *w,
2679 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002680{
2681 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002682 PyErr_BadInternalCall();
2683 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002684 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002685 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002686}
2687
Victor Stinner137c34c2010-09-29 10:25:54 +00002688wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002689PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002690 Py_ssize_t *size)
2691{
2692 wchar_t* buffer;
2693 Py_ssize_t buflen;
2694
2695 if (unicode == NULL) {
2696 PyErr_BadInternalCall();
2697 return NULL;
2698 }
2699
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002700 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 if (buflen == -1)
2702 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002703 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002704 PyErr_NoMemory();
2705 return NULL;
2706 }
2707
Victor Stinner137c34c2010-09-29 10:25:54 +00002708 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2709 if (buffer == NULL) {
2710 PyErr_NoMemory();
2711 return NULL;
2712 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002713 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002714 if (buflen == -1)
2715 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002716 if (size != NULL)
2717 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002718 return buffer;
2719}
2720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002721#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002722
Alexander Belopolsky40018472011-02-26 01:02:56 +00002723PyObject *
2724PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002725{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002726 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002727 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002728 PyErr_SetString(PyExc_ValueError,
2729 "chr() arg not in range(0x110000)");
2730 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002731 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002733 if (ordinal < 256)
2734 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 v = PyUnicode_New(1, ordinal);
2737 if (v == NULL)
2738 return NULL;
2739 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002740 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002741 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002742}
2743
Alexander Belopolsky40018472011-02-26 01:02:56 +00002744PyObject *
2745PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002746{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002747 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002748 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002749 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002750 if (PyUnicode_READY(obj))
2751 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002752 Py_INCREF(obj);
2753 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002754 }
2755 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002756 /* For a Unicode subtype that's not a Unicode object,
2757 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002758 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002759 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002760 PyErr_Format(PyExc_TypeError,
2761 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002762 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002763 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002764}
2765
Alexander Belopolsky40018472011-02-26 01:02:56 +00002766PyObject *
2767PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002768 const char *encoding,
2769 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002770{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002771 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002772 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002773
Guido van Rossumd57fd912000-03-10 22:53:23 +00002774 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002775 PyErr_BadInternalCall();
2776 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002778
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002779 /* Decoding bytes objects is the most common case and should be fast */
2780 if (PyBytes_Check(obj)) {
2781 if (PyBytes_GET_SIZE(obj) == 0) {
2782 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002783 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002784 }
2785 else {
2786 v = PyUnicode_Decode(
2787 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2788 encoding, errors);
2789 }
2790 return v;
2791 }
2792
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002793 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002794 PyErr_SetString(PyExc_TypeError,
2795 "decoding str is not supported");
2796 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002797 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002798
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002799 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2800 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2801 PyErr_Format(PyExc_TypeError,
2802 "coercing to str: need bytes, bytearray "
2803 "or buffer-like object, %.80s found",
2804 Py_TYPE(obj)->tp_name);
2805 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002806 }
Tim Petersced69f82003-09-16 20:30:58 +00002807
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002808 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002809 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002810 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002811 }
Tim Petersced69f82003-09-16 20:30:58 +00002812 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002813 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002814
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002816 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002817}
2818
Victor Stinner600d3be2010-06-10 12:00:55 +00002819/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002820 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2821 1 on success. */
2822static int
2823normalize_encoding(const char *encoding,
2824 char *lower,
2825 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002826{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002827 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002828 char *l;
2829 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002830
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002831 if (encoding == NULL) {
2832 strcpy(lower, "utf-8");
2833 return 1;
2834 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002835 e = encoding;
2836 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002837 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002838 while (*e) {
2839 if (l == l_end)
2840 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002841 if (Py_ISUPPER(*e)) {
2842 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002843 }
2844 else if (*e == '_') {
2845 *l++ = '-';
2846 e++;
2847 }
2848 else {
2849 *l++ = *e++;
2850 }
2851 }
2852 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002853 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002854}
2855
Alexander Belopolsky40018472011-02-26 01:02:56 +00002856PyObject *
2857PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002858 Py_ssize_t size,
2859 const char *encoding,
2860 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002861{
2862 PyObject *buffer = NULL, *unicode;
2863 Py_buffer info;
2864 char lower[11]; /* Enough for any encoding shortcut */
2865
Fred Drakee4315f52000-05-09 19:53:39 +00002866 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002867 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002868 if ((strcmp(lower, "utf-8") == 0) ||
2869 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002870 return PyUnicode_DecodeUTF8(s, size, errors);
2871 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002872 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002873 (strcmp(lower, "iso-8859-1") == 0))
2874 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002875#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002876 else if (strcmp(lower, "mbcs") == 0)
2877 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002878#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002879 else if (strcmp(lower, "ascii") == 0)
2880 return PyUnicode_DecodeASCII(s, size, errors);
2881 else if (strcmp(lower, "utf-16") == 0)
2882 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2883 else if (strcmp(lower, "utf-32") == 0)
2884 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2885 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002886
2887 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002888 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002889 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002890 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002891 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002892 if (buffer == NULL)
2893 goto onError;
2894 unicode = PyCodec_Decode(buffer, encoding, errors);
2895 if (unicode == NULL)
2896 goto onError;
2897 if (!PyUnicode_Check(unicode)) {
2898 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002899 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002900 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002901 Py_DECREF(unicode);
2902 goto onError;
2903 }
2904 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002905#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002906 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002907 Py_DECREF(unicode);
2908 return NULL;
2909 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002910#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002911 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002912 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002913
Benjamin Peterson29060642009-01-31 22:14:21 +00002914 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002915 Py_XDECREF(buffer);
2916 return NULL;
2917}
2918
Alexander Belopolsky40018472011-02-26 01:02:56 +00002919PyObject *
2920PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002921 const char *encoding,
2922 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002923{
2924 PyObject *v;
2925
2926 if (!PyUnicode_Check(unicode)) {
2927 PyErr_BadArgument();
2928 goto onError;
2929 }
2930
2931 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002932 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002933
2934 /* Decode via the codec registry */
2935 v = PyCodec_Decode(unicode, encoding, errors);
2936 if (v == NULL)
2937 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002938 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002939 return v;
2940
Benjamin Peterson29060642009-01-31 22:14:21 +00002941 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002942 return NULL;
2943}
2944
Alexander Belopolsky40018472011-02-26 01:02:56 +00002945PyObject *
2946PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002947 const char *encoding,
2948 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002949{
2950 PyObject *v;
2951
2952 if (!PyUnicode_Check(unicode)) {
2953 PyErr_BadArgument();
2954 goto onError;
2955 }
2956
2957 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002958 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002959
2960 /* Decode via the codec registry */
2961 v = PyCodec_Decode(unicode, encoding, errors);
2962 if (v == NULL)
2963 goto onError;
2964 if (!PyUnicode_Check(v)) {
2965 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002966 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002967 Py_TYPE(v)->tp_name);
2968 Py_DECREF(v);
2969 goto onError;
2970 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002971 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002972 return v;
2973
Benjamin Peterson29060642009-01-31 22:14:21 +00002974 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002975 return NULL;
2976}
2977
Alexander Belopolsky40018472011-02-26 01:02:56 +00002978PyObject *
2979PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002980 Py_ssize_t size,
2981 const char *encoding,
2982 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002983{
2984 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002985
Guido van Rossumd57fd912000-03-10 22:53:23 +00002986 unicode = PyUnicode_FromUnicode(s, size);
2987 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002988 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002989 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2990 Py_DECREF(unicode);
2991 return v;
2992}
2993
Alexander Belopolsky40018472011-02-26 01:02:56 +00002994PyObject *
2995PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002996 const char *encoding,
2997 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002998{
2999 PyObject *v;
3000
3001 if (!PyUnicode_Check(unicode)) {
3002 PyErr_BadArgument();
3003 goto onError;
3004 }
3005
3006 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003007 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003008
3009 /* Encode via the codec registry */
3010 v = PyCodec_Encode(unicode, encoding, errors);
3011 if (v == NULL)
3012 goto onError;
3013 return v;
3014
Benjamin Peterson29060642009-01-31 22:14:21 +00003015 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003016 return NULL;
3017}
3018
Victor Stinnerad158722010-10-27 00:25:46 +00003019PyObject *
3020PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003021{
Victor Stinner99b95382011-07-04 14:23:54 +02003022#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003023 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3024 PyUnicode_GET_SIZE(unicode),
3025 NULL);
3026#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003027 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003028#else
Victor Stinner793b5312011-04-27 00:24:21 +02003029 PyInterpreterState *interp = PyThreadState_GET()->interp;
3030 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3031 cannot use it to encode and decode filenames before it is loaded. Load
3032 the Python codec requires to encode at least its own filename. Use the C
3033 version of the locale codec until the codec registry is initialized and
3034 the Python codec is loaded.
3035
3036 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3037 cannot only rely on it: check also interp->fscodec_initialized for
3038 subinterpreters. */
3039 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003040 return PyUnicode_AsEncodedString(unicode,
3041 Py_FileSystemDefaultEncoding,
3042 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003043 }
3044 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003045 /* locale encoding with surrogateescape */
3046 wchar_t *wchar;
3047 char *bytes;
3048 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003049 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003050
3051 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3052 if (wchar == NULL)
3053 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003054 bytes = _Py_wchar2char(wchar, &error_pos);
3055 if (bytes == NULL) {
3056 if (error_pos != (size_t)-1) {
3057 char *errmsg = strerror(errno);
3058 PyObject *exc = NULL;
3059 if (errmsg == NULL)
3060 errmsg = "Py_wchar2char() failed";
3061 raise_encode_exception(&exc,
3062 "filesystemencoding",
3063 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3064 error_pos, error_pos+1,
3065 errmsg);
3066 Py_XDECREF(exc);
3067 }
3068 else
3069 PyErr_NoMemory();
3070 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003071 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003072 }
3073 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003074
3075 bytes_obj = PyBytes_FromString(bytes);
3076 PyMem_Free(bytes);
3077 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003078 }
Victor Stinnerad158722010-10-27 00:25:46 +00003079#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003080}
3081
Alexander Belopolsky40018472011-02-26 01:02:56 +00003082PyObject *
3083PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003084 const char *encoding,
3085 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003086{
3087 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003088 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003089
Guido van Rossumd57fd912000-03-10 22:53:23 +00003090 if (!PyUnicode_Check(unicode)) {
3091 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003092 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003093 }
Fred Drakee4315f52000-05-09 19:53:39 +00003094
Fred Drakee4315f52000-05-09 19:53:39 +00003095 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003096 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003097 if ((strcmp(lower, "utf-8") == 0) ||
3098 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003099 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003100 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003101 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003102 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003103 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003104 }
Victor Stinner37296e82010-06-10 13:36:23 +00003105 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003106 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003107 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003108 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003109#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003110 else if (strcmp(lower, "mbcs") == 0)
3111 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3112 PyUnicode_GET_SIZE(unicode),
3113 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003114#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003115 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003116 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003117 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118
3119 /* Encode via the codec registry */
3120 v = PyCodec_Encode(unicode, encoding, errors);
3121 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 return NULL;
3123
3124 /* The normal path */
3125 if (PyBytes_Check(v))
3126 return v;
3127
3128 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003129 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003130 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003131 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003132
3133 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3134 "encoder %s returned bytearray instead of bytes",
3135 encoding);
3136 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003137 Py_DECREF(v);
3138 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003139 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003140
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003141 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3142 Py_DECREF(v);
3143 return b;
3144 }
3145
3146 PyErr_Format(PyExc_TypeError,
3147 "encoder did not return a bytes object (type=%.400s)",
3148 Py_TYPE(v)->tp_name);
3149 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003150 return NULL;
3151}
3152
Alexander Belopolsky40018472011-02-26 01:02:56 +00003153PyObject *
3154PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003155 const char *encoding,
3156 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003157{
3158 PyObject *v;
3159
3160 if (!PyUnicode_Check(unicode)) {
3161 PyErr_BadArgument();
3162 goto onError;
3163 }
3164
3165 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003166 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003167
3168 /* Encode via the codec registry */
3169 v = PyCodec_Encode(unicode, encoding, errors);
3170 if (v == NULL)
3171 goto onError;
3172 if (!PyUnicode_Check(v)) {
3173 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003174 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003175 Py_TYPE(v)->tp_name);
3176 Py_DECREF(v);
3177 goto onError;
3178 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003179 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003180
Benjamin Peterson29060642009-01-31 22:14:21 +00003181 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003182 return NULL;
3183}
3184
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003185PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003186PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003187 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003188 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3189}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003190
Christian Heimes5894ba72007-11-04 11:43:14 +00003191PyObject*
3192PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3193{
Victor Stinner99b95382011-07-04 14:23:54 +02003194#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003195 return PyUnicode_DecodeMBCS(s, size, NULL);
3196#elif defined(__APPLE__)
3197 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3198#else
Victor Stinner793b5312011-04-27 00:24:21 +02003199 PyInterpreterState *interp = PyThreadState_GET()->interp;
3200 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3201 cannot use it to encode and decode filenames before it is loaded. Load
3202 the Python codec requires to encode at least its own filename. Use the C
3203 version of the locale codec until the codec registry is initialized and
3204 the Python codec is loaded.
3205
3206 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3207 cannot only rely on it: check also interp->fscodec_initialized for
3208 subinterpreters. */
3209 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003210 return PyUnicode_Decode(s, size,
3211 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003212 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003213 }
3214 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003215 /* locale encoding with surrogateescape */
3216 wchar_t *wchar;
3217 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003218 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003219
3220 if (s[size] != '\0' || size != strlen(s)) {
3221 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3222 return NULL;
3223 }
3224
Victor Stinner168e1172010-10-16 23:16:16 +00003225 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003226 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003227 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003228
Victor Stinner168e1172010-10-16 23:16:16 +00003229 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003230 PyMem_Free(wchar);
3231 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003232 }
Victor Stinnerad158722010-10-27 00:25:46 +00003233#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003234}
3235
Martin v. Löwis011e8422009-05-05 04:43:17 +00003236
3237int
3238PyUnicode_FSConverter(PyObject* arg, void* addr)
3239{
3240 PyObject *output = NULL;
3241 Py_ssize_t size;
3242 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003243 if (arg == NULL) {
3244 Py_DECREF(*(PyObject**)addr);
3245 return 1;
3246 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003247 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003248 output = arg;
3249 Py_INCREF(output);
3250 }
3251 else {
3252 arg = PyUnicode_FromObject(arg);
3253 if (!arg)
3254 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003255 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003256 Py_DECREF(arg);
3257 if (!output)
3258 return 0;
3259 if (!PyBytes_Check(output)) {
3260 Py_DECREF(output);
3261 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3262 return 0;
3263 }
3264 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003265 size = PyBytes_GET_SIZE(output);
3266 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003267 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003268 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003269 Py_DECREF(output);
3270 return 0;
3271 }
3272 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003273 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003274}
3275
3276
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003277int
3278PyUnicode_FSDecoder(PyObject* arg, void* addr)
3279{
3280 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003281 if (arg == NULL) {
3282 Py_DECREF(*(PyObject**)addr);
3283 return 1;
3284 }
3285 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003286 if (PyUnicode_READY(arg))
3287 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003288 output = arg;
3289 Py_INCREF(output);
3290 }
3291 else {
3292 arg = PyBytes_FromObject(arg);
3293 if (!arg)
3294 return 0;
3295 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3296 PyBytes_GET_SIZE(arg));
3297 Py_DECREF(arg);
3298 if (!output)
3299 return 0;
3300 if (!PyUnicode_Check(output)) {
3301 Py_DECREF(output);
3302 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3303 return 0;
3304 }
3305 }
Victor Stinner065836e2011-10-27 01:56:33 +02003306 if (PyUnicode_READY(output) < 0) {
3307 Py_DECREF(output);
3308 return 0;
3309 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003310 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003311 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003312 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3313 Py_DECREF(output);
3314 return 0;
3315 }
3316 *(PyObject**)addr = output;
3317 return Py_CLEANUP_SUPPORTED;
3318}
3319
3320
Martin v. Löwis5b222132007-06-10 09:51:05 +00003321char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003322PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003323{
Christian Heimesf3863112007-11-22 07:46:41 +00003324 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003325
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003326 if (!PyUnicode_Check(unicode)) {
3327 PyErr_BadArgument();
3328 return NULL;
3329 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003330 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003331 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003332
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003333 if (PyUnicode_UTF8(unicode) == NULL) {
3334 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003335 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3336 if (bytes == NULL)
3337 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003338 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3339 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003340 Py_DECREF(bytes);
3341 return NULL;
3342 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003343 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3344 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3345 PyBytes_AS_STRING(bytes),
3346 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003347 Py_DECREF(bytes);
3348 }
3349
3350 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003351 *psize = PyUnicode_UTF8_LENGTH(unicode);
3352 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003353}
3354
3355char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003357{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003358 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3359}
3360
3361#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003362static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003363#endif
3364
3365
3366Py_UNICODE *
3367PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3368{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003369 const unsigned char *one_byte;
3370#if SIZEOF_WCHAR_T == 4
3371 const Py_UCS2 *two_bytes;
3372#else
3373 const Py_UCS4 *four_bytes;
3374 const Py_UCS4 *ucs4_end;
3375 Py_ssize_t num_surrogates;
3376#endif
3377 wchar_t *w;
3378 wchar_t *wchar_end;
3379
3380 if (!PyUnicode_Check(unicode)) {
3381 PyErr_BadArgument();
3382 return NULL;
3383 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003384 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003385 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003386 assert(_PyUnicode_KIND(unicode) != 0);
3387 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388
3389#ifdef Py_DEBUG
3390 ++unicode_as_unicode_calls;
3391#endif
3392
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003393 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003395 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3396 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003397 num_surrogates = 0;
3398
3399 for (; four_bytes < ucs4_end; ++four_bytes) {
3400 if (*four_bytes > 0xFFFF)
3401 ++num_surrogates;
3402 }
3403
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003404 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3405 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3406 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003407 PyErr_NoMemory();
3408 return NULL;
3409 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003410 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003411
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003412 w = _PyUnicode_WSTR(unicode);
3413 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3414 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003415 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3416 if (*four_bytes > 0xFFFF) {
3417 /* encode surrogate pair in this case */
3418 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3419 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3420 }
3421 else
3422 *w = *four_bytes;
3423
3424 if (w > wchar_end) {
3425 assert(0 && "Miscalculated string end");
3426 }
3427 }
3428 *w = 0;
3429#else
3430 /* sizeof(wchar_t) == 4 */
3431 Py_FatalError("Impossible unicode object state, wstr and str "
3432 "should share memory already.");
3433 return NULL;
3434#endif
3435 }
3436 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003437 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3438 (_PyUnicode_LENGTH(unicode) + 1));
3439 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003440 PyErr_NoMemory();
3441 return NULL;
3442 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003443 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3444 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3445 w = _PyUnicode_WSTR(unicode);
3446 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003447
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003448 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3449 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003450 for (; w < wchar_end; ++one_byte, ++w)
3451 *w = *one_byte;
3452 /* null-terminate the wstr */
3453 *w = 0;
3454 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003455 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003456#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003457 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003458 for (; w < wchar_end; ++two_bytes, ++w)
3459 *w = *two_bytes;
3460 /* null-terminate the wstr */
3461 *w = 0;
3462#else
3463 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003464 PyObject_FREE(_PyUnicode_WSTR(unicode));
3465 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003466 Py_FatalError("Impossible unicode object state, wstr "
3467 "and str should share memory already.");
3468 return NULL;
3469#endif
3470 }
3471 else {
3472 assert(0 && "This should never happen.");
3473 }
3474 }
3475 }
3476 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003477 *size = PyUnicode_WSTR_LENGTH(unicode);
3478 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003479}
3480
Alexander Belopolsky40018472011-02-26 01:02:56 +00003481Py_UNICODE *
3482PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003484 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003485}
3486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003487
Alexander Belopolsky40018472011-02-26 01:02:56 +00003488Py_ssize_t
3489PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003490{
3491 if (!PyUnicode_Check(unicode)) {
3492 PyErr_BadArgument();
3493 goto onError;
3494 }
3495 return PyUnicode_GET_SIZE(unicode);
3496
Benjamin Peterson29060642009-01-31 22:14:21 +00003497 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003498 return -1;
3499}
3500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003501Py_ssize_t
3502PyUnicode_GetLength(PyObject *unicode)
3503{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003504 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003505 PyErr_BadArgument();
3506 return -1;
3507 }
3508
3509 return PyUnicode_GET_LENGTH(unicode);
3510}
3511
3512Py_UCS4
3513PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3514{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003515 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3516 PyErr_BadArgument();
3517 return (Py_UCS4)-1;
3518 }
3519 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3520 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003521 return (Py_UCS4)-1;
3522 }
3523 return PyUnicode_READ_CHAR(unicode, index);
3524}
3525
3526int
3527PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3528{
3529 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003530 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531 return -1;
3532 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003533 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3534 PyErr_SetString(PyExc_IndexError, "string index out of range");
3535 return -1;
3536 }
3537 if (_PyUnicode_Dirty(unicode))
3538 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003539 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3540 index, ch);
3541 return 0;
3542}
3543
Alexander Belopolsky40018472011-02-26 01:02:56 +00003544const char *
3545PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003546{
Victor Stinner42cb4622010-09-01 19:39:01 +00003547 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003548}
3549
Victor Stinner554f3f02010-06-16 23:33:54 +00003550/* create or adjust a UnicodeDecodeError */
3551static void
3552make_decode_exception(PyObject **exceptionObject,
3553 const char *encoding,
3554 const char *input, Py_ssize_t length,
3555 Py_ssize_t startpos, Py_ssize_t endpos,
3556 const char *reason)
3557{
3558 if (*exceptionObject == NULL) {
3559 *exceptionObject = PyUnicodeDecodeError_Create(
3560 encoding, input, length, startpos, endpos, reason);
3561 }
3562 else {
3563 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3564 goto onError;
3565 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3566 goto onError;
3567 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3568 goto onError;
3569 }
3570 return;
3571
3572onError:
3573 Py_DECREF(*exceptionObject);
3574 *exceptionObject = NULL;
3575}
3576
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003577/* error handling callback helper:
3578 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003579 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003580 and adjust various state variables.
3581 return 0 on success, -1 on error
3582*/
3583
Alexander Belopolsky40018472011-02-26 01:02:56 +00003584static int
3585unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003586 const char *encoding, const char *reason,
3587 const char **input, const char **inend, Py_ssize_t *startinpos,
3588 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3589 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003590{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003591 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003592
3593 PyObject *restuple = NULL;
3594 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003595 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003596 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003597 Py_ssize_t requiredsize;
3598 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003599 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003600 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003601 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003602 int res = -1;
3603
3604 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003605 *errorHandler = PyCodec_LookupError(errors);
3606 if (*errorHandler == NULL)
3607 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003608 }
3609
Victor Stinner554f3f02010-06-16 23:33:54 +00003610 make_decode_exception(exceptionObject,
3611 encoding,
3612 *input, *inend - *input,
3613 *startinpos, *endinpos,
3614 reason);
3615 if (*exceptionObject == NULL)
3616 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003617
3618 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3619 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003620 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003621 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003622 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003623 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003624 }
3625 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003626 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003627
3628 /* Copy back the bytes variables, which might have been modified by the
3629 callback */
3630 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3631 if (!inputobj)
3632 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003633 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003634 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003635 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003636 *input = PyBytes_AS_STRING(inputobj);
3637 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003638 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003639 /* we can DECREF safely, as the exception has another reference,
3640 so the object won't go away. */
3641 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003642
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003643 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003644 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003645 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003646 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3647 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003648 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003649
3650 /* need more space? (at least enough for what we
3651 have+the replacement+the rest of the string (starting
3652 at the new input position), so we won't have to check space
3653 when there are no errors in the rest of the string) */
3654 repptr = PyUnicode_AS_UNICODE(repunicode);
3655 repsize = PyUnicode_GET_SIZE(repunicode);
3656 requiredsize = *outpos + repsize + insize-newpos;
3657 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003658 if (requiredsize<2*outsize)
3659 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003660 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003661 goto onError;
3662 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003663 }
3664 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003665 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003666 Py_UNICODE_COPY(*outptr, repptr, repsize);
3667 *outptr += repsize;
3668 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003669
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003670 /* we made it! */
3671 res = 0;
3672
Benjamin Peterson29060642009-01-31 22:14:21 +00003673 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003674 Py_XDECREF(restuple);
3675 return res;
3676}
3677
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003678/* --- UTF-7 Codec -------------------------------------------------------- */
3679
Antoine Pitrou244651a2009-05-04 18:56:13 +00003680/* See RFC2152 for details. We encode conservatively and decode liberally. */
3681
3682/* Three simple macros defining base-64. */
3683
3684/* Is c a base-64 character? */
3685
3686#define IS_BASE64(c) \
3687 (((c) >= 'A' && (c) <= 'Z') || \
3688 ((c) >= 'a' && (c) <= 'z') || \
3689 ((c) >= '0' && (c) <= '9') || \
3690 (c) == '+' || (c) == '/')
3691
3692/* given that c is a base-64 character, what is its base-64 value? */
3693
3694#define FROM_BASE64(c) \
3695 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3696 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3697 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3698 (c) == '+' ? 62 : 63)
3699
3700/* What is the base-64 character of the bottom 6 bits of n? */
3701
3702#define TO_BASE64(n) \
3703 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3704
3705/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3706 * decoded as itself. We are permissive on decoding; the only ASCII
3707 * byte not decoding to itself is the + which begins a base64
3708 * string. */
3709
3710#define DECODE_DIRECT(c) \
3711 ((c) <= 127 && (c) != '+')
3712
3713/* The UTF-7 encoder treats ASCII characters differently according to
3714 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3715 * the above). See RFC2152. This array identifies these different
3716 * sets:
3717 * 0 : "Set D"
3718 * alphanumeric and '(),-./:?
3719 * 1 : "Set O"
3720 * !"#$%&*;<=>@[]^_`{|}
3721 * 2 : "whitespace"
3722 * ht nl cr sp
3723 * 3 : special (must be base64 encoded)
3724 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3725 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003726
Tim Petersced69f82003-09-16 20:30:58 +00003727static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003728char utf7_category[128] = {
3729/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3730 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3731/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3732 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3733/* sp ! " # $ % & ' ( ) * + , - . / */
3734 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3735/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3736 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3737/* @ A B C D E F G H I J K L M N O */
3738 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3739/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3740 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3741/* ` a b c d e f g h i j k l m n o */
3742 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3743/* p q r s t u v w x y z { | } ~ del */
3744 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003745};
3746
Antoine Pitrou244651a2009-05-04 18:56:13 +00003747/* ENCODE_DIRECT: this character should be encoded as itself. The
3748 * answer depends on whether we are encoding set O as itself, and also
3749 * on whether we are encoding whitespace as itself. RFC2152 makes it
3750 * clear that the answers to these questions vary between
3751 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003752
Antoine Pitrou244651a2009-05-04 18:56:13 +00003753#define ENCODE_DIRECT(c, directO, directWS) \
3754 ((c) < 128 && (c) > 0 && \
3755 ((utf7_category[(c)] == 0) || \
3756 (directWS && (utf7_category[(c)] == 2)) || \
3757 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003758
Alexander Belopolsky40018472011-02-26 01:02:56 +00003759PyObject *
3760PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003761 Py_ssize_t size,
3762 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003763{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003764 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3765}
3766
Antoine Pitrou244651a2009-05-04 18:56:13 +00003767/* The decoder. The only state we preserve is our read position,
3768 * i.e. how many characters we have consumed. So if we end in the
3769 * middle of a shift sequence we have to back off the read position
3770 * and the output to the beginning of the sequence, otherwise we lose
3771 * all the shift state (seen bits, number of bits seen, high
3772 * surrogate). */
3773
Alexander Belopolsky40018472011-02-26 01:02:56 +00003774PyObject *
3775PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003776 Py_ssize_t size,
3777 const char *errors,
3778 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003779{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003780 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003781 Py_ssize_t startinpos;
3782 Py_ssize_t endinpos;
3783 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003784 const char *e;
3785 PyUnicodeObject *unicode;
3786 Py_UNICODE *p;
3787 const char *errmsg = "";
3788 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003789 Py_UNICODE *shiftOutStart;
3790 unsigned int base64bits = 0;
3791 unsigned long base64buffer = 0;
3792 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003793 PyObject *errorHandler = NULL;
3794 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003795
3796 unicode = _PyUnicode_New(size);
3797 if (!unicode)
3798 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003799 if (size == 0) {
3800 if (consumed)
3801 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003802 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003803 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003805 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003806 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003807 e = s + size;
3808
3809 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003810 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003811 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003812 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003813
Antoine Pitrou244651a2009-05-04 18:56:13 +00003814 if (inShift) { /* in a base-64 section */
3815 if (IS_BASE64(ch)) { /* consume a base-64 character */
3816 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3817 base64bits += 6;
3818 s++;
3819 if (base64bits >= 16) {
3820 /* we have enough bits for a UTF-16 value */
3821 Py_UNICODE outCh = (Py_UNICODE)
3822 (base64buffer >> (base64bits-16));
3823 base64bits -= 16;
3824 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3825 if (surrogate) {
3826 /* expecting a second surrogate */
3827 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3828#ifdef Py_UNICODE_WIDE
3829 *p++ = (((surrogate & 0x3FF)<<10)
3830 | (outCh & 0x3FF)) + 0x10000;
3831#else
3832 *p++ = surrogate;
3833 *p++ = outCh;
3834#endif
3835 surrogate = 0;
3836 }
3837 else {
3838 surrogate = 0;
3839 errmsg = "second surrogate missing";
3840 goto utf7Error;
3841 }
3842 }
3843 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3844 /* first surrogate */
3845 surrogate = outCh;
3846 }
3847 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3848 errmsg = "unexpected second surrogate";
3849 goto utf7Error;
3850 }
3851 else {
3852 *p++ = outCh;
3853 }
3854 }
3855 }
3856 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003857 inShift = 0;
3858 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003859 if (surrogate) {
3860 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003861 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003863 if (base64bits > 0) { /* left-over bits */
3864 if (base64bits >= 6) {
3865 /* We've seen at least one base-64 character */
3866 errmsg = "partial character in shift sequence";
3867 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003869 else {
3870 /* Some bits remain; they should be zero */
3871 if (base64buffer != 0) {
3872 errmsg = "non-zero padding bits in shift sequence";
3873 goto utf7Error;
3874 }
3875 }
3876 }
3877 if (ch != '-') {
3878 /* '-' is absorbed; other terminating
3879 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003880 *p++ = ch;
3881 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003882 }
3883 }
3884 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003885 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 s++; /* consume '+' */
3887 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003888 s++;
3889 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003890 }
3891 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003892 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003893 shiftOutStart = p;
3894 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003895 }
3896 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003898 *p++ = ch;
3899 s++;
3900 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003901 else {
3902 startinpos = s-starts;
3903 s++;
3904 errmsg = "unexpected special character";
3905 goto utf7Error;
3906 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003907 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003908utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003909 outpos = p-PyUnicode_AS_UNICODE(unicode);
3910 endinpos = s-starts;
3911 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003912 errors, &errorHandler,
3913 "utf7", errmsg,
3914 &starts, &e, &startinpos, &endinpos, &exc, &s,
3915 &unicode, &outpos, &p))
3916 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003917 }
3918
Antoine Pitrou244651a2009-05-04 18:56:13 +00003919 /* end of string */
3920
3921 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3922 /* if we're in an inconsistent state, that's an error */
3923 if (surrogate ||
3924 (base64bits >= 6) ||
3925 (base64bits > 0 && base64buffer != 0)) {
3926 outpos = p-PyUnicode_AS_UNICODE(unicode);
3927 endinpos = size;
3928 if (unicode_decode_call_errorhandler(
3929 errors, &errorHandler,
3930 "utf7", "unterminated shift sequence",
3931 &starts, &e, &startinpos, &endinpos, &exc, &s,
3932 &unicode, &outpos, &p))
3933 goto onError;
3934 if (s < e)
3935 goto restart;
3936 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003937 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003938
3939 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003940 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003941 if (inShift) {
3942 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003943 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003944 }
3945 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003946 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003947 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003948 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003949
Victor Stinnerfe226c02011-10-03 03:52:20 +02003950 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003951 goto onError;
3952
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003953 Py_XDECREF(errorHandler);
3954 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003955#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003956 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003957 Py_DECREF(unicode);
3958 return NULL;
3959 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003960#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003961 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003962 return (PyObject *)unicode;
3963
Benjamin Peterson29060642009-01-31 22:14:21 +00003964 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003965 Py_XDECREF(errorHandler);
3966 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003967 Py_DECREF(unicode);
3968 return NULL;
3969}
3970
3971
Alexander Belopolsky40018472011-02-26 01:02:56 +00003972PyObject *
3973PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003974 Py_ssize_t size,
3975 int base64SetO,
3976 int base64WhiteSpace,
3977 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003978{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003979 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003980 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003981 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003982 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003983 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003984 unsigned int base64bits = 0;
3985 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003986 char * out;
3987 char * start;
3988
3989 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003990 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003991
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003992 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003993 return PyErr_NoMemory();
3994
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003996 if (v == NULL)
3997 return NULL;
3998
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003999 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004000 for (;i < size; ++i) {
4001 Py_UNICODE ch = s[i];
4002
Antoine Pitrou244651a2009-05-04 18:56:13 +00004003 if (inShift) {
4004 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4005 /* shifting out */
4006 if (base64bits) { /* output remaining bits */
4007 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4008 base64buffer = 0;
4009 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004010 }
4011 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004012 /* Characters not in the BASE64 set implicitly unshift the sequence
4013 so no '-' is required, except if the character is itself a '-' */
4014 if (IS_BASE64(ch) || ch == '-') {
4015 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004016 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004017 *out++ = (char) ch;
4018 }
4019 else {
4020 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004021 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004022 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004023 else { /* not in a shift sequence */
4024 if (ch == '+') {
4025 *out++ = '+';
4026 *out++ = '-';
4027 }
4028 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4029 *out++ = (char) ch;
4030 }
4031 else {
4032 *out++ = '+';
4033 inShift = 1;
4034 goto encode_char;
4035 }
4036 }
4037 continue;
4038encode_char:
4039#ifdef Py_UNICODE_WIDE
4040 if (ch >= 0x10000) {
4041 /* code first surrogate */
4042 base64bits += 16;
4043 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4044 while (base64bits >= 6) {
4045 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4046 base64bits -= 6;
4047 }
4048 /* prepare second surrogate */
4049 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4050 }
4051#endif
4052 base64bits += 16;
4053 base64buffer = (base64buffer << 16) | ch;
4054 while (base64bits >= 6) {
4055 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4056 base64bits -= 6;
4057 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004058 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004059 if (base64bits)
4060 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4061 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004062 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004063 if (_PyBytes_Resize(&v, out - start) < 0)
4064 return NULL;
4065 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004066}
4067
Antoine Pitrou244651a2009-05-04 18:56:13 +00004068#undef IS_BASE64
4069#undef FROM_BASE64
4070#undef TO_BASE64
4071#undef DECODE_DIRECT
4072#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004073
Guido van Rossumd57fd912000-03-10 22:53:23 +00004074/* --- UTF-8 Codec -------------------------------------------------------- */
4075
Tim Petersced69f82003-09-16 20:30:58 +00004076static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004077char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004078 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4079 illegal prefix. See RFC 3629 for details */
4080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004082 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004083 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4084 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4085 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4086 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004087 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4088 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 80-8F */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004089 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4090 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004091 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4092 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4093 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4094 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4095 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 /* F0-F4 + F5-FF */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004096};
4097
Alexander Belopolsky40018472011-02-26 01:02:56 +00004098PyObject *
4099PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004100 Py_ssize_t size,
4101 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004102{
Walter Dörwald69652032004-09-07 20:24:22 +00004103 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4104}
4105
Antoine Pitrouab868312009-01-10 15:40:25 +00004106/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4107#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4108
4109/* Mask to quickly check whether a C 'long' contains a
4110 non-ASCII, UTF8-encoded char. */
4111#if (SIZEOF_LONG == 8)
4112# define ASCII_CHAR_MASK 0x8080808080808080L
4113#elif (SIZEOF_LONG == 4)
4114# define ASCII_CHAR_MASK 0x80808080L
4115#else
4116# error C 'long' size should be either 4 or 8!
4117#endif
4118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004119/* Scans a UTF-8 string and returns the maximum character to be expected,
4120 the size of the decoded unicode string and if any major errors were
4121 encountered.
4122
4123 This function does check basic UTF-8 sanity, it does however NOT CHECK
4124 if the string contains surrogates, and if all continuation bytes are
4125 within the correct ranges, these checks are performed in
4126 PyUnicode_DecodeUTF8Stateful.
4127
4128 If it sets has_errors to 1, it means the value of unicode_size and max_char
4129 will be bogus and you should not rely on useful information in them.
4130 */
4131static Py_UCS4
4132utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4133 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4134 int *has_errors)
4135{
4136 Py_ssize_t n;
4137 Py_ssize_t char_count = 0;
4138 Py_UCS4 max_char = 127, new_max;
4139 Py_UCS4 upper_bound;
4140 const unsigned char *p = (const unsigned char *)s;
4141 const unsigned char *end = p + string_size;
4142 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4143 int err = 0;
4144
4145 for (; p < end && !err; ++p, ++char_count) {
4146 /* Only check value if it's not a ASCII char... */
4147 if (*p < 0x80) {
4148 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4149 an explanation. */
4150 if (!((size_t) p & LONG_PTR_MASK)) {
4151 /* Help register allocation */
4152 register const unsigned char *_p = p;
4153 while (_p < aligned_end) {
4154 unsigned long value = *(unsigned long *) _p;
4155 if (value & ASCII_CHAR_MASK)
4156 break;
4157 _p += SIZEOF_LONG;
4158 char_count += SIZEOF_LONG;
4159 }
4160 p = _p;
4161 if (p == end)
4162 break;
4163 }
4164 }
4165 if (*p >= 0x80) {
4166 n = utf8_code_length[*p];
4167 new_max = max_char;
4168 switch (n) {
4169 /* invalid start byte */
4170 case 0:
4171 err = 1;
4172 break;
4173 case 2:
4174 /* Code points between 0x00FF and 0x07FF inclusive.
4175 Approximate the upper bound of the code point,
4176 if this flips over 255 we can be sure it will be more
4177 than 255 and the string will need 2 bytes per code coint,
4178 if it stays under or equal to 255, we can be sure 1 byte
4179 is enough.
4180 ((*p & 0b00011111) << 6) | 0b00111111 */
4181 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4182 if (max_char < upper_bound)
4183 new_max = upper_bound;
4184 /* Ensure we track at least that we left ASCII space. */
4185 if (new_max < 128)
4186 new_max = 128;
4187 break;
4188 case 3:
4189 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4190 always > 255 and <= 65535 and will always need 2 bytes. */
4191 if (max_char < 65535)
4192 new_max = 65535;
4193 break;
4194 case 4:
4195 /* Code point will be above 0xFFFF for sure in this case. */
4196 new_max = 65537;
4197 break;
4198 /* Internal error, this should be caught by the first if */
4199 case 1:
4200 default:
4201 assert(0 && "Impossible case in utf8_max_char_and_size");
4202 err = 1;
4203 }
4204 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004205 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004206 --n;
4207 /* Check if the follow up chars are all valid continuation bytes */
4208 if (n >= 1) {
4209 const unsigned char *cont;
4210 if ((p + n) >= end) {
4211 if (consumed == 0)
4212 /* incomplete data, non-incremental decoding */
4213 err = 1;
4214 break;
4215 }
4216 for (cont = p + 1; cont < (p + n); ++cont) {
4217 if ((*cont & 0xc0) != 0x80) {
4218 err = 1;
4219 break;
4220 }
4221 }
4222 p += n;
4223 }
4224 else
4225 err = 1;
4226 max_char = new_max;
4227 }
4228 }
4229
4230 if (unicode_size)
4231 *unicode_size = char_count;
4232 if (has_errors)
4233 *has_errors = err;
4234 return max_char;
4235}
4236
4237/* Similar to PyUnicode_WRITE but can also write into wstr field
4238 of the legacy unicode representation */
4239#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4240 do { \
4241 const int k_ = (kind); \
4242 if (k_ == PyUnicode_WCHAR_KIND) \
4243 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4244 else if (k_ == PyUnicode_1BYTE_KIND) \
4245 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4246 else if (k_ == PyUnicode_2BYTE_KIND) \
4247 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4248 else \
4249 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4250 } while (0)
4251
Alexander Belopolsky40018472011-02-26 01:02:56 +00004252PyObject *
4253PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004254 Py_ssize_t size,
4255 const char *errors,
4256 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004257{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004258 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004259 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004260 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004261 Py_ssize_t startinpos;
4262 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004263 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004264 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004265 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004266 PyObject *errorHandler = NULL;
4267 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004268 Py_UCS4 maxchar = 0;
4269 Py_ssize_t unicode_size;
4270 Py_ssize_t i;
4271 int kind;
4272 void *data;
4273 int has_errors;
4274 Py_UNICODE *error_outptr;
4275#if SIZEOF_WCHAR_T == 2
4276 Py_ssize_t wchar_offset = 0;
4277#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004278
Walter Dörwald69652032004-09-07 20:24:22 +00004279 if (size == 0) {
4280 if (consumed)
4281 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004282 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004283 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004284 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4285 consumed, &has_errors);
4286 if (has_errors) {
4287 unicode = _PyUnicode_New(size);
4288 if (!unicode)
4289 return NULL;
4290 kind = PyUnicode_WCHAR_KIND;
4291 data = PyUnicode_AS_UNICODE(unicode);
4292 assert(data != NULL);
4293 }
4294 else {
4295 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4296 if (!unicode)
4297 return NULL;
4298 /* When the string is ASCII only, just use memcpy and return.
4299 unicode_size may be != size if there is an incomplete UTF-8
4300 sequence at the end of the ASCII block. */
4301 if (maxchar < 128 && size == unicode_size) {
4302 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4303 return (PyObject *)unicode;
4304 }
4305 kind = PyUnicode_KIND(unicode);
4306 data = PyUnicode_DATA(unicode);
4307 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004309 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004310 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004311 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004312
4313 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004314 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004315
4316 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004317 /* Fast path for runs of ASCII characters. Given that common UTF-8
4318 input will consist of an overwhelming majority of ASCII
4319 characters, we try to optimize for this case by checking
4320 as many characters as a C 'long' can contain.
4321 First, check if we can do an aligned read, as most CPUs have
4322 a penalty for unaligned reads.
4323 */
4324 if (!((size_t) s & LONG_PTR_MASK)) {
4325 /* Help register allocation */
4326 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004327 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004328 while (_s < aligned_end) {
4329 /* Read a whole long at a time (either 4 or 8 bytes),
4330 and do a fast unrolled copy if it only contains ASCII
4331 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004332 unsigned long value = *(unsigned long *) _s;
4333 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004334 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004335 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4336 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4337 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4338 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004339#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004340 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4341 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4342 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4343 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004344#endif
4345 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004346 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004347 }
4348 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004349 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004350 if (s == e)
4351 break;
4352 ch = (unsigned char)*s;
4353 }
4354 }
4355
4356 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004357 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004358 s++;
4359 continue;
4360 }
4361
4362 n = utf8_code_length[ch];
4363
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004364 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004365 if (consumed)
4366 break;
4367 else {
4368 errmsg = "unexpected end of data";
4369 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004370 endinpos = startinpos+1;
4371 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4372 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004373 goto utf8Error;
4374 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004375 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004376
4377 switch (n) {
4378
4379 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004380 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004381 startinpos = s-starts;
4382 endinpos = startinpos+1;
4383 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004384
4385 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004386 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004387 startinpos = s-starts;
4388 endinpos = startinpos+1;
4389 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004390
4391 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004392 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004393 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004394 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004395 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004396 goto utf8Error;
4397 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004398 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004399 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004400 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004401 break;
4402
4403 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004404 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4405 will result in surrogates in range d800-dfff. Surrogates are
4406 not valid UTF-8 so they are rejected.
4407 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4408 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004409 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004410 (s[2] & 0xc0) != 0x80 ||
4411 ((unsigned char)s[0] == 0xE0 &&
4412 (unsigned char)s[1] < 0xA0) ||
4413 ((unsigned char)s[0] == 0xED &&
4414 (unsigned char)s[1] > 0x9F)) {
4415 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004416 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004417 endinpos = startinpos + 1;
4418
4419 /* if s[1] first two bits are 1 and 0, then the invalid
4420 continuation byte is s[2], so increment endinpos by 1,
4421 if not, s[1] is invalid and endinpos doesn't need to
4422 be incremented. */
4423 if ((s[1] & 0xC0) == 0x80)
4424 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004425 goto utf8Error;
4426 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004427 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004428 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004429 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004430 break;
4431
4432 case 4:
4433 if ((s[1] & 0xc0) != 0x80 ||
4434 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004435 (s[3] & 0xc0) != 0x80 ||
4436 ((unsigned char)s[0] == 0xF0 &&
4437 (unsigned char)s[1] < 0x90) ||
4438 ((unsigned char)s[0] == 0xF4 &&
4439 (unsigned char)s[1] > 0x8F)) {
4440 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004442 endinpos = startinpos + 1;
4443 if ((s[1] & 0xC0) == 0x80) {
4444 endinpos++;
4445 if ((s[2] & 0xC0) == 0x80)
4446 endinpos++;
4447 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004448 goto utf8Error;
4449 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004450 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004451 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4452 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004454 /* If the string is flexible or we have native UCS-4, write
4455 directly.. */
4456 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4457 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004459 else {
4460 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004462 /* translate from 10000..10FFFF to 0..FFFF */
4463 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004465 /* high surrogate = top 10 bits added to D800 */
4466 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4467 (Py_UNICODE)(0xD800 + (ch >> 10)));
4468
4469 /* low surrogate = bottom 10 bits added to DC00 */
4470 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4471 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4472 }
4473#if SIZEOF_WCHAR_T == 2
4474 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004475#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004477 }
4478 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004479 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004480
Benjamin Peterson29060642009-01-31 22:14:21 +00004481 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004482 /* If this is not yet a resizable string, make it one.. */
4483 if (kind != PyUnicode_WCHAR_KIND) {
4484 const Py_UNICODE *u;
4485 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4486 if (!new_unicode)
4487 goto onError;
4488 u = PyUnicode_AsUnicode((PyObject *)unicode);
4489 if (!u)
4490 goto onError;
4491#if SIZEOF_WCHAR_T == 2
4492 i += wchar_offset;
4493#endif
4494 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4495 Py_DECREF(unicode);
4496 unicode = new_unicode;
4497 kind = 0;
4498 data = PyUnicode_AS_UNICODE(new_unicode);
4499 assert(data != NULL);
4500 }
4501 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004502 if (unicode_decode_call_errorhandler(
4503 errors, &errorHandler,
4504 "utf8", errmsg,
4505 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004506 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004507 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004508 /* Update data because unicode_decode_call_errorhandler might have
4509 re-created or resized the unicode object. */
4510 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004513 /* Ensure the unicode_size calculation above was correct: */
4514 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4515
Walter Dörwald69652032004-09-07 20:24:22 +00004516 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004517 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004519 /* Adjust length and ready string when it contained errors and
4520 is of the old resizable kind. */
4521 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004522 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004523 goto onError;
4524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004525
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004526 Py_XDECREF(errorHandler);
4527 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004528#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004529 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004530 Py_DECREF(unicode);
4531 return NULL;
4532 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004533#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004534 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535 return (PyObject *)unicode;
4536
Benjamin Peterson29060642009-01-31 22:14:21 +00004537 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004538 Py_XDECREF(errorHandler);
4539 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004540 Py_DECREF(unicode);
4541 return NULL;
4542}
4543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004544#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004545
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004546#ifdef __APPLE__
4547
4548/* Simplified UTF-8 decoder using surrogateescape error handler,
4549 used to decode the command line arguments on Mac OS X. */
4550
4551wchar_t*
4552_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4553{
4554 int n;
4555 const char *e;
4556 wchar_t *unicode, *p;
4557
4558 /* Note: size will always be longer than the resulting Unicode
4559 character count */
4560 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4561 PyErr_NoMemory();
4562 return NULL;
4563 }
4564 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4565 if (!unicode)
4566 return NULL;
4567
4568 /* Unpack UTF-8 encoded data */
4569 p = unicode;
4570 e = s + size;
4571 while (s < e) {
4572 Py_UCS4 ch = (unsigned char)*s;
4573
4574 if (ch < 0x80) {
4575 *p++ = (wchar_t)ch;
4576 s++;
4577 continue;
4578 }
4579
4580 n = utf8_code_length[ch];
4581 if (s + n > e) {
4582 goto surrogateescape;
4583 }
4584
4585 switch (n) {
4586 case 0:
4587 case 1:
4588 goto surrogateescape;
4589
4590 case 2:
4591 if ((s[1] & 0xc0) != 0x80)
4592 goto surrogateescape;
4593 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4594 assert ((ch > 0x007F) && (ch <= 0x07FF));
4595 *p++ = (wchar_t)ch;
4596 break;
4597
4598 case 3:
4599 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4600 will result in surrogates in range d800-dfff. Surrogates are
4601 not valid UTF-8 so they are rejected.
4602 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4603 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4604 if ((s[1] & 0xc0) != 0x80 ||
4605 (s[2] & 0xc0) != 0x80 ||
4606 ((unsigned char)s[0] == 0xE0 &&
4607 (unsigned char)s[1] < 0xA0) ||
4608 ((unsigned char)s[0] == 0xED &&
4609 (unsigned char)s[1] > 0x9F)) {
4610
4611 goto surrogateescape;
4612 }
4613 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4614 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004615 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004616 break;
4617
4618 case 4:
4619 if ((s[1] & 0xc0) != 0x80 ||
4620 (s[2] & 0xc0) != 0x80 ||
4621 (s[3] & 0xc0) != 0x80 ||
4622 ((unsigned char)s[0] == 0xF0 &&
4623 (unsigned char)s[1] < 0x90) ||
4624 ((unsigned char)s[0] == 0xF4 &&
4625 (unsigned char)s[1] > 0x8F)) {
4626 goto surrogateescape;
4627 }
4628 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4629 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4630 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4631
4632#if SIZEOF_WCHAR_T == 4
4633 *p++ = (wchar_t)ch;
4634#else
4635 /* compute and append the two surrogates: */
4636
4637 /* translate from 10000..10FFFF to 0..FFFF */
4638 ch -= 0x10000;
4639
4640 /* high surrogate = top 10 bits added to D800 */
4641 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4642
4643 /* low surrogate = bottom 10 bits added to DC00 */
4644 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4645#endif
4646 break;
4647 }
4648 s += n;
4649 continue;
4650
4651 surrogateescape:
4652 *p++ = 0xDC00 + ch;
4653 s++;
4654 }
4655 *p = L'\0';
4656 return unicode;
4657}
4658
4659#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004661/* Primary internal function which creates utf8 encoded bytes objects.
4662
4663 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004664 and allocate exactly as much space needed at the end. Else allocate the
4665 maximum possible needed (4 result bytes per Unicode character), and return
4666 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004667*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004668PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004669_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004670{
Tim Peters602f7402002-04-27 18:03:26 +00004671#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004672
Guido van Rossum98297ee2007-11-06 21:34:58 +00004673 Py_ssize_t i; /* index into s of next input byte */
4674 PyObject *result; /* result string object */
4675 char *p; /* next free byte in output buffer */
4676 Py_ssize_t nallocated; /* number of result bytes allocated */
4677 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004678 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004679 PyObject *errorHandler = NULL;
4680 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004681 int kind;
4682 void *data;
4683 Py_ssize_t size;
4684 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4685#if SIZEOF_WCHAR_T == 2
4686 Py_ssize_t wchar_offset = 0;
4687#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004688
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004689 if (!PyUnicode_Check(unicode)) {
4690 PyErr_BadArgument();
4691 return NULL;
4692 }
4693
4694 if (PyUnicode_READY(unicode) == -1)
4695 return NULL;
4696
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004697 if (PyUnicode_UTF8(unicode))
4698 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4699 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004700
4701 kind = PyUnicode_KIND(unicode);
4702 data = PyUnicode_DATA(unicode);
4703 size = PyUnicode_GET_LENGTH(unicode);
4704
Tim Peters602f7402002-04-27 18:03:26 +00004705 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004706
Tim Peters602f7402002-04-27 18:03:26 +00004707 if (size <= MAX_SHORT_UNICHARS) {
4708 /* Write into the stack buffer; nallocated can't overflow.
4709 * At the end, we'll allocate exactly as much heap space as it
4710 * turns out we need.
4711 */
4712 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004713 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004714 p = stackbuf;
4715 }
4716 else {
4717 /* Overallocate on the heap, and give the excess back at the end. */
4718 nallocated = size * 4;
4719 if (nallocated / 4 != size) /* overflow! */
4720 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004721 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004722 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004723 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004724 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004725 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004726
Tim Peters602f7402002-04-27 18:03:26 +00004727 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004728 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004729
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004730 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004731 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004732 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004733
Guido van Rossumd57fd912000-03-10 22:53:23 +00004734 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004735 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004736 *p++ = (char)(0xc0 | (ch >> 6));
4737 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004738 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 Py_ssize_t newpos;
4740 PyObject *rep;
4741 Py_ssize_t repsize, k, startpos;
4742 startpos = i-1;
4743#if SIZEOF_WCHAR_T == 2
4744 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004745#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004746 rep = unicode_encode_call_errorhandler(
4747 errors, &errorHandler, "utf-8", "surrogates not allowed",
Martin v. Löwis23e275b2011-11-02 18:02:51 +01004748 obj, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004749 if (!rep)
4750 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004752 if (PyBytes_Check(rep))
4753 repsize = PyBytes_GET_SIZE(rep);
4754 else
4755 repsize = PyUnicode_GET_SIZE(rep);
4756
4757 if (repsize > 4) {
4758 Py_ssize_t offset;
4759
4760 if (result == NULL)
4761 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004762 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004763 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004765 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4766 /* integer overflow */
4767 PyErr_NoMemory();
4768 goto error;
4769 }
4770 nallocated += repsize - 4;
4771 if (result != NULL) {
4772 if (_PyBytes_Resize(&result, nallocated) < 0)
4773 goto error;
4774 } else {
4775 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004776 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 goto error;
4778 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4779 }
4780 p = PyBytes_AS_STRING(result) + offset;
4781 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004782
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 if (PyBytes_Check(rep)) {
4784 char *prep = PyBytes_AS_STRING(rep);
4785 for(k = repsize; k > 0; k--)
4786 *p++ = *prep++;
4787 } else /* rep is unicode */ {
4788 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4789 Py_UNICODE c;
4790
4791 for(k=0; k<repsize; k++) {
4792 c = prep[k];
4793 if (0x80 <= c) {
Martin v. Löwis9e816682011-11-02 12:45:42 +01004794 raise_encode_exception_obj(&exc, "utf-8",
4795 (PyObject*)unicode,
4796 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004798 goto error;
4799 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004800 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004801 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004802 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004803 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004804 } else if (ch < 0x10000) {
4805 *p++ = (char)(0xe0 | (ch >> 12));
4806 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4807 *p++ = (char)(0x80 | (ch & 0x3f));
4808 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004809 /* Encode UCS4 Unicode ordinals */
4810 *p++ = (char)(0xf0 | (ch >> 18));
4811 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4812 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4813 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004814#if SIZEOF_WCHAR_T == 2
4815 wchar_offset++;
4816#endif
Tim Peters602f7402002-04-27 18:03:26 +00004817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004818 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004819
Guido van Rossum98297ee2007-11-06 21:34:58 +00004820 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004821 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004822 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004823 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004824 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004825 }
4826 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004827 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004828 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004829 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004830 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004831 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004832
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004833 Py_XDECREF(errorHandler);
4834 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004835 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004836 error:
4837 Py_XDECREF(errorHandler);
4838 Py_XDECREF(exc);
4839 Py_XDECREF(result);
4840 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004841
Tim Peters602f7402002-04-27 18:03:26 +00004842#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004843}
4844
Alexander Belopolsky40018472011-02-26 01:02:56 +00004845PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004846PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4847 Py_ssize_t size,
4848 const char *errors)
4849{
4850 PyObject *v, *unicode;
4851
4852 unicode = PyUnicode_FromUnicode(s, size);
4853 if (unicode == NULL)
4854 return NULL;
4855 v = _PyUnicode_AsUTF8String(unicode, errors);
4856 Py_DECREF(unicode);
4857 return v;
4858}
4859
4860PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004861PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004862{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004863 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004864}
4865
Walter Dörwald41980ca2007-08-16 21:55:45 +00004866/* --- UTF-32 Codec ------------------------------------------------------- */
4867
4868PyObject *
4869PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004870 Py_ssize_t size,
4871 const char *errors,
4872 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004873{
4874 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4875}
4876
4877PyObject *
4878PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004879 Py_ssize_t size,
4880 const char *errors,
4881 int *byteorder,
4882 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004883{
4884 const char *starts = s;
4885 Py_ssize_t startinpos;
4886 Py_ssize_t endinpos;
4887 Py_ssize_t outpos;
4888 PyUnicodeObject *unicode;
4889 Py_UNICODE *p;
4890#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004891 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004892 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004893#else
4894 const int pairs = 0;
4895#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004896 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004897 int bo = 0; /* assume native ordering by default */
4898 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004899 /* Offsets from q for retrieving bytes in the right order. */
4900#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4901 int iorder[] = {0, 1, 2, 3};
4902#else
4903 int iorder[] = {3, 2, 1, 0};
4904#endif
4905 PyObject *errorHandler = NULL;
4906 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004907
Walter Dörwald41980ca2007-08-16 21:55:45 +00004908 q = (unsigned char *)s;
4909 e = q + size;
4910
4911 if (byteorder)
4912 bo = *byteorder;
4913
4914 /* Check for BOM marks (U+FEFF) in the input and adjust current
4915 byte order setting accordingly. In native mode, the leading BOM
4916 mark is skipped, in all other modes, it is copied to the output
4917 stream as-is (giving a ZWNBSP character). */
4918 if (bo == 0) {
4919 if (size >= 4) {
4920 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004921 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004922#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004923 if (bom == 0x0000FEFF) {
4924 q += 4;
4925 bo = -1;
4926 }
4927 else if (bom == 0xFFFE0000) {
4928 q += 4;
4929 bo = 1;
4930 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004932 if (bom == 0x0000FEFF) {
4933 q += 4;
4934 bo = 1;
4935 }
4936 else if (bom == 0xFFFE0000) {
4937 q += 4;
4938 bo = -1;
4939 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004940#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004941 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004942 }
4943
4944 if (bo == -1) {
4945 /* force LE */
4946 iorder[0] = 0;
4947 iorder[1] = 1;
4948 iorder[2] = 2;
4949 iorder[3] = 3;
4950 }
4951 else if (bo == 1) {
4952 /* force BE */
4953 iorder[0] = 3;
4954 iorder[1] = 2;
4955 iorder[2] = 1;
4956 iorder[3] = 0;
4957 }
4958
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004959 /* On narrow builds we split characters outside the BMP into two
4960 codepoints => count how much extra space we need. */
4961#ifndef Py_UNICODE_WIDE
4962 for (qq = q; qq < e; qq += 4)
4963 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4964 pairs++;
4965#endif
4966
4967 /* This might be one to much, because of a BOM */
4968 unicode = _PyUnicode_New((size+3)/4+pairs);
4969 if (!unicode)
4970 return NULL;
4971 if (size == 0)
4972 return (PyObject *)unicode;
4973
4974 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004975 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004976
Walter Dörwald41980ca2007-08-16 21:55:45 +00004977 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004978 Py_UCS4 ch;
4979 /* remaining bytes at the end? (size should be divisible by 4) */
4980 if (e-q<4) {
4981 if (consumed)
4982 break;
4983 errmsg = "truncated data";
4984 startinpos = ((const char *)q)-starts;
4985 endinpos = ((const char *)e)-starts;
4986 goto utf32Error;
4987 /* The remaining input chars are ignored if the callback
4988 chooses to skip the input */
4989 }
4990 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4991 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004992
Benjamin Peterson29060642009-01-31 22:14:21 +00004993 if (ch >= 0x110000)
4994 {
4995 errmsg = "codepoint not in range(0x110000)";
4996 startinpos = ((const char *)q)-starts;
4997 endinpos = startinpos+4;
4998 goto utf32Error;
4999 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 if (ch >= 0x10000)
5002 {
5003 *p++ = 0xD800 | ((ch-0x10000) >> 10);
5004 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
5005 }
5006 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00005007#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005008 *p++ = ch;
5009 q += 4;
5010 continue;
5011 utf32Error:
5012 outpos = p-PyUnicode_AS_UNICODE(unicode);
5013 if (unicode_decode_call_errorhandler(
5014 errors, &errorHandler,
5015 "utf32", errmsg,
5016 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5017 &unicode, &outpos, &p))
5018 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019 }
5020
5021 if (byteorder)
5022 *byteorder = bo;
5023
5024 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005025 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005026
5027 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005028 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005029 goto onError;
5030
5031 Py_XDECREF(errorHandler);
5032 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005033#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005034 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005035 Py_DECREF(unicode);
5036 return NULL;
5037 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005038#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005039 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005040 return (PyObject *)unicode;
5041
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043 Py_DECREF(unicode);
5044 Py_XDECREF(errorHandler);
5045 Py_XDECREF(exc);
5046 return NULL;
5047}
5048
5049PyObject *
5050PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 Py_ssize_t size,
5052 const char *errors,
5053 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005055 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005056 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005057 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005058#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005059 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005060#else
5061 const int pairs = 0;
5062#endif
5063 /* Offsets from p for storing byte pairs in the right order. */
5064#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5065 int iorder[] = {0, 1, 2, 3};
5066#else
5067 int iorder[] = {3, 2, 1, 0};
5068#endif
5069
Benjamin Peterson29060642009-01-31 22:14:21 +00005070#define STORECHAR(CH) \
5071 do { \
5072 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5073 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5074 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5075 p[iorder[0]] = (CH) & 0xff; \
5076 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077 } while(0)
5078
5079 /* In narrow builds we can output surrogate pairs as one codepoint,
5080 so we need less space. */
5081#ifndef Py_UNICODE_WIDE
5082 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005083 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5084 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5085 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005087 nsize = (size - pairs + (byteorder == 0));
5088 bytesize = nsize * 4;
5089 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005090 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005091 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092 if (v == NULL)
5093 return NULL;
5094
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005095 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005096 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005097 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005098 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005099 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100
5101 if (byteorder == -1) {
5102 /* force LE */
5103 iorder[0] = 0;
5104 iorder[1] = 1;
5105 iorder[2] = 2;
5106 iorder[3] = 3;
5107 }
5108 else if (byteorder == 1) {
5109 /* force BE */
5110 iorder[0] = 3;
5111 iorder[1] = 2;
5112 iorder[2] = 1;
5113 iorder[3] = 0;
5114 }
5115
5116 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005117 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005118#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005119 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5120 Py_UCS4 ch2 = *s;
5121 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5122 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5123 s++;
5124 size--;
5125 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005126 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005127#endif
5128 STORECHAR(ch);
5129 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005130
5131 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005132 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005133#undef STORECHAR
5134}
5135
Alexander Belopolsky40018472011-02-26 01:02:56 +00005136PyObject *
5137PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005138{
5139 if (!PyUnicode_Check(unicode)) {
5140 PyErr_BadArgument();
5141 return NULL;
5142 }
5143 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005144 PyUnicode_GET_SIZE(unicode),
5145 NULL,
5146 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005147}
5148
Guido van Rossumd57fd912000-03-10 22:53:23 +00005149/* --- UTF-16 Codec ------------------------------------------------------- */
5150
Tim Peters772747b2001-08-09 22:21:55 +00005151PyObject *
5152PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005153 Py_ssize_t size,
5154 const char *errors,
5155 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005156{
Walter Dörwald69652032004-09-07 20:24:22 +00005157 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5158}
5159
Antoine Pitrouab868312009-01-10 15:40:25 +00005160/* Two masks for fast checking of whether a C 'long' may contain
5161 UTF16-encoded surrogate characters. This is an efficient heuristic,
5162 assuming that non-surrogate characters with a code point >= 0x8000 are
5163 rare in most input.
5164 FAST_CHAR_MASK is used when the input is in native byte ordering,
5165 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005166*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005167#if (SIZEOF_LONG == 8)
5168# define FAST_CHAR_MASK 0x8000800080008000L
5169# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5170#elif (SIZEOF_LONG == 4)
5171# define FAST_CHAR_MASK 0x80008000L
5172# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5173#else
5174# error C 'long' size should be either 4 or 8!
5175#endif
5176
Walter Dörwald69652032004-09-07 20:24:22 +00005177PyObject *
5178PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005179 Py_ssize_t size,
5180 const char *errors,
5181 int *byteorder,
5182 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005183{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005184 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005185 Py_ssize_t startinpos;
5186 Py_ssize_t endinpos;
5187 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005188 PyUnicodeObject *unicode;
5189 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005190 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005191 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005192 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005193 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005194 /* Offsets from q for retrieving byte pairs in the right order. */
5195#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5196 int ihi = 1, ilo = 0;
5197#else
5198 int ihi = 0, ilo = 1;
5199#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005200 PyObject *errorHandler = NULL;
5201 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005202
5203 /* Note: size will always be longer than the resulting Unicode
5204 character count */
5205 unicode = _PyUnicode_New(size);
5206 if (!unicode)
5207 return NULL;
5208 if (size == 0)
5209 return (PyObject *)unicode;
5210
5211 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005212 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005213 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005214 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
5216 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005217 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005219 /* Check for BOM marks (U+FEFF) in the input and adjust current
5220 byte order setting accordingly. In native mode, the leading BOM
5221 mark is skipped, in all other modes, it is copied to the output
5222 stream as-is (giving a ZWNBSP character). */
5223 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005224 if (size >= 2) {
5225 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005226#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005227 if (bom == 0xFEFF) {
5228 q += 2;
5229 bo = -1;
5230 }
5231 else if (bom == 0xFFFE) {
5232 q += 2;
5233 bo = 1;
5234 }
Tim Petersced69f82003-09-16 20:30:58 +00005235#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005236 if (bom == 0xFEFF) {
5237 q += 2;
5238 bo = 1;
5239 }
5240 else if (bom == 0xFFFE) {
5241 q += 2;
5242 bo = -1;
5243 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005244#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005245 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005246 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005247
Tim Peters772747b2001-08-09 22:21:55 +00005248 if (bo == -1) {
5249 /* force LE */
5250 ihi = 1;
5251 ilo = 0;
5252 }
5253 else if (bo == 1) {
5254 /* force BE */
5255 ihi = 0;
5256 ilo = 1;
5257 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005258#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5259 native_ordering = ilo < ihi;
5260#else
5261 native_ordering = ilo > ihi;
5262#endif
Tim Peters772747b2001-08-09 22:21:55 +00005263
Antoine Pitrouab868312009-01-10 15:40:25 +00005264 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005265 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005266 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005267 /* First check for possible aligned read of a C 'long'. Unaligned
5268 reads are more expensive, better to defer to another iteration. */
5269 if (!((size_t) q & LONG_PTR_MASK)) {
5270 /* Fast path for runs of non-surrogate chars. */
5271 register const unsigned char *_q = q;
5272 Py_UNICODE *_p = p;
5273 if (native_ordering) {
5274 /* Native ordering is simple: as long as the input cannot
5275 possibly contain a surrogate char, do an unrolled copy
5276 of several 16-bit code points to the target object.
5277 The non-surrogate check is done on several input bytes
5278 at a time (as many as a C 'long' can contain). */
5279 while (_q < aligned_end) {
5280 unsigned long data = * (unsigned long *) _q;
5281 if (data & FAST_CHAR_MASK)
5282 break;
5283 _p[0] = ((unsigned short *) _q)[0];
5284 _p[1] = ((unsigned short *) _q)[1];
5285#if (SIZEOF_LONG == 8)
5286 _p[2] = ((unsigned short *) _q)[2];
5287 _p[3] = ((unsigned short *) _q)[3];
5288#endif
5289 _q += SIZEOF_LONG;
5290 _p += SIZEOF_LONG / 2;
5291 }
5292 }
5293 else {
5294 /* Byteswapped ordering is similar, but we must decompose
5295 the copy bytewise, and take care of zero'ing out the
5296 upper bytes if the target object is in 32-bit units
5297 (that is, in UCS-4 builds). */
5298 while (_q < aligned_end) {
5299 unsigned long data = * (unsigned long *) _q;
5300 if (data & SWAPPED_FAST_CHAR_MASK)
5301 break;
5302 /* Zero upper bytes in UCS-4 builds */
5303#if (Py_UNICODE_SIZE > 2)
5304 _p[0] = 0;
5305 _p[1] = 0;
5306#if (SIZEOF_LONG == 8)
5307 _p[2] = 0;
5308 _p[3] = 0;
5309#endif
5310#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005311 /* Issue #4916; UCS-4 builds on big endian machines must
5312 fill the two last bytes of each 4-byte unit. */
5313#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5314# define OFF 2
5315#else
5316# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005317#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005318 ((unsigned char *) _p)[OFF + 1] = _q[0];
5319 ((unsigned char *) _p)[OFF + 0] = _q[1];
5320 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5321 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5322#if (SIZEOF_LONG == 8)
5323 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5324 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5325 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5326 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5327#endif
5328#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005329 _q += SIZEOF_LONG;
5330 _p += SIZEOF_LONG / 2;
5331 }
5332 }
5333 p = _p;
5334 q = _q;
5335 if (q >= e)
5336 break;
5337 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005339
Benjamin Peterson14339b62009-01-31 16:36:08 +00005340 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005341
5342 if (ch < 0xD800 || ch > 0xDFFF) {
5343 *p++ = ch;
5344 continue;
5345 }
5346
5347 /* UTF-16 code pair: */
5348 if (q > e) {
5349 errmsg = "unexpected end of data";
5350 startinpos = (((const char *)q) - 2) - starts;
5351 endinpos = ((const char *)e) + 1 - starts;
5352 goto utf16Error;
5353 }
5354 if (0xD800 <= ch && ch <= 0xDBFF) {
5355 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5356 q += 2;
5357 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005358#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005359 *p++ = ch;
5360 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005361#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005362 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005363#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 continue;
5365 }
5366 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005367 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005368 startinpos = (((const char *)q)-4)-starts;
5369 endinpos = startinpos+2;
5370 goto utf16Error;
5371 }
5372
Benjamin Peterson14339b62009-01-31 16:36:08 +00005373 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005374 errmsg = "illegal encoding";
5375 startinpos = (((const char *)q)-2)-starts;
5376 endinpos = startinpos+2;
5377 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005378
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 utf16Error:
5380 outpos = p - PyUnicode_AS_UNICODE(unicode);
5381 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005382 errors,
5383 &errorHandler,
5384 "utf16", errmsg,
5385 &starts,
5386 (const char **)&e,
5387 &startinpos,
5388 &endinpos,
5389 &exc,
5390 (const char **)&q,
5391 &unicode,
5392 &outpos,
5393 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005394 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005395 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005396 /* remaining byte at the end? (size should be even) */
5397 if (e == q) {
5398 if (!consumed) {
5399 errmsg = "truncated data";
5400 startinpos = ((const char *)q) - starts;
5401 endinpos = ((const char *)e) + 1 - starts;
5402 outpos = p - PyUnicode_AS_UNICODE(unicode);
5403 if (unicode_decode_call_errorhandler(
5404 errors,
5405 &errorHandler,
5406 "utf16", errmsg,
5407 &starts,
5408 (const char **)&e,
5409 &startinpos,
5410 &endinpos,
5411 &exc,
5412 (const char **)&q,
5413 &unicode,
5414 &outpos,
5415 &p))
5416 goto onError;
5417 /* The remaining input chars are ignored if the callback
5418 chooses to skip the input */
5419 }
5420 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421
5422 if (byteorder)
5423 *byteorder = bo;
5424
Walter Dörwald69652032004-09-07 20:24:22 +00005425 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005426 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005427
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005429 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005430 goto onError;
5431
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005432 Py_XDECREF(errorHandler);
5433 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005434#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005435 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005436 Py_DECREF(unicode);
5437 return NULL;
5438 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005439#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005440 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441 return (PyObject *)unicode;
5442
Benjamin Peterson29060642009-01-31 22:14:21 +00005443 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005444 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005445 Py_XDECREF(errorHandler);
5446 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005447 return NULL;
5448}
5449
Antoine Pitrouab868312009-01-10 15:40:25 +00005450#undef FAST_CHAR_MASK
5451#undef SWAPPED_FAST_CHAR_MASK
5452
Tim Peters772747b2001-08-09 22:21:55 +00005453PyObject *
5454PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005455 Py_ssize_t size,
5456 const char *errors,
5457 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005458{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005459 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005460 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005461 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005462#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005463 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005464#else
5465 const int pairs = 0;
5466#endif
Tim Peters772747b2001-08-09 22:21:55 +00005467 /* Offsets from p for storing byte pairs in the right order. */
5468#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5469 int ihi = 1, ilo = 0;
5470#else
5471 int ihi = 0, ilo = 1;
5472#endif
5473
Benjamin Peterson29060642009-01-31 22:14:21 +00005474#define STORECHAR(CH) \
5475 do { \
5476 p[ihi] = ((CH) >> 8) & 0xff; \
5477 p[ilo] = (CH) & 0xff; \
5478 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005479 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005481#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005482 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 if (s[i] >= 0x10000)
5484 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005485#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005486 /* 2 * (size + pairs + (byteorder == 0)) */
5487 if (size > PY_SSIZE_T_MAX ||
5488 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005490 nsize = size + pairs + (byteorder == 0);
5491 bytesize = nsize * 2;
5492 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005493 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005494 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005495 if (v == NULL)
5496 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005497
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005498 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005499 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005500 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005501 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005502 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005503
5504 if (byteorder == -1) {
5505 /* force LE */
5506 ihi = 1;
5507 ilo = 0;
5508 }
5509 else if (byteorder == 1) {
5510 /* force BE */
5511 ihi = 0;
5512 ilo = 1;
5513 }
5514
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005515 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005516 Py_UNICODE ch = *s++;
5517 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005518#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005519 if (ch >= 0x10000) {
5520 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5521 ch = 0xD800 | ((ch-0x10000) >> 10);
5522 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005523#endif
Tim Peters772747b2001-08-09 22:21:55 +00005524 STORECHAR(ch);
5525 if (ch2)
5526 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005527 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005528
5529 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005530 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005531#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005532}
5533
Alexander Belopolsky40018472011-02-26 01:02:56 +00005534PyObject *
5535PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005536{
5537 if (!PyUnicode_Check(unicode)) {
5538 PyErr_BadArgument();
5539 return NULL;
5540 }
5541 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005542 PyUnicode_GET_SIZE(unicode),
5543 NULL,
5544 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005545}
5546
5547/* --- Unicode Escape Codec ----------------------------------------------- */
5548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005549/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5550 if all the escapes in the string make it still a valid ASCII string.
5551 Returns -1 if any escapes were found which cause the string to
5552 pop out of ASCII range. Otherwise returns the length of the
5553 required buffer to hold the string.
5554 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005555static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005556length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5557{
5558 const unsigned char *p = (const unsigned char *)s;
5559 const unsigned char *end = p + size;
5560 Py_ssize_t length = 0;
5561
5562 if (size < 0)
5563 return -1;
5564
5565 for (; p < end; ++p) {
5566 if (*p > 127) {
5567 /* Non-ASCII */
5568 return -1;
5569 }
5570 else if (*p != '\\') {
5571 /* Normal character */
5572 ++length;
5573 }
5574 else {
5575 /* Backslash-escape, check next char */
5576 ++p;
5577 /* Escape sequence reaches till end of string or
5578 non-ASCII follow-up. */
5579 if (p >= end || *p > 127)
5580 return -1;
5581 switch (*p) {
5582 case '\n':
5583 /* backslash + \n result in zero characters */
5584 break;
5585 case '\\': case '\'': case '\"':
5586 case 'b': case 'f': case 't':
5587 case 'n': case 'r': case 'v': case 'a':
5588 ++length;
5589 break;
5590 case '0': case '1': case '2': case '3':
5591 case '4': case '5': case '6': case '7':
5592 case 'x': case 'u': case 'U': case 'N':
5593 /* these do not guarantee ASCII characters */
5594 return -1;
5595 default:
5596 /* count the backslash + the other character */
5597 length += 2;
5598 }
5599 }
5600 }
5601 return length;
5602}
5603
5604/* Similar to PyUnicode_WRITE but either write into wstr field
5605 or treat string as ASCII. */
5606#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5607 do { \
5608 if ((kind) != PyUnicode_WCHAR_KIND) \
5609 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5610 else \
5611 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5612 } while (0)
5613
5614#define WRITE_WSTR(buf, index, value) \
5615 assert(kind == PyUnicode_WCHAR_KIND), \
5616 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5617
5618
Fredrik Lundh06d12682001-01-24 07:59:11 +00005619static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005620
Alexander Belopolsky40018472011-02-26 01:02:56 +00005621PyObject *
5622PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005623 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005624 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005625{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005626 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005627 Py_ssize_t startinpos;
5628 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005629 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005630 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005631 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005632 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005633 char* message;
5634 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005635 PyObject *errorHandler = NULL;
5636 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005637 Py_ssize_t ascii_length;
5638 Py_ssize_t i;
5639 int kind;
5640 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005642 ascii_length = length_of_escaped_ascii_string(s, size);
5643
5644 /* After length_of_escaped_ascii_string() there are two alternatives,
5645 either the string is pure ASCII with named escapes like \n, etc.
5646 and we determined it's exact size (common case)
5647 or it contains \x, \u, ... escape sequences. then we create a
5648 legacy wchar string and resize it at the end of this function. */
5649 if (ascii_length >= 0) {
5650 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5651 if (!v)
5652 goto onError;
5653 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5654 kind = PyUnicode_1BYTE_KIND;
5655 data = PyUnicode_DATA(v);
5656 }
5657 else {
5658 /* Escaped strings will always be longer than the resulting
5659 Unicode string, so we start with size here and then reduce the
5660 length after conversion to the true value.
5661 (but if the error callback returns a long replacement string
5662 we'll have to allocate more space) */
5663 v = _PyUnicode_New(size);
5664 if (!v)
5665 goto onError;
5666 kind = PyUnicode_WCHAR_KIND;
5667 data = PyUnicode_AS_UNICODE(v);
5668 }
5669
Guido van Rossumd57fd912000-03-10 22:53:23 +00005670 if (size == 0)
5671 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005672 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005674
Guido van Rossumd57fd912000-03-10 22:53:23 +00005675 while (s < end) {
5676 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005677 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005678 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680 if (kind == PyUnicode_WCHAR_KIND) {
5681 assert(i < _PyUnicode_WSTR_LENGTH(v));
5682 }
5683 else {
5684 /* The only case in which i == ascii_length is a backslash
5685 followed by a newline. */
5686 assert(i <= ascii_length);
5687 }
5688
Guido van Rossumd57fd912000-03-10 22:53:23 +00005689 /* Non-escape characters are interpreted as Unicode ordinals */
5690 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005691 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692 continue;
5693 }
5694
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005695 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005696 /* \ - Escapes */
5697 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005698 c = *s++;
5699 if (s > end)
5700 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005701
5702 if (kind == PyUnicode_WCHAR_KIND) {
5703 assert(i < _PyUnicode_WSTR_LENGTH(v));
5704 }
5705 else {
5706 /* The only case in which i == ascii_length is a backslash
5707 followed by a newline. */
5708 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5709 }
5710
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005711 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005712
Benjamin Peterson29060642009-01-31 22:14:21 +00005713 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005714 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005715 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5716 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5717 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5718 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5719 /* FF */
5720 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5721 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5722 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5723 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5724 /* VT */
5725 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5726 /* BEL, not classic C */
5727 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728
Benjamin Peterson29060642009-01-31 22:14:21 +00005729 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 case '0': case '1': case '2': case '3':
5731 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005732 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005733 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005734 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005735 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005736 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005738 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739 break;
5740
Benjamin Peterson29060642009-01-31 22:14:21 +00005741 /* hex escapes */
5742 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005743 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005744 digits = 2;
5745 message = "truncated \\xXX escape";
5746 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005749 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005750 digits = 4;
5751 message = "truncated \\uXXXX escape";
5752 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005753
Benjamin Peterson29060642009-01-31 22:14:21 +00005754 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005755 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005756 digits = 8;
5757 message = "truncated \\UXXXXXXXX escape";
5758 hexescape:
5759 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005760 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005761 if (s+digits>end) {
5762 endinpos = size;
5763 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005764 errors, &errorHandler,
5765 "unicodeescape", "end of string in escape sequence",
5766 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005767 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005768 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005770 goto nextByte;
5771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005772 for (j = 0; j < digits; ++j) {
5773 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005774 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005775 endinpos = (s+j+1)-starts;
5776 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005777 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005778 errors, &errorHandler,
5779 "unicodeescape", message,
5780 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005781 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005782 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005783 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005784 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005785 }
5786 chr = (chr<<4) & ~0xF;
5787 if (c >= '0' && c <= '9')
5788 chr += c - '0';
5789 else if (c >= 'a' && c <= 'f')
5790 chr += 10 + c - 'a';
5791 else
5792 chr += 10 + c - 'A';
5793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005794 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005795 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005796 /* _decoding_error will have already written into the
5797 target buffer. */
5798 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005800 /* when we get here, chr is a 32-bit unicode character */
5801 if (chr <= 0xffff)
5802 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005803 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005804 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005805 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005806 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005807#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005808 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005809#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005810 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5812 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005813#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005814 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005815 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005816 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005817 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005818 errors, &errorHandler,
5819 "unicodeescape", "illegal Unicode character",
5820 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005822 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005823 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005824 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005825 break;
5826
Benjamin Peterson29060642009-01-31 22:14:21 +00005827 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005828 case 'N':
5829 message = "malformed \\N character escape";
5830 if (ucnhash_CAPI == NULL) {
5831 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005832 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5833 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005834 if (ucnhash_CAPI == NULL)
5835 goto ucnhashError;
5836 }
5837 if (*s == '{') {
5838 const char *start = s+1;
5839 /* look for the closing brace */
5840 while (*s != '}' && s < end)
5841 s++;
5842 if (s > start && s < end && *s == '}') {
5843 /* found a name. look it up in the unicode database */
5844 message = "unknown Unicode character name";
5845 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005847 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005848 goto store;
5849 }
5850 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005851 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005853 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005854 errors, &errorHandler,
5855 "unicodeescape", message,
5856 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005858 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005859 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005860 break;
5861
5862 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005863 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005864 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005865 message = "\\ at end of string";
5866 s--;
5867 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005868 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005869 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005870 errors, &errorHandler,
5871 "unicodeescape", message,
5872 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005873 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005876 }
5877 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005878 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5879 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005880 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005881 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005882 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005883 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005884 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005886 /* Ensure the length prediction worked in case of ASCII strings */
5887 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5888
Victor Stinnerfe226c02011-10-03 03:52:20 +02005889 if (kind == PyUnicode_WCHAR_KIND)
5890 {
5891 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5892 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005893 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005894 Py_XDECREF(errorHandler);
5895 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005896#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005897 if (_PyUnicode_READY_REPLACE(&v)) {
5898 Py_DECREF(v);
5899 return NULL;
5900 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005901#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005902 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005903 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005904
Benjamin Peterson29060642009-01-31 22:14:21 +00005905 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005906 PyErr_SetString(
5907 PyExc_UnicodeError,
5908 "\\N escapes not supported (can't load unicodedata module)"
5909 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005910 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 Py_XDECREF(errorHandler);
5912 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005913 return NULL;
5914
Benjamin Peterson29060642009-01-31 22:14:21 +00005915 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005917 Py_XDECREF(errorHandler);
5918 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919 return NULL;
5920}
5921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005922#undef WRITE_ASCII_OR_WSTR
5923#undef WRITE_WSTR
5924
Guido van Rossumd57fd912000-03-10 22:53:23 +00005925/* Return a Unicode-Escape string version of the Unicode object.
5926
5927 If quotes is true, the string is enclosed in u"" or u'' quotes as
5928 appropriate.
5929
5930*/
5931
Alexander Belopolsky40018472011-02-26 01:02:56 +00005932PyObject *
5933PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005934 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005935{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005936 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005938
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005939#ifdef Py_UNICODE_WIDE
5940 const Py_ssize_t expandsize = 10;
5941#else
5942 const Py_ssize_t expandsize = 6;
5943#endif
5944
Thomas Wouters89f507f2006-12-13 04:49:30 +00005945 /* XXX(nnorwitz): rather than over-allocating, it would be
5946 better to choose a different scheme. Perhaps scan the
5947 first N-chars of the string and allocate based on that size.
5948 */
5949 /* Initial allocation is based on the longest-possible unichr
5950 escape.
5951
5952 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5953 unichr, so in this case it's the longest unichr escape. In
5954 narrow (UTF-16) builds this is five chars per source unichr
5955 since there are two unichrs in the surrogate pair, so in narrow
5956 (UTF-16) builds it's not the longest unichr escape.
5957
5958 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5959 so in the narrow (UTF-16) build case it's the longest unichr
5960 escape.
5961 */
5962
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005963 if (size == 0)
5964 return PyBytes_FromStringAndSize(NULL, 0);
5965
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005966 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005967 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005968
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005969 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005970 2
5971 + expandsize*size
5972 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 if (repr == NULL)
5974 return NULL;
5975
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005976 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 while (size-- > 0) {
5979 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005980
Walter Dörwald79e913e2007-05-12 11:08:06 +00005981 /* Escape backslashes */
5982 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005983 *p++ = '\\';
5984 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005985 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005986 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005987
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005988#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005989 /* Map 21-bit characters to '\U00xxxxxx' */
5990 else if (ch >= 0x10000) {
5991 *p++ = '\\';
5992 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005993 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5994 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5995 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5996 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5997 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5998 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5999 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
6000 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006001 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00006002 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006003#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006004 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6005 else if (ch >= 0xD800 && ch < 0xDC00) {
6006 Py_UNICODE ch2;
6007 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00006008
Benjamin Peterson29060642009-01-31 22:14:21 +00006009 ch2 = *s++;
6010 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006011 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6013 *p++ = '\\';
6014 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006015 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
6016 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
6017 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
6018 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
6019 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
6020 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
6021 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
6022 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006023 continue;
6024 }
6025 /* Fall through: isolated surrogates are copied as-is */
6026 s--;
6027 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006028 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006029#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006030
Guido van Rossumd57fd912000-03-10 22:53:23 +00006031 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006032 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 *p++ = '\\';
6034 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006035 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6036 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6037 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6038 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006039 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006040
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006041 /* Map special whitespace to '\t', \n', '\r' */
6042 else if (ch == '\t') {
6043 *p++ = '\\';
6044 *p++ = 't';
6045 }
6046 else if (ch == '\n') {
6047 *p++ = '\\';
6048 *p++ = 'n';
6049 }
6050 else if (ch == '\r') {
6051 *p++ = '\\';
6052 *p++ = 'r';
6053 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006054
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006055 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006056 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006058 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006059 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6060 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006061 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006062
Guido van Rossumd57fd912000-03-10 22:53:23 +00006063 /* Copy everything else as-is */
6064 else
6065 *p++ = (char) ch;
6066 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006068 assert(p - PyBytes_AS_STRING(repr) > 0);
6069 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6070 return NULL;
6071 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072}
6073
Alexander Belopolsky40018472011-02-26 01:02:56 +00006074PyObject *
6075PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006076{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006077 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006078 if (!PyUnicode_Check(unicode)) {
6079 PyErr_BadArgument();
6080 return NULL;
6081 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006082 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6083 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006084 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006085}
6086
6087/* --- Raw Unicode Escape Codec ------------------------------------------- */
6088
Alexander Belopolsky40018472011-02-26 01:02:56 +00006089PyObject *
6090PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006091 Py_ssize_t size,
6092 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006093{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006094 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006095 Py_ssize_t startinpos;
6096 Py_ssize_t endinpos;
6097 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006098 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006099 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006100 const char *end;
6101 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006102 PyObject *errorHandler = NULL;
6103 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006104
Guido van Rossumd57fd912000-03-10 22:53:23 +00006105 /* Escaped strings will always be longer than the resulting
6106 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006107 length after conversion to the true value. (But decoding error
6108 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109 v = _PyUnicode_New(size);
6110 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006112 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006113 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006114 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115 end = s + size;
6116 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006117 unsigned char c;
6118 Py_UCS4 x;
6119 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006120 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006121
Benjamin Peterson29060642009-01-31 22:14:21 +00006122 /* Non-escape characters are interpreted as Unicode ordinals */
6123 if (*s != '\\') {
6124 *p++ = (unsigned char)*s++;
6125 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006126 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006127 startinpos = s-starts;
6128
6129 /* \u-escapes are only interpreted iff the number of leading
6130 backslashes if odd */
6131 bs = s;
6132 for (;s < end;) {
6133 if (*s != '\\')
6134 break;
6135 *p++ = (unsigned char)*s++;
6136 }
6137 if (((s - bs) & 1) == 0 ||
6138 s >= end ||
6139 (*s != 'u' && *s != 'U')) {
6140 continue;
6141 }
6142 p--;
6143 count = *s=='u' ? 4 : 8;
6144 s++;
6145
6146 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6147 outpos = p-PyUnicode_AS_UNICODE(v);
6148 for (x = 0, i = 0; i < count; ++i, ++s) {
6149 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006150 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006151 endinpos = s-starts;
6152 if (unicode_decode_call_errorhandler(
6153 errors, &errorHandler,
6154 "rawunicodeescape", "truncated \\uXXXX",
6155 &starts, &end, &startinpos, &endinpos, &exc, &s,
6156 &v, &outpos, &p))
6157 goto onError;
6158 goto nextByte;
6159 }
6160 x = (x<<4) & ~0xF;
6161 if (c >= '0' && c <= '9')
6162 x += c - '0';
6163 else if (c >= 'a' && c <= 'f')
6164 x += 10 + c - 'a';
6165 else
6166 x += 10 + c - 'A';
6167 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006168 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 /* UCS-2 character */
6170 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006171 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006172 /* UCS-4 character. Either store directly, or as
6173 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006174#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006175 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006176#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006177 x -= 0x10000L;
6178 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6179 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006180#endif
6181 } else {
6182 endinpos = s-starts;
6183 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006184 if (unicode_decode_call_errorhandler(
6185 errors, &errorHandler,
6186 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006187 &starts, &end, &startinpos, &endinpos, &exc, &s,
6188 &v, &outpos, &p))
6189 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006190 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 nextByte:
6192 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006194 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006196 Py_XDECREF(errorHandler);
6197 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006198#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006199 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006200 Py_DECREF(v);
6201 return NULL;
6202 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006203#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006204 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006205 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006206
Benjamin Peterson29060642009-01-31 22:14:21 +00006207 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006209 Py_XDECREF(errorHandler);
6210 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211 return NULL;
6212}
6213
Alexander Belopolsky40018472011-02-26 01:02:56 +00006214PyObject *
6215PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006216 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006218 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006219 char *p;
6220 char *q;
6221
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006222#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006223 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006224#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006225 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006226#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006227
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006228 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006229 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006230
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006231 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 if (repr == NULL)
6233 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006234 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006235 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006236
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006237 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006238 while (size-- > 0) {
6239 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006240#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006241 /* Map 32-bit characters to '\Uxxxxxxxx' */
6242 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006243 *p++ = '\\';
6244 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006245 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6246 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6247 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6248 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6249 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6250 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6251 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6252 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006253 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006254 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006255#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006256 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6257 if (ch >= 0xD800 && ch < 0xDC00) {
6258 Py_UNICODE ch2;
6259 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006260
Benjamin Peterson29060642009-01-31 22:14:21 +00006261 ch2 = *s++;
6262 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006263 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6265 *p++ = '\\';
6266 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006267 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6268 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6269 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6270 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6271 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6272 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6273 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6274 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006275 continue;
6276 }
6277 /* Fall through: isolated surrogates are copied as-is */
6278 s--;
6279 size++;
6280 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006281#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006282 /* Map 16-bit characters to '\uxxxx' */
6283 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284 *p++ = '\\';
6285 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006286 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6287 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6288 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6289 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006290 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006291 /* Copy everything else as-is */
6292 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006293 *p++ = (char) ch;
6294 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006295 size = p - q;
6296
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006297 assert(size > 0);
6298 if (_PyBytes_Resize(&repr, size) < 0)
6299 return NULL;
6300 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301}
6302
Alexander Belopolsky40018472011-02-26 01:02:56 +00006303PyObject *
6304PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006306 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006307 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006308 PyErr_BadArgument();
6309 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006310 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006311 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6312 PyUnicode_GET_SIZE(unicode));
6313
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006314 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006315}
6316
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006317/* --- Unicode Internal Codec ------------------------------------------- */
6318
Alexander Belopolsky40018472011-02-26 01:02:56 +00006319PyObject *
6320_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006321 Py_ssize_t size,
6322 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006323{
6324 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006325 Py_ssize_t startinpos;
6326 Py_ssize_t endinpos;
6327 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006328 PyUnicodeObject *v;
6329 Py_UNICODE *p;
6330 const char *end;
6331 const char *reason;
6332 PyObject *errorHandler = NULL;
6333 PyObject *exc = NULL;
6334
Neal Norwitzd43069c2006-01-08 01:12:10 +00006335#ifdef Py_UNICODE_WIDE
6336 Py_UNICODE unimax = PyUnicode_GetMax();
6337#endif
6338
Thomas Wouters89f507f2006-12-13 04:49:30 +00006339 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006340 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6341 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006343 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6344 as string was created with the old API. */
6345 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006346 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006347 p = PyUnicode_AS_UNICODE(v);
6348 end = s + size;
6349
6350 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006351 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006352 /* We have to sanity check the raw data, otherwise doom looms for
6353 some malformed UCS-4 data. */
6354 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006355#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006356 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006357#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006358 end-s < Py_UNICODE_SIZE
6359 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006361 startinpos = s - starts;
6362 if (end-s < Py_UNICODE_SIZE) {
6363 endinpos = end-starts;
6364 reason = "truncated input";
6365 }
6366 else {
6367 endinpos = s - starts + Py_UNICODE_SIZE;
6368 reason = "illegal code point (> 0x10FFFF)";
6369 }
6370 outpos = p - PyUnicode_AS_UNICODE(v);
6371 if (unicode_decode_call_errorhandler(
6372 errors, &errorHandler,
6373 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006374 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006375 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006376 goto onError;
6377 }
6378 }
6379 else {
6380 p++;
6381 s += Py_UNICODE_SIZE;
6382 }
6383 }
6384
Victor Stinnerfe226c02011-10-03 03:52:20 +02006385 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006386 goto onError;
6387 Py_XDECREF(errorHandler);
6388 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006389#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006390 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006391 Py_DECREF(v);
6392 return NULL;
6393 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006394#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006395 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006396 return (PyObject *)v;
6397
Benjamin Peterson29060642009-01-31 22:14:21 +00006398 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006399 Py_XDECREF(v);
6400 Py_XDECREF(errorHandler);
6401 Py_XDECREF(exc);
6402 return NULL;
6403}
6404
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405/* --- Latin-1 Codec ------------------------------------------------------ */
6406
Alexander Belopolsky40018472011-02-26 01:02:56 +00006407PyObject *
6408PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006409 Py_ssize_t size,
6410 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006411{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006412 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006413 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006414}
6415
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006416/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006417static void
6418make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006419 const char *encoding,
6420 const Py_UNICODE *unicode, Py_ssize_t size,
6421 Py_ssize_t startpos, Py_ssize_t endpos,
6422 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006423{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006424 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006425 *exceptionObject = PyUnicodeEncodeError_Create(
6426 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006427 }
6428 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006429 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6430 goto onError;
6431 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6432 goto onError;
6433 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6434 goto onError;
6435 return;
6436 onError:
6437 Py_DECREF(*exceptionObject);
6438 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006439 }
6440}
6441
Martin v. Löwis9e816682011-11-02 12:45:42 +01006442/* This is ultimately going t replace above function. */
6443static void
6444make_encode_exception_obj(PyObject **exceptionObject,
6445 const char *encoding,
6446 PyObject *unicode,
6447 Py_ssize_t startpos, Py_ssize_t endpos,
6448 const char *reason)
6449{
6450 if (*exceptionObject == NULL) {
6451 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006452 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006453 encoding, unicode, startpos, endpos, reason);
6454 }
6455 else {
6456 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6457 goto onError;
6458 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6459 goto onError;
6460 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6461 goto onError;
6462 return;
6463 onError:
6464 Py_DECREF(*exceptionObject);
6465 *exceptionObject = NULL;
6466 }
6467}
6468
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006470static void
6471raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006472 const char *encoding,
6473 const Py_UNICODE *unicode, Py_ssize_t size,
6474 Py_ssize_t startpos, Py_ssize_t endpos,
6475 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006476{
6477 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006478 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006479 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006480 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006481}
Martin v. Löwis9e816682011-11-02 12:45:42 +01006482/* This is ultimately going to replace above function. */
6483static void
6484raise_encode_exception_obj(PyObject **exceptionObject,
6485 const char *encoding,
6486 PyObject *unicode,
6487 Py_ssize_t startpos, Py_ssize_t endpos,
6488 const char *reason)
6489{
6490 make_encode_exception_obj(exceptionObject,
6491 encoding, unicode, startpos, endpos, reason);
6492 if (*exceptionObject != NULL)
6493 PyCodec_StrictErrors(*exceptionObject);
6494}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006495
6496/* error handling callback helper:
6497 build arguments, call the callback and check the arguments,
6498 put the result into newpos and return the replacement string, which
6499 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006500static PyObject *
6501unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006502 PyObject **errorHandler,
6503 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006505 Py_ssize_t startpos, Py_ssize_t endpos,
6506 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006507{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006508 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006509 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006510 PyObject *restuple;
6511 PyObject *resunicode;
6512
6513 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006515 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006516 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006517 }
6518
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006519 if (PyUnicode_READY(unicode) < 0)
6520 return NULL;
6521 len = PyUnicode_GET_LENGTH(unicode);
6522
6523 make_encode_exception_obj(exceptionObject,
6524 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006525 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006527
6528 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006529 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006530 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006532 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006533 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 Py_DECREF(restuple);
6535 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006536 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006537 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006538 &resunicode, newpos)) {
6539 Py_DECREF(restuple);
6540 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006541 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006542 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6543 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6544 Py_DECREF(restuple);
6545 return NULL;
6546 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006547 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006548 *newpos = len + *newpos;
6549 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006550 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6551 Py_DECREF(restuple);
6552 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006553 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006554 Py_INCREF(resunicode);
6555 Py_DECREF(restuple);
6556 return resunicode;
6557}
6558
Alexander Belopolsky40018472011-02-26 01:02:56 +00006559static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006560unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006561 const char *errors,
6562 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006563{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 /* input state */
6565 Py_ssize_t pos=0, size;
6566 int kind;
6567 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006568 /* output object */
6569 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006570 /* pointer into the output */
6571 char *str;
6572 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006573 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006574 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6575 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576 PyObject *errorHandler = NULL;
6577 PyObject *exc = NULL;
6578 /* the following variable is used for caching string comparisons
6579 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6580 int known_errorHandler = -1;
6581
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006582 if (PyUnicode_READY(unicode) < 0)
6583 return NULL;
6584 size = PyUnicode_GET_LENGTH(unicode);
6585 kind = PyUnicode_KIND(unicode);
6586 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006587 /* allocate enough for a simple encoding without
6588 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006589 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006590 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006591 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006592 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006593 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006594 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006595 ressize = size;
6596
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006597 while (pos < size) {
6598 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006599
Benjamin Peterson29060642009-01-31 22:14:21 +00006600 /* can we encode this? */
6601 if (c<limit) {
6602 /* no overflow check, because we know that the space is enough */
6603 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006604 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006605 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006607 Py_ssize_t requiredsize;
6608 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006609 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006610 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006611 Py_ssize_t collstart = pos;
6612 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006615 ++collend;
6616 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6617 if (known_errorHandler==-1) {
6618 if ((errors==NULL) || (!strcmp(errors, "strict")))
6619 known_errorHandler = 1;
6620 else if (!strcmp(errors, "replace"))
6621 known_errorHandler = 2;
6622 else if (!strcmp(errors, "ignore"))
6623 known_errorHandler = 3;
6624 else if (!strcmp(errors, "xmlcharrefreplace"))
6625 known_errorHandler = 4;
6626 else
6627 known_errorHandler = 0;
6628 }
6629 switch (known_errorHandler) {
6630 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006631 raise_encode_exception_obj(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006632 goto onError;
6633 case 2: /* replace */
6634 while (collstart++<collend)
6635 *str++ = '?'; /* fall through */
6636 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 break;
6639 case 4: /* xmlcharrefreplace */
6640 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006641 /* determine replacement size */
6642 for (i = collstart, repsize = 0; i < collend; ++i) {
6643 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6644 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006645 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006647 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006648 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006649 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006650 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006651 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006652#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006653 else
6654 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006655#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006656 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006657 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006658 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006659 repsize += 2+6+1;
6660 else
6661 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006662#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006663 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006664 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 if (requiredsize > ressize) {
6666 if (requiredsize<2*ressize)
6667 requiredsize = 2*ressize;
6668 if (_PyBytes_Resize(&res, requiredsize))
6669 goto onError;
6670 str = PyBytes_AS_STRING(res) + respos;
6671 ressize = requiredsize;
6672 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006673 /* generate replacement */
6674 for (i = collstart; i < collend; ++i) {
6675 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006676 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006677 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006678 break;
6679 default:
6680 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006681 encoding, reason, unicode, &exc,
6682 collstart, collend, &newpos);
6683 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6684 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006685 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006686 if (PyBytes_Check(repunicode)) {
6687 /* Directly copy bytes result to output. */
6688 repsize = PyBytes_Size(repunicode);
6689 if (repsize > 1) {
6690 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006691 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006692 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6693 Py_DECREF(repunicode);
6694 goto onError;
6695 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006696 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006697 ressize += repsize-1;
6698 }
6699 memcpy(str, PyBytes_AsString(repunicode), repsize);
6700 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006701 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006702 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006703 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006704 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006705 /* need more space? (at least enough for what we
6706 have+the replacement+the rest of the string, so
6707 we won't have to check space for encodable characters) */
6708 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006709 repsize = PyUnicode_GET_LENGTH(repunicode);
6710 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006711 if (requiredsize > ressize) {
6712 if (requiredsize<2*ressize)
6713 requiredsize = 2*ressize;
6714 if (_PyBytes_Resize(&res, requiredsize)) {
6715 Py_DECREF(repunicode);
6716 goto onError;
6717 }
6718 str = PyBytes_AS_STRING(res) + respos;
6719 ressize = requiredsize;
6720 }
6721 /* check if there is anything unencodable in the replacement
6722 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006723 for (i = 0; repsize-->0; ++i, ++str) {
6724 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006725 if (c >= limit) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006726 raise_encode_exception_obj(&exc, encoding, unicode,
6727 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 Py_DECREF(repunicode);
6729 goto onError;
6730 }
6731 *str = (char)c;
6732 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006733 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006734 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006735 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006736 }
6737 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006738 /* Resize if we allocated to much */
6739 size = str - PyBytes_AS_STRING(res);
6740 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006741 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006742 if (_PyBytes_Resize(&res, size) < 0)
6743 goto onError;
6744 }
6745
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006746 Py_XDECREF(errorHandler);
6747 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006748 return res;
6749
6750 onError:
6751 Py_XDECREF(res);
6752 Py_XDECREF(errorHandler);
6753 Py_XDECREF(exc);
6754 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006755}
6756
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006757/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006758PyObject *
6759PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006760 Py_ssize_t size,
6761 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006762{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006763 PyObject *result;
6764 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6765 if (unicode == NULL)
6766 return NULL;
6767 result = unicode_encode_ucs1(unicode, errors, 256);
6768 Py_DECREF(unicode);
6769 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006770}
6771
Alexander Belopolsky40018472011-02-26 01:02:56 +00006772PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006773_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006774{
6775 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006776 PyErr_BadArgument();
6777 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006778 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006779 if (PyUnicode_READY(unicode) == -1)
6780 return NULL;
6781 /* Fast path: if it is a one-byte string, construct
6782 bytes object directly. */
6783 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6784 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6785 PyUnicode_GET_LENGTH(unicode));
6786 /* Non-Latin-1 characters present. Defer to above function to
6787 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006788 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006789}
6790
6791PyObject*
6792PyUnicode_AsLatin1String(PyObject *unicode)
6793{
6794 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006795}
6796
6797/* --- 7-bit ASCII Codec -------------------------------------------------- */
6798
Alexander Belopolsky40018472011-02-26 01:02:56 +00006799PyObject *
6800PyUnicode_DecodeASCII(const char *s,
6801 Py_ssize_t size,
6802 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006803{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006804 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006805 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006806 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006807 Py_ssize_t startinpos;
6808 Py_ssize_t endinpos;
6809 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006810 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006811 int has_error;
6812 const unsigned char *p = (const unsigned char *)s;
6813 const unsigned char *end = p + size;
6814 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006815 PyObject *errorHandler = NULL;
6816 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006817
Guido van Rossumd57fd912000-03-10 22:53:23 +00006818 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006819 if (size == 1 && (unsigned char)s[0] < 128)
6820 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006821
Victor Stinner702c7342011-10-05 13:50:52 +02006822 has_error = 0;
6823 while (p < end && !has_error) {
6824 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6825 an explanation. */
6826 if (!((size_t) p & LONG_PTR_MASK)) {
6827 /* Help register allocation */
6828 register const unsigned char *_p = p;
6829 while (_p < aligned_end) {
6830 unsigned long value = *(unsigned long *) _p;
6831 if (value & ASCII_CHAR_MASK) {
6832 has_error = 1;
6833 break;
6834 }
6835 _p += SIZEOF_LONG;
6836 }
6837 if (_p == end)
6838 break;
6839 if (has_error)
6840 break;
6841 p = _p;
6842 }
6843 if (*p & 0x80) {
6844 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006845 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006846 }
6847 else {
6848 ++p;
6849 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006850 }
Victor Stinner702c7342011-10-05 13:50:52 +02006851 if (!has_error)
6852 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006853
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854 v = _PyUnicode_New(size);
6855 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006857 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006858 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006859 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006860 e = s + size;
6861 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006862 register unsigned char c = (unsigned char)*s;
6863 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006864 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 ++s;
6866 }
6867 else {
6868 startinpos = s-starts;
6869 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006870 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 if (unicode_decode_call_errorhandler(
6872 errors, &errorHandler,
6873 "ascii", "ordinal not in range(128)",
6874 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006875 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006876 goto onError;
6877 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006878 }
Victor Stinner702c7342011-10-05 13:50:52 +02006879 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6880 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006882 Py_XDECREF(errorHandler);
6883 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006884#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006885 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006886 Py_DECREF(v);
6887 return NULL;
6888 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006889#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006890 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006891 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006892
Benjamin Peterson29060642009-01-31 22:14:21 +00006893 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006895 Py_XDECREF(errorHandler);
6896 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006897 return NULL;
6898}
6899
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006900/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006901PyObject *
6902PyUnicode_EncodeASCII(const Py_UNICODE *p,
6903 Py_ssize_t size,
6904 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006905{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006906 PyObject *result;
6907 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6908 if (unicode == NULL)
6909 return NULL;
6910 result = unicode_encode_ucs1(unicode, errors, 128);
6911 Py_DECREF(unicode);
6912 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006913}
6914
Alexander Belopolsky40018472011-02-26 01:02:56 +00006915PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006916_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006917{
6918 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006919 PyErr_BadArgument();
6920 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006921 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006922 if (PyUnicode_READY(unicode) == -1)
6923 return NULL;
6924 /* Fast path: if it is an ASCII-only string, construct bytes object
6925 directly. Else defer to above function to raise the exception. */
6926 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6927 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6928 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006929 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006930}
6931
6932PyObject *
6933PyUnicode_AsASCIIString(PyObject *unicode)
6934{
6935 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006936}
6937
Victor Stinner99b95382011-07-04 14:23:54 +02006938#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006939
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006940/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006941
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006942#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006943#define NEED_RETRY
6944#endif
6945
Victor Stinner3a50e702011-10-18 21:21:00 +02006946#ifndef WC_ERR_INVALID_CHARS
6947# define WC_ERR_INVALID_CHARS 0x0080
6948#endif
6949
6950static char*
6951code_page_name(UINT code_page, PyObject **obj)
6952{
6953 *obj = NULL;
6954 if (code_page == CP_ACP)
6955 return "mbcs";
6956 if (code_page == CP_UTF7)
6957 return "CP_UTF7";
6958 if (code_page == CP_UTF8)
6959 return "CP_UTF8";
6960
6961 *obj = PyBytes_FromFormat("cp%u", code_page);
6962 if (*obj == NULL)
6963 return NULL;
6964 return PyBytes_AS_STRING(*obj);
6965}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006966
Alexander Belopolsky40018472011-02-26 01:02:56 +00006967static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006968is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006969{
6970 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006972
Victor Stinner3a50e702011-10-18 21:21:00 +02006973 if (!IsDBCSLeadByteEx(code_page, *curr))
6974 return 0;
6975
6976 prev = CharPrevExA(code_page, s, curr, 0);
6977 if (prev == curr)
6978 return 1;
6979 /* FIXME: This code is limited to "true" double-byte encodings,
6980 as it assumes an incomplete character consists of a single
6981 byte. */
6982 if (curr - prev == 2)
6983 return 1;
6984 if (!IsDBCSLeadByteEx(code_page, *prev))
6985 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006986 return 0;
6987}
6988
Victor Stinner3a50e702011-10-18 21:21:00 +02006989static DWORD
6990decode_code_page_flags(UINT code_page)
6991{
6992 if (code_page == CP_UTF7) {
6993 /* The CP_UTF7 decoder only supports flags=0 */
6994 return 0;
6995 }
6996 else
6997 return MB_ERR_INVALID_CHARS;
6998}
6999
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007000/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007001 * Decode a byte string from a Windows code page into unicode object in strict
7002 * mode.
7003 *
7004 * Returns consumed size if succeed, returns -2 on decode error, or raise a
7005 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007006 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007007static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007008decode_code_page_strict(UINT code_page,
7009 PyUnicodeObject **v,
7010 const char *in,
7011 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007012{
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 const DWORD flags = decode_code_page_flags(code_page);
7014 Py_UNICODE *out;
7015 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007016
7017 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007018 assert(insize > 0);
7019 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7020 if (outsize <= 0)
7021 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007022
7023 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007024 /* Create unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007025 *v = _PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007026 if (*v == NULL)
7027 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007029 }
7030 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007031 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7033 if (PyUnicode_Resize((PyObject**)v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007034 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007035 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007036 }
7037
7038 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007039 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7040 if (outsize <= 0)
7041 goto error;
7042 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007043
Victor Stinner3a50e702011-10-18 21:21:00 +02007044error:
7045 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7046 return -2;
7047 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007048 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049}
7050
Victor Stinner3a50e702011-10-18 21:21:00 +02007051/*
7052 * Decode a byte string from a code page into unicode object with an error
7053 * handler.
7054 *
7055 * Returns consumed size if succeed, or raise a WindowsError or
7056 * UnicodeDecodeError exception and returns -1 on error.
7057 */
7058static int
7059decode_code_page_errors(UINT code_page,
7060 PyUnicodeObject **v,
7061 const char *in,
7062 int size,
7063 const char *errors)
7064{
7065 const char *startin = in;
7066 const char *endin = in + size;
7067 const DWORD flags = decode_code_page_flags(code_page);
7068 /* Ideally, we should get reason from FormatMessage. This is the Windows
7069 2000 English version of the message. */
7070 const char *reason = "No mapping for the Unicode character exists "
7071 "in the target code page.";
7072 /* each step cannot decode more than 1 character, but a character can be
7073 represented as a surrogate pair */
7074 wchar_t buffer[2], *startout, *out;
7075 int insize, outsize;
7076 PyObject *errorHandler = NULL;
7077 PyObject *exc = NULL;
7078 PyObject *encoding_obj = NULL;
7079 char *encoding;
7080 DWORD err;
7081 int ret = -1;
7082
7083 assert(size > 0);
7084
7085 encoding = code_page_name(code_page, &encoding_obj);
7086 if (encoding == NULL)
7087 return -1;
7088
7089 if (errors == NULL || strcmp(errors, "strict") == 0) {
7090 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7091 UnicodeDecodeError. */
7092 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7093 if (exc != NULL) {
7094 PyCodec_StrictErrors(exc);
7095 Py_CLEAR(exc);
7096 }
7097 goto error;
7098 }
7099
7100 if (*v == NULL) {
7101 /* Create unicode object */
7102 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7103 PyErr_NoMemory();
7104 goto error;
7105 }
7106 *v = _PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
7107 if (*v == NULL)
7108 goto error;
7109 startout = PyUnicode_AS_UNICODE(*v);
7110 }
7111 else {
7112 /* Extend unicode object */
7113 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7114 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7115 PyErr_NoMemory();
7116 goto error;
7117 }
7118 if (PyUnicode_Resize((PyObject**)v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
7119 goto error;
7120 startout = PyUnicode_AS_UNICODE(*v) + n;
7121 }
7122
7123 /* Decode the byte string character per character */
7124 out = startout;
7125 while (in < endin)
7126 {
7127 /* Decode a character */
7128 insize = 1;
7129 do
7130 {
7131 outsize = MultiByteToWideChar(code_page, flags,
7132 in, insize,
7133 buffer, Py_ARRAY_LENGTH(buffer));
7134 if (outsize > 0)
7135 break;
7136 err = GetLastError();
7137 if (err != ERROR_NO_UNICODE_TRANSLATION
7138 && err != ERROR_INSUFFICIENT_BUFFER)
7139 {
7140 PyErr_SetFromWindowsErr(0);
7141 goto error;
7142 }
7143 insize++;
7144 }
7145 /* 4=maximum length of a UTF-8 sequence */
7146 while (insize <= 4 && (in + insize) <= endin);
7147
7148 if (outsize <= 0) {
7149 Py_ssize_t startinpos, endinpos, outpos;
7150
7151 startinpos = in - startin;
7152 endinpos = startinpos + 1;
7153 outpos = out - PyUnicode_AS_UNICODE(*v);
7154 if (unicode_decode_call_errorhandler(
7155 errors, &errorHandler,
7156 encoding, reason,
7157 &startin, &endin, &startinpos, &endinpos, &exc, &in,
7158 v, &outpos, &out))
7159 {
7160 goto error;
7161 }
7162 }
7163 else {
7164 in += insize;
7165 memcpy(out, buffer, outsize * sizeof(wchar_t));
7166 out += outsize;
7167 }
7168 }
7169
7170 /* write a NUL character at the end */
7171 *out = 0;
7172
7173 /* Extend unicode object */
7174 outsize = out - startout;
7175 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
7176 if (PyUnicode_Resize((PyObject**)v, outsize) < 0)
7177 goto error;
7178 ret = 0;
7179
7180error:
7181 Py_XDECREF(encoding_obj);
7182 Py_XDECREF(errorHandler);
7183 Py_XDECREF(exc);
7184 return ret;
7185}
7186
7187/*
7188 * Decode a byte string from a Windows code page into unicode object. If
7189 * 'final' is set, converts trailing lead-byte too.
7190 *
7191 * Returns consumed size if succeed, or raise a WindowsError or
7192 * UnicodeDecodeError exception and returns -1 on error.
7193 */
7194static int
7195decode_code_page(UINT code_page,
7196 PyUnicodeObject **v,
7197 const char *s, int size,
7198 int final, const char *errors)
7199{
7200 int done;
7201
7202 /* Skip trailing lead-byte unless 'final' is set */
7203 if (size == 0) {
7204 if (*v == NULL) {
7205 Py_INCREF(unicode_empty);
7206 *v = (PyUnicodeObject*)unicode_empty;
7207 if (*v == NULL)
7208 return -1;
7209 }
7210 return 0;
7211 }
7212
7213 if (!final && is_dbcs_lead_byte(code_page, s, size - 1))
7214 --size;
7215
7216 done = decode_code_page_strict(code_page, v, s, size);
7217 if (done == -2)
7218 done = decode_code_page_errors(code_page, v, s, size, errors);
7219 return done;
7220}
7221
7222static PyObject *
7223decode_code_page_stateful(int code_page,
7224 const char *s,
7225 Py_ssize_t size,
7226 const char *errors,
7227 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007228{
7229 PyUnicodeObject *v = NULL;
7230 int done;
7231
Victor Stinner3a50e702011-10-18 21:21:00 +02007232 if (code_page < 0) {
7233 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7234 return NULL;
7235 }
7236
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007237 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007238 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007239
7240#ifdef NEED_RETRY
7241 retry:
7242 if (size > INT_MAX)
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 done = decode_code_page(code_page, &v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007244 else
7245#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 done = decode_code_page(code_page, &v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007247
7248 if (done < 0) {
7249 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00007250 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251 }
7252
7253 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007254 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007255
7256#ifdef NEED_RETRY
7257 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007258 s += done;
7259 size -= done;
7260 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007261 }
7262#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007263
Victor Stinner17efeed2011-10-04 20:05:46 +02007264#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007265 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007266 Py_DECREF(v);
7267 return NULL;
7268 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007269#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007270 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007271 return (PyObject *)v;
7272}
7273
Alexander Belopolsky40018472011-02-26 01:02:56 +00007274PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007275PyUnicode_DecodeCodePageStateful(int code_page,
7276 const char *s,
7277 Py_ssize_t size,
7278 const char *errors,
7279 Py_ssize_t *consumed)
7280{
7281 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7282}
7283
7284PyObject *
7285PyUnicode_DecodeMBCSStateful(const char *s,
7286 Py_ssize_t size,
7287 const char *errors,
7288 Py_ssize_t *consumed)
7289{
7290 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7291}
7292
7293PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007294PyUnicode_DecodeMBCS(const char *s,
7295 Py_ssize_t size,
7296 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007297{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007298 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7299}
7300
Victor Stinner3a50e702011-10-18 21:21:00 +02007301static DWORD
7302encode_code_page_flags(UINT code_page, const char *errors)
7303{
7304 if (code_page == CP_UTF8) {
7305 if (winver.dwMajorVersion >= 6)
7306 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7307 and later */
7308 return WC_ERR_INVALID_CHARS;
7309 else
7310 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7311 return 0;
7312 }
7313 else if (code_page == CP_UTF7) {
7314 /* CP_UTF7 only supports flags=0 */
7315 return 0;
7316 }
7317 else {
7318 if (errors != NULL && strcmp(errors, "replace") == 0)
7319 return 0;
7320 else
7321 return WC_NO_BEST_FIT_CHARS;
7322 }
7323}
7324
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007325/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 * Encode a Unicode string to a Windows code page into a byte string in strict
7327 * mode.
7328 *
7329 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7330 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007331 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007332static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007333encode_code_page_strict(UINT code_page, PyObject **outbytes,
7334 const Py_UNICODE *p, const int size,
7335 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007336{
Victor Stinner554f3f02010-06-16 23:33:54 +00007337 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007338 BOOL *pusedDefaultChar = &usedDefaultChar;
7339 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007340 PyObject *exc = NULL;
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 const DWORD flags = encode_code_page_flags(code_page, NULL);
7342 char *out;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007343
Victor Stinner3a50e702011-10-18 21:21:00 +02007344 assert(size > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007345
Victor Stinner3a50e702011-10-18 21:21:00 +02007346 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007347 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007348 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007349 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007350
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007351 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007352 outsize = WideCharToMultiByte(code_page, flags,
7353 p, size,
7354 NULL, 0,
7355 NULL, pusedDefaultChar);
7356 if (outsize <= 0)
7357 goto error;
7358 /* If we used a default char, then we failed! */
7359 if (pusedDefaultChar && *pusedDefaultChar)
7360 return -2;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007361
Victor Stinner3a50e702011-10-18 21:21:00 +02007362 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007363 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7365 if (*outbytes == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007366 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007367 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007368 }
7369 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007370 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007371 const Py_ssize_t n = PyBytes_Size(*outbytes);
7372 if (outsize > PY_SSIZE_T_MAX - n) {
7373 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007374 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 }
7376 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7377 return -1;
7378 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007379 }
7380
7381 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 outsize = WideCharToMultiByte(code_page, flags,
7383 p, size,
7384 out, outsize,
7385 NULL, pusedDefaultChar);
7386 if (outsize <= 0)
7387 goto error;
7388 if (pusedDefaultChar && *pusedDefaultChar)
7389 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007390 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007391
Victor Stinner3a50e702011-10-18 21:21:00 +02007392error:
7393 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7394 return -2;
7395 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007396 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007397}
7398
Victor Stinner3a50e702011-10-18 21:21:00 +02007399/*
7400 * Encode a Unicode string to a Windows code page into a byte string using a
7401 * error handler.
7402 *
7403 * Returns consumed characters if succeed, or raise a WindowsError and returns
7404 * -1 on other error.
7405 */
7406static int
7407encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007408 PyObject *unicode, Py_ssize_t unicode_offset,
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 const Py_UNICODE *in, const int insize,
7410 const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007411{
Victor Stinner3a50e702011-10-18 21:21:00 +02007412 const DWORD flags = encode_code_page_flags(code_page, errors);
7413 const Py_UNICODE *startin = in;
7414 const Py_UNICODE *endin = in + insize;
7415 /* Ideally, we should get reason from FormatMessage. This is the Windows
7416 2000 English version of the message. */
7417 const char *reason = "invalid character";
7418 /* 4=maximum length of a UTF-8 sequence */
7419 char buffer[4];
7420 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7421 Py_ssize_t outsize;
7422 char *out;
7423 int charsize;
7424 PyObject *errorHandler = NULL;
7425 PyObject *exc = NULL;
7426 PyObject *encoding_obj = NULL;
7427 char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 Py_ssize_t startpos, newpos, newoutsize;
7429 PyObject *rep;
7430 int ret = -1;
7431
7432 assert(insize > 0);
7433
7434 encoding = code_page_name(code_page, &encoding_obj);
7435 if (encoding == NULL)
7436 return -1;
7437
7438 if (errors == NULL || strcmp(errors, "strict") == 0) {
7439 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7440 then we raise a UnicodeEncodeError. */
7441 make_encode_exception(&exc, encoding, in, insize, 0, 0, reason);
7442 if (exc != NULL) {
7443 PyCodec_StrictErrors(exc);
7444 Py_DECREF(exc);
7445 }
7446 Py_XDECREF(encoding_obj);
7447 return -1;
7448 }
7449
7450 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7451 pusedDefaultChar = &usedDefaultChar;
7452 else
7453 pusedDefaultChar = NULL;
7454
7455 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7456 PyErr_NoMemory();
7457 goto error;
7458 }
7459 outsize = insize * Py_ARRAY_LENGTH(buffer);
7460
7461 if (*outbytes == NULL) {
7462 /* Create string object */
7463 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7464 if (*outbytes == NULL)
7465 goto error;
7466 out = PyBytes_AS_STRING(*outbytes);
7467 }
7468 else {
7469 /* Extend string object */
7470 Py_ssize_t n = PyBytes_Size(*outbytes);
7471 if (n > PY_SSIZE_T_MAX - outsize) {
7472 PyErr_NoMemory();
7473 goto error;
7474 }
7475 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7476 goto error;
7477 out = PyBytes_AS_STRING(*outbytes) + n;
7478 }
7479
7480 /* Encode the string character per character */
7481 while (in < endin)
7482 {
7483 if ((in + 2) <= endin
7484 && 0xD800 <= in[0] && in[0] <= 0xDBFF
7485 && 0xDC00 <= in[1] && in[1] <= 0xDFFF)
7486 charsize = 2;
7487 else
7488 charsize = 1;
7489
7490 outsize = WideCharToMultiByte(code_page, flags,
7491 in, charsize,
7492 buffer, Py_ARRAY_LENGTH(buffer),
7493 NULL, pusedDefaultChar);
7494 if (outsize > 0) {
7495 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7496 {
7497 in += charsize;
7498 memcpy(out, buffer, outsize);
7499 out += outsize;
7500 continue;
7501 }
7502 }
7503 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7504 PyErr_SetFromWindowsErr(0);
7505 goto error;
7506 }
7507
7508 charsize = Py_MAX(charsize - 1, 1);
Victor Stinner7581cef2011-11-03 22:32:33 +01007509 startpos = unicode_offset + in - startin;
Victor Stinner3a50e702011-10-18 21:21:00 +02007510 rep = unicode_encode_call_errorhandler(
7511 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007512 unicode, &exc,
Victor Stinner3a50e702011-10-18 21:21:00 +02007513 startpos, startpos + charsize, &newpos);
7514 if (rep == NULL)
7515 goto error;
Victor Stinner7581cef2011-11-03 22:32:33 +01007516 in += (newpos - startpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007517
7518 if (PyBytes_Check(rep)) {
7519 outsize = PyBytes_GET_SIZE(rep);
7520 if (outsize != 1) {
7521 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7522 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7523 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7524 Py_DECREF(rep);
7525 goto error;
7526 }
7527 out = PyBytes_AS_STRING(*outbytes) + offset;
7528 }
7529 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7530 out += outsize;
7531 }
7532 else {
7533 Py_ssize_t i;
7534 enum PyUnicode_Kind kind;
7535 void *data;
7536
7537 if (PyUnicode_READY(rep) < 0) {
7538 Py_DECREF(rep);
7539 goto error;
7540 }
7541
7542 outsize = PyUnicode_GET_LENGTH(rep);
7543 if (outsize != 1) {
7544 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7545 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7546 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7547 Py_DECREF(rep);
7548 goto error;
7549 }
7550 out = PyBytes_AS_STRING(*outbytes) + offset;
7551 }
7552 kind = PyUnicode_KIND(rep);
7553 data = PyUnicode_DATA(rep);
7554 for (i=0; i < outsize; i++) {
7555 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7556 if (ch > 127) {
7557 raise_encode_exception(&exc,
7558 encoding,
7559 startin, insize,
7560 startpos, startpos + charsize,
7561 "unable to encode error handler result to ASCII");
7562 Py_DECREF(rep);
7563 goto error;
7564 }
7565 *out = (unsigned char)ch;
7566 out++;
7567 }
7568 }
7569 Py_DECREF(rep);
7570 }
7571 /* write a NUL byte */
7572 *out = 0;
7573 outsize = out - PyBytes_AS_STRING(*outbytes);
7574 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7575 if (_PyBytes_Resize(outbytes, outsize) < 0)
7576 goto error;
7577 ret = 0;
7578
7579error:
7580 Py_XDECREF(encoding_obj);
7581 Py_XDECREF(errorHandler);
7582 Py_XDECREF(exc);
7583 return ret;
7584}
7585
7586/*
7587 * Encode a Unicode string to a Windows code page into a byte string.
7588 *
7589 * Returns consumed characters if succeed, or raise a WindowsError and returns
7590 * -1 on other error.
7591 */
7592static int
7593encode_code_page_chunk(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007594 PyObject *unicode, Py_ssize_t unicode_offset,
Victor Stinner3a50e702011-10-18 21:21:00 +02007595 const Py_UNICODE *p, int size,
7596 const char* errors)
7597{
7598 int done;
7599
7600 if (size == 0) {
7601 if (*outbytes == NULL) {
7602 *outbytes = PyBytes_FromStringAndSize(NULL, 0);
7603 if (*outbytes == NULL)
7604 return -1;
7605 }
7606 return 0;
7607 }
7608
Victor Stinner7581cef2011-11-03 22:32:33 +01007609 done = encode_code_page_strict(code_page, outbytes,
7610 p, size,
7611 errors);
Victor Stinner3a50e702011-10-18 21:21:00 +02007612 if (done == -2)
Victor Stinner7581cef2011-11-03 22:32:33 +01007613 done = encode_code_page_errors(code_page, outbytes,
7614 unicode, unicode_offset,
7615 p, size,
7616 errors);
Victor Stinner3a50e702011-10-18 21:21:00 +02007617 return done;
7618}
7619
7620static PyObject *
7621encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007622 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007623 const char *errors)
7624{
Victor Stinner7581cef2011-11-03 22:32:33 +01007625 const Py_UNICODE *p;
7626 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007627 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007628 Py_ssize_t offset;
7629 int chunk_len, ret;
7630
7631 p = PyUnicode_AsUnicodeAndSize(unicode, &size);
7632 if (p == NULL)
7633 return NULL;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007634
Victor Stinner3a50e702011-10-18 21:21:00 +02007635 if (code_page < 0) {
7636 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7637 return NULL;
7638 }
7639
Victor Stinner7581cef2011-11-03 22:32:33 +01007640 offset = 0;
7641 do
7642 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007643#ifdef NEED_RETRY
Victor Stinner7581cef2011-11-03 22:32:33 +01007644 if (size > INT_MAX)
7645 chunk_len = INT_MAX;
7646 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007647#endif
Victor Stinner7581cef2011-11-03 22:32:33 +01007648 chunk_len = (int)size;
7649 ret = encode_code_page_chunk(code_page, &outbytes,
7650 unicode, offset,
7651 p, chunk_len,
7652 errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007653
Victor Stinner7581cef2011-11-03 22:32:33 +01007654 if (ret < 0) {
7655 Py_XDECREF(outbytes);
7656 return NULL;
7657 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007658
Victor Stinner7581cef2011-11-03 22:32:33 +01007659 p += chunk_len;
7660 offset += chunk_len;
7661 size -= chunk_len;
7662 } while (size != 0);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007663
Victor Stinner3a50e702011-10-18 21:21:00 +02007664 return outbytes;
7665}
7666
7667PyObject *
7668PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7669 Py_ssize_t size,
7670 const char *errors)
7671{
Victor Stinner7581cef2011-11-03 22:32:33 +01007672 PyObject *unicode, *res;
7673 unicode = PyUnicode_FromUnicode(p, size);
7674 if (unicode == NULL)
7675 return NULL;
7676 res = encode_code_page(CP_ACP, unicode, errors);
7677 Py_DECREF(unicode);
7678 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007679}
7680
7681PyObject *
7682PyUnicode_EncodeCodePage(int code_page,
7683 PyObject *unicode,
7684 const char *errors)
7685{
Victor Stinner7581cef2011-11-03 22:32:33 +01007686 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007687}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007688
Alexander Belopolsky40018472011-02-26 01:02:56 +00007689PyObject *
7690PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007691{
7692 if (!PyUnicode_Check(unicode)) {
7693 PyErr_BadArgument();
7694 return NULL;
7695 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007696 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007697}
7698
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007699#undef NEED_RETRY
7700
Victor Stinner99b95382011-07-04 14:23:54 +02007701#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007702
Guido van Rossumd57fd912000-03-10 22:53:23 +00007703/* --- Character Mapping Codec -------------------------------------------- */
7704
Alexander Belopolsky40018472011-02-26 01:02:56 +00007705PyObject *
7706PyUnicode_DecodeCharmap(const char *s,
7707 Py_ssize_t size,
7708 PyObject *mapping,
7709 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007710{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007711 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007712 Py_ssize_t startinpos;
7713 Py_ssize_t endinpos;
7714 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007715 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007716 PyUnicodeObject *v;
7717 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007718 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007719 PyObject *errorHandler = NULL;
7720 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007721 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007722 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007723
Guido van Rossumd57fd912000-03-10 22:53:23 +00007724 /* Default to Latin-1 */
7725 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007726 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007727
7728 v = _PyUnicode_New(size);
7729 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007730 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007731 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007732 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007733 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007734 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007735 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007736 mapstring = PyUnicode_AS_UNICODE(mapping);
7737 maplen = PyUnicode_GET_SIZE(mapping);
7738 while (s < e) {
7739 unsigned char ch = *s;
7740 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007741
Benjamin Peterson29060642009-01-31 22:14:21 +00007742 if (ch < maplen)
7743 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007744
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 if (x == 0xfffe) {
7746 /* undefined mapping */
7747 outpos = p-PyUnicode_AS_UNICODE(v);
7748 startinpos = s-starts;
7749 endinpos = startinpos+1;
7750 if (unicode_decode_call_errorhandler(
7751 errors, &errorHandler,
7752 "charmap", "character maps to <undefined>",
7753 &starts, &e, &startinpos, &endinpos, &exc, &s,
7754 &v, &outpos, &p)) {
7755 goto onError;
7756 }
7757 continue;
7758 }
7759 *p++ = x;
7760 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007761 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007762 }
7763 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 while (s < e) {
7765 unsigned char ch = *s;
7766 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007767
Benjamin Peterson29060642009-01-31 22:14:21 +00007768 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7769 w = PyLong_FromLong((long)ch);
7770 if (w == NULL)
7771 goto onError;
7772 x = PyObject_GetItem(mapping, w);
7773 Py_DECREF(w);
7774 if (x == NULL) {
7775 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7776 /* No mapping found means: mapping is undefined. */
7777 PyErr_Clear();
7778 x = Py_None;
7779 Py_INCREF(x);
7780 } else
7781 goto onError;
7782 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007783
Benjamin Peterson29060642009-01-31 22:14:21 +00007784 /* Apply mapping */
7785 if (PyLong_Check(x)) {
7786 long value = PyLong_AS_LONG(x);
7787 if (value < 0 || value > 65535) {
7788 PyErr_SetString(PyExc_TypeError,
7789 "character mapping must be in range(65536)");
7790 Py_DECREF(x);
7791 goto onError;
7792 }
7793 *p++ = (Py_UNICODE)value;
7794 }
7795 else if (x == Py_None) {
7796 /* undefined mapping */
7797 outpos = p-PyUnicode_AS_UNICODE(v);
7798 startinpos = s-starts;
7799 endinpos = startinpos+1;
7800 if (unicode_decode_call_errorhandler(
7801 errors, &errorHandler,
7802 "charmap", "character maps to <undefined>",
7803 &starts, &e, &startinpos, &endinpos, &exc, &s,
7804 &v, &outpos, &p)) {
7805 Py_DECREF(x);
7806 goto onError;
7807 }
7808 Py_DECREF(x);
7809 continue;
7810 }
7811 else if (PyUnicode_Check(x)) {
7812 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007813
Benjamin Peterson29060642009-01-31 22:14:21 +00007814 if (targetsize == 1)
7815 /* 1-1 mapping */
7816 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007817
Benjamin Peterson29060642009-01-31 22:14:21 +00007818 else if (targetsize > 1) {
7819 /* 1-n mapping */
7820 if (targetsize > extrachars) {
7821 /* resize first */
7822 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7823 Py_ssize_t needed = (targetsize - extrachars) + \
7824 (targetsize << 2);
7825 extrachars += needed;
7826 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007827 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 PyUnicode_GET_SIZE(v) + needed) < 0) {
7829 Py_DECREF(x);
7830 goto onError;
7831 }
7832 p = PyUnicode_AS_UNICODE(v) + oldpos;
7833 }
7834 Py_UNICODE_COPY(p,
7835 PyUnicode_AS_UNICODE(x),
7836 targetsize);
7837 p += targetsize;
7838 extrachars -= targetsize;
7839 }
7840 /* 1-0 mapping: skip the character */
7841 }
7842 else {
7843 /* wrong return value */
7844 PyErr_SetString(PyExc_TypeError,
7845 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007846 Py_DECREF(x);
7847 goto onError;
7848 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007849 Py_DECREF(x);
7850 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007852 }
7853 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007854 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007855 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007856 Py_XDECREF(errorHandler);
7857 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007858#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007859 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007860 Py_DECREF(v);
7861 return NULL;
7862 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007863#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007864 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007865 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007866
Benjamin Peterson29060642009-01-31 22:14:21 +00007867 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007868 Py_XDECREF(errorHandler);
7869 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007870 Py_XDECREF(v);
7871 return NULL;
7872}
7873
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007874/* Charmap encoding: the lookup table */
7875
Alexander Belopolsky40018472011-02-26 01:02:56 +00007876struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 PyObject_HEAD
7878 unsigned char level1[32];
7879 int count2, count3;
7880 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007881};
7882
7883static PyObject*
7884encoding_map_size(PyObject *obj, PyObject* args)
7885{
7886 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007887 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007888 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007889}
7890
7891static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007892 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007893 PyDoc_STR("Return the size (in bytes) of this object") },
7894 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007895};
7896
7897static void
7898encoding_map_dealloc(PyObject* o)
7899{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007900 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007901}
7902
7903static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007904 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007905 "EncodingMap", /*tp_name*/
7906 sizeof(struct encoding_map), /*tp_basicsize*/
7907 0, /*tp_itemsize*/
7908 /* methods */
7909 encoding_map_dealloc, /*tp_dealloc*/
7910 0, /*tp_print*/
7911 0, /*tp_getattr*/
7912 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007913 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007914 0, /*tp_repr*/
7915 0, /*tp_as_number*/
7916 0, /*tp_as_sequence*/
7917 0, /*tp_as_mapping*/
7918 0, /*tp_hash*/
7919 0, /*tp_call*/
7920 0, /*tp_str*/
7921 0, /*tp_getattro*/
7922 0, /*tp_setattro*/
7923 0, /*tp_as_buffer*/
7924 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7925 0, /*tp_doc*/
7926 0, /*tp_traverse*/
7927 0, /*tp_clear*/
7928 0, /*tp_richcompare*/
7929 0, /*tp_weaklistoffset*/
7930 0, /*tp_iter*/
7931 0, /*tp_iternext*/
7932 encoding_map_methods, /*tp_methods*/
7933 0, /*tp_members*/
7934 0, /*tp_getset*/
7935 0, /*tp_base*/
7936 0, /*tp_dict*/
7937 0, /*tp_descr_get*/
7938 0, /*tp_descr_set*/
7939 0, /*tp_dictoffset*/
7940 0, /*tp_init*/
7941 0, /*tp_alloc*/
7942 0, /*tp_new*/
7943 0, /*tp_free*/
7944 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007945};
7946
7947PyObject*
7948PyUnicode_BuildEncodingMap(PyObject* string)
7949{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950 PyObject *result;
7951 struct encoding_map *mresult;
7952 int i;
7953 int need_dict = 0;
7954 unsigned char level1[32];
7955 unsigned char level2[512];
7956 unsigned char *mlevel1, *mlevel2, *mlevel3;
7957 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007958 int kind;
7959 void *data;
7960 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007962 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007963 PyErr_BadArgument();
7964 return NULL;
7965 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007966 kind = PyUnicode_KIND(string);
7967 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007968 memset(level1, 0xFF, sizeof level1);
7969 memset(level2, 0xFF, sizeof level2);
7970
7971 /* If there isn't a one-to-one mapping of NULL to \0,
7972 or if there are non-BMP characters, we need to use
7973 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007974 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007975 need_dict = 1;
7976 for (i = 1; i < 256; i++) {
7977 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007978 ch = PyUnicode_READ(kind, data, i);
7979 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007980 need_dict = 1;
7981 break;
7982 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007983 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007984 /* unmapped character */
7985 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007986 l1 = ch >> 11;
7987 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007988 if (level1[l1] == 0xFF)
7989 level1[l1] = count2++;
7990 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007991 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007992 }
7993
7994 if (count2 >= 0xFF || count3 >= 0xFF)
7995 need_dict = 1;
7996
7997 if (need_dict) {
7998 PyObject *result = PyDict_New();
7999 PyObject *key, *value;
8000 if (!result)
8001 return NULL;
8002 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008003 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00008004 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008005 if (!key || !value)
8006 goto failed1;
8007 if (PyDict_SetItem(result, key, value) == -1)
8008 goto failed1;
8009 Py_DECREF(key);
8010 Py_DECREF(value);
8011 }
8012 return result;
8013 failed1:
8014 Py_XDECREF(key);
8015 Py_XDECREF(value);
8016 Py_DECREF(result);
8017 return NULL;
8018 }
8019
8020 /* Create a three-level trie */
8021 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8022 16*count2 + 128*count3 - 1);
8023 if (!result)
8024 return PyErr_NoMemory();
8025 PyObject_Init(result, &EncodingMapType);
8026 mresult = (struct encoding_map*)result;
8027 mresult->count2 = count2;
8028 mresult->count3 = count3;
8029 mlevel1 = mresult->level1;
8030 mlevel2 = mresult->level23;
8031 mlevel3 = mresult->level23 + 16*count2;
8032 memcpy(mlevel1, level1, 32);
8033 memset(mlevel2, 0xFF, 16*count2);
8034 memset(mlevel3, 0, 128*count3);
8035 count3 = 0;
8036 for (i = 1; i < 256; i++) {
8037 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008038 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008039 /* unmapped character */
8040 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008041 o1 = PyUnicode_READ(kind, data, i)>>11;
8042 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008043 i2 = 16*mlevel1[o1] + o2;
8044 if (mlevel2[i2] == 0xFF)
8045 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008046 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008047 i3 = 128*mlevel2[i2] + o3;
8048 mlevel3[i3] = i;
8049 }
8050 return result;
8051}
8052
8053static int
8054encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
8055{
8056 struct encoding_map *map = (struct encoding_map*)mapping;
8057 int l1 = c>>11;
8058 int l2 = (c>>7) & 0xF;
8059 int l3 = c & 0x7F;
8060 int i;
8061
8062#ifdef Py_UNICODE_WIDE
8063 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008064 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008065 }
8066#endif
8067 if (c == 0)
8068 return 0;
8069 /* level 1*/
8070 i = map->level1[l1];
8071 if (i == 0xFF) {
8072 return -1;
8073 }
8074 /* level 2*/
8075 i = map->level23[16*i+l2];
8076 if (i == 0xFF) {
8077 return -1;
8078 }
8079 /* level 3 */
8080 i = map->level23[16*map->count2 + 128*i + l3];
8081 if (i == 0) {
8082 return -1;
8083 }
8084 return i;
8085}
8086
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008087/* Lookup the character ch in the mapping. If the character
8088 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008089 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008090static PyObject *
8091charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008092{
Christian Heimes217cfd12007-12-02 14:31:20 +00008093 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008094 PyObject *x;
8095
8096 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008097 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008098 x = PyObject_GetItem(mapping, w);
8099 Py_DECREF(w);
8100 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8102 /* No mapping found means: mapping is undefined. */
8103 PyErr_Clear();
8104 x = Py_None;
8105 Py_INCREF(x);
8106 return x;
8107 } else
8108 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008109 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008110 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008112 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008113 long value = PyLong_AS_LONG(x);
8114 if (value < 0 || value > 255) {
8115 PyErr_SetString(PyExc_TypeError,
8116 "character mapping must be in range(256)");
8117 Py_DECREF(x);
8118 return NULL;
8119 }
8120 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008121 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008122 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008123 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008124 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008125 /* wrong return value */
8126 PyErr_Format(PyExc_TypeError,
8127 "character mapping must return integer, bytes or None, not %.400s",
8128 x->ob_type->tp_name);
8129 Py_DECREF(x);
8130 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008131 }
8132}
8133
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008134static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008135charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8138 /* exponentially overallocate to minimize reallocations */
8139 if (requiredsize < 2*outsize)
8140 requiredsize = 2*outsize;
8141 if (_PyBytes_Resize(outobj, requiredsize))
8142 return -1;
8143 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008144}
8145
Benjamin Peterson14339b62009-01-31 16:36:08 +00008146typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008147 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008148} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008149/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008150 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008151 space is available. Return a new reference to the object that
8152 was put in the output buffer, or Py_None, if the mapping was undefined
8153 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008154 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008155static charmapencode_result
8156charmapencode_output(Py_UNICODE c, PyObject *mapping,
8157 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008158{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008159 PyObject *rep;
8160 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008161 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008162
Christian Heimes90aa7642007-12-19 02:45:37 +00008163 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008164 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008166 if (res == -1)
8167 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 if (outsize<requiredsize)
8169 if (charmapencode_resize(outobj, outpos, requiredsize))
8170 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008171 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008172 outstart[(*outpos)++] = (char)res;
8173 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008174 }
8175
8176 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008177 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008178 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008179 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 Py_DECREF(rep);
8181 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008182 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008183 if (PyLong_Check(rep)) {
8184 Py_ssize_t requiredsize = *outpos+1;
8185 if (outsize<requiredsize)
8186 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8187 Py_DECREF(rep);
8188 return enc_EXCEPTION;
8189 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008190 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008191 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008192 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 else {
8194 const char *repchars = PyBytes_AS_STRING(rep);
8195 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8196 Py_ssize_t requiredsize = *outpos+repsize;
8197 if (outsize<requiredsize)
8198 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8199 Py_DECREF(rep);
8200 return enc_EXCEPTION;
8201 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008202 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 memcpy(outstart + *outpos, repchars, repsize);
8204 *outpos += repsize;
8205 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008206 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008207 Py_DECREF(rep);
8208 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008209}
8210
8211/* handle an error in PyUnicode_EncodeCharmap
8212 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008213static int
8214charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008215 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008217 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008218 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008219{
8220 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008221 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008222 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008223 Py_UNICODE *uni2;
8224 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008225 Py_ssize_t collstartpos = *inpos;
8226 Py_ssize_t collendpos = *inpos+1;
8227 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008228 char *encoding = "charmap";
8229 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008230 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008231 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008232 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008233
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008234 if (PyUnicode_READY(unicode) < 0)
8235 return -1;
8236 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 /* find all unencodable characters */
8238 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008239 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008240 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008241 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008242 val = encoding_map_lookup(ch, mapping);
8243 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008244 break;
8245 ++collendpos;
8246 continue;
8247 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008248
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008249 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8250 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 if (rep==NULL)
8252 return -1;
8253 else if (rep!=Py_None) {
8254 Py_DECREF(rep);
8255 break;
8256 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008257 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008258 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008259 }
8260 /* cache callback name lookup
8261 * (if not done yet, i.e. it's the first error) */
8262 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 if ((errors==NULL) || (!strcmp(errors, "strict")))
8264 *known_errorHandler = 1;
8265 else if (!strcmp(errors, "replace"))
8266 *known_errorHandler = 2;
8267 else if (!strcmp(errors, "ignore"))
8268 *known_errorHandler = 3;
8269 else if (!strcmp(errors, "xmlcharrefreplace"))
8270 *known_errorHandler = 4;
8271 else
8272 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008273 }
8274 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008275 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008276 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008277 return -1;
8278 case 2: /* replace */
8279 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 x = charmapencode_output('?', mapping, res, respos);
8281 if (x==enc_EXCEPTION) {
8282 return -1;
8283 }
8284 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008285 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008286 return -1;
8287 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008288 }
8289 /* fall through */
8290 case 3: /* ignore */
8291 *inpos = collendpos;
8292 break;
8293 case 4: /* xmlcharrefreplace */
8294 /* generate replacement (temporarily (mis)uses p) */
8295 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 char buffer[2+29+1+1];
8297 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008298 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 for (cp = buffer; *cp; ++cp) {
8300 x = charmapencode_output(*cp, mapping, res, respos);
8301 if (x==enc_EXCEPTION)
8302 return -1;
8303 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008304 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008305 return -1;
8306 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008307 }
8308 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008309 *inpos = collendpos;
8310 break;
8311 default:
8312 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008313 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008314 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008315 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008317 if (PyBytes_Check(repunicode)) {
8318 /* Directly copy bytes result to output. */
8319 Py_ssize_t outsize = PyBytes_Size(*res);
8320 Py_ssize_t requiredsize;
8321 repsize = PyBytes_Size(repunicode);
8322 requiredsize = *respos + repsize;
8323 if (requiredsize > outsize)
8324 /* Make room for all additional bytes. */
8325 if (charmapencode_resize(res, respos, requiredsize)) {
8326 Py_DECREF(repunicode);
8327 return -1;
8328 }
8329 memcpy(PyBytes_AsString(*res) + *respos,
8330 PyBytes_AsString(repunicode), repsize);
8331 *respos += repsize;
8332 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008333 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008334 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008335 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008336 /* generate replacement */
8337 repsize = PyUnicode_GET_SIZE(repunicode);
8338 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008339 x = charmapencode_output(*uni2, mapping, res, respos);
8340 if (x==enc_EXCEPTION) {
8341 return -1;
8342 }
8343 else if (x==enc_FAILED) {
8344 Py_DECREF(repunicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008345 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008346 return -1;
8347 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008348 }
8349 *inpos = newpos;
8350 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351 }
8352 return 0;
8353}
8354
Alexander Belopolsky40018472011-02-26 01:02:56 +00008355PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008356_PyUnicode_EncodeCharmap(PyObject *unicode,
8357 PyObject *mapping,
8358 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008359{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 /* output object */
8361 PyObject *res = NULL;
8362 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008363 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008364 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008366 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 PyObject *errorHandler = NULL;
8368 PyObject *exc = NULL;
8369 /* the following variable is used for caching string comparisons
8370 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8371 * 3=ignore, 4=xmlcharrefreplace */
8372 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008373
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 if (PyUnicode_READY(unicode) < 0)
8375 return NULL;
8376 size = PyUnicode_GET_LENGTH(unicode);
8377
Guido van Rossumd57fd912000-03-10 22:53:23 +00008378 /* Default to Latin-1 */
8379 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008381
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008382 /* allocate enough for a simple encoding without
8383 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008384 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008385 if (res == NULL)
8386 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008387 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008389
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008390 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008391 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008392 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008393 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008394 if (x==enc_EXCEPTION) /* error */
8395 goto onError;
8396 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008397 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008398 &exc,
8399 &known_errorHandler, &errorHandler, errors,
8400 &res, &respos)) {
8401 goto onError;
8402 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008403 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 else
8405 /* done with this character => adjust input position */
8406 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008407 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008408
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008410 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008411 if (_PyBytes_Resize(&res, respos) < 0)
8412 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008413
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 Py_XDECREF(exc);
8415 Py_XDECREF(errorHandler);
8416 return res;
8417
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 Py_XDECREF(res);
8420 Py_XDECREF(exc);
8421 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008422 return NULL;
8423}
8424
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008425/* Deprecated */
8426PyObject *
8427PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8428 Py_ssize_t size,
8429 PyObject *mapping,
8430 const char *errors)
8431{
8432 PyObject *result;
8433 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8434 if (unicode == NULL)
8435 return NULL;
8436 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8437 Py_DECREF(unicode);
8438 return NULL;
8439}
8440
Alexander Belopolsky40018472011-02-26 01:02:56 +00008441PyObject *
8442PyUnicode_AsCharmapString(PyObject *unicode,
8443 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008444{
8445 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008446 PyErr_BadArgument();
8447 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008448 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008449 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008450}
8451
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008453static void
8454make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008456 Py_ssize_t startpos, Py_ssize_t endpos,
8457 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008458{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 *exceptionObject = _PyUnicodeTranslateError_Create(
8461 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008462 }
8463 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8465 goto onError;
8466 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8467 goto onError;
8468 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8469 goto onError;
8470 return;
8471 onError:
8472 Py_DECREF(*exceptionObject);
8473 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008474 }
8475}
8476
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008477/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008478static void
8479raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008481 Py_ssize_t startpos, Py_ssize_t endpos,
8482 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008483{
8484 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488}
8489
8490/* error handling callback helper:
8491 build arguments, call the callback and check the arguments,
8492 put the result into newpos and return the replacement string, which
8493 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008494static PyObject *
8495unicode_translate_call_errorhandler(const char *errors,
8496 PyObject **errorHandler,
8497 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008499 Py_ssize_t startpos, Py_ssize_t endpos,
8500 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008502 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008503
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008504 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505 PyObject *restuple;
8506 PyObject *resunicode;
8507
8508 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008511 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 }
8513
8514 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518
8519 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008521 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008523 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008524 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008525 Py_DECREF(restuple);
8526 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 }
8528 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008529 &resunicode, &i_newpos)) {
8530 Py_DECREF(restuple);
8531 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008533 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008535 else
8536 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8539 Py_DECREF(restuple);
8540 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008541 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 Py_INCREF(resunicode);
8543 Py_DECREF(restuple);
8544 return resunicode;
8545}
8546
8547/* Lookup the character ch in the mapping and put the result in result,
8548 which must be decrefed by the caller.
8549 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008550static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008551charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552{
Christian Heimes217cfd12007-12-02 14:31:20 +00008553 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008554 PyObject *x;
8555
8556 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008558 x = PyObject_GetItem(mapping, w);
8559 Py_DECREF(w);
8560 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8562 /* No mapping found means: use 1:1 mapping. */
8563 PyErr_Clear();
8564 *result = NULL;
8565 return 0;
8566 } else
8567 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008568 }
8569 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 *result = x;
8571 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008572 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008573 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008574 long value = PyLong_AS_LONG(x);
8575 long max = PyUnicode_GetMax();
8576 if (value < 0 || value > max) {
8577 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008578 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 Py_DECREF(x);
8580 return -1;
8581 }
8582 *result = x;
8583 return 0;
8584 }
8585 else if (PyUnicode_Check(x)) {
8586 *result = x;
8587 return 0;
8588 }
8589 else {
8590 /* wrong return value */
8591 PyErr_SetString(PyExc_TypeError,
8592 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008593 Py_DECREF(x);
8594 return -1;
8595 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596}
8597/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 if not reallocate and adjust various state variables.
8599 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008600static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008605 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008606 /* exponentially overallocate to minimize reallocations */
8607 if (requiredsize < 2 * oldsize)
8608 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008609 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8610 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008611 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008613 }
8614 return 0;
8615}
8616/* lookup the character, put the result in the output string and adjust
8617 various state variables. Return a new reference to the object that
8618 was put in the output buffer in *result, or Py_None, if the mapping was
8619 undefined (in which case no character was written).
8620 The called must decref result.
8621 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008622static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8624 PyObject *mapping, Py_UCS4 **output,
8625 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008626 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008627{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008628 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8629 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008631 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008634 }
8635 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008637 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008640 }
8641 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 Py_ssize_t repsize;
8643 if (PyUnicode_READY(*res) == -1)
8644 return -1;
8645 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 if (repsize==1) {
8647 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008649 }
8650 else if (repsize!=0) {
8651 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 Py_ssize_t requiredsize = *opos +
8653 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008654 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 Py_ssize_t i;
8656 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008657 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 for(i = 0; i < repsize; i++)
8659 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008660 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008661 }
8662 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 return 0;
8665}
8666
Alexander Belopolsky40018472011-02-26 01:02:56 +00008667PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008668_PyUnicode_TranslateCharmap(PyObject *input,
8669 PyObject *mapping,
8670 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 /* input object */
8673 char *idata;
8674 Py_ssize_t size, i;
8675 int kind;
8676 /* output buffer */
8677 Py_UCS4 *output = NULL;
8678 Py_ssize_t osize;
8679 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008680 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008681 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008682 char *reason = "character maps to <undefined>";
8683 PyObject *errorHandler = NULL;
8684 PyObject *exc = NULL;
8685 /* the following variable is used for caching string comparisons
8686 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8687 * 3=ignore, 4=xmlcharrefreplace */
8688 int known_errorHandler = -1;
8689
Guido van Rossumd57fd912000-03-10 22:53:23 +00008690 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 PyErr_BadArgument();
8692 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008693 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008694
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008695 if (PyUnicode_READY(input) == -1)
8696 return NULL;
8697 idata = (char*)PyUnicode_DATA(input);
8698 kind = PyUnicode_KIND(input);
8699 size = PyUnicode_GET_LENGTH(input);
8700 i = 0;
8701
8702 if (size == 0) {
8703 Py_INCREF(input);
8704 return input;
8705 }
8706
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008707 /* allocate enough for a simple 1:1 translation without
8708 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709 osize = size;
8710 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8711 opos = 0;
8712 if (output == NULL) {
8713 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008715 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008716
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 /* try to encode it */
8719 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008720 if (charmaptranslate_output(input, i, mapping,
8721 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 Py_XDECREF(x);
8723 goto onError;
8724 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008725 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008726 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008727 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008728 else { /* untranslatable character */
8729 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8730 Py_ssize_t repsize;
8731 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008732 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008733 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008734 Py_ssize_t collstart = i;
8735 Py_ssize_t collend = i+1;
8736 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008737
Benjamin Peterson29060642009-01-31 22:14:21 +00008738 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739 while (collend < size) {
8740 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008741 goto onError;
8742 Py_XDECREF(x);
8743 if (x!=Py_None)
8744 break;
8745 ++collend;
8746 }
8747 /* cache callback name lookup
8748 * (if not done yet, i.e. it's the first error) */
8749 if (known_errorHandler==-1) {
8750 if ((errors==NULL) || (!strcmp(errors, "strict")))
8751 known_errorHandler = 1;
8752 else if (!strcmp(errors, "replace"))
8753 known_errorHandler = 2;
8754 else if (!strcmp(errors, "ignore"))
8755 known_errorHandler = 3;
8756 else if (!strcmp(errors, "xmlcharrefreplace"))
8757 known_errorHandler = 4;
8758 else
8759 known_errorHandler = 0;
8760 }
8761 switch (known_errorHandler) {
8762 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 raise_translate_exception(&exc, input, collstart,
8764 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008765 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 case 2: /* replace */
8767 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008768 for (coll = collstart; coll<collend; coll++)
8769 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 /* fall through */
8771 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008773 break;
8774 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008775 /* generate replacement (temporarily (mis)uses i) */
8776 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 char buffer[2+29+1+1];
8778 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8780 if (charmaptranslate_makespace(&output, &osize,
8781 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 goto onError;
8783 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008785 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008786 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 break;
8788 default:
8789 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 reason, input, &exc,
8791 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008792 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008793 goto onError;
8794 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008795 repsize = PyUnicode_GET_LENGTH(repunicode);
8796 if (charmaptranslate_makespace(&output, &osize,
8797 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008798 Py_DECREF(repunicode);
8799 goto onError;
8800 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 for (uni2 = 0; repsize-->0; ++uni2)
8802 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8803 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008804 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008805 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008806 }
8807 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008808 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8809 if (!res)
8810 goto onError;
8811 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008812 Py_XDECREF(exc);
8813 Py_XDECREF(errorHandler);
8814 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008815
Benjamin Peterson29060642009-01-31 22:14:21 +00008816 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008817 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008818 Py_XDECREF(exc);
8819 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008820 return NULL;
8821}
8822
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823/* Deprecated. Use PyUnicode_Translate instead. */
8824PyObject *
8825PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8826 Py_ssize_t size,
8827 PyObject *mapping,
8828 const char *errors)
8829{
8830 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8831 if (!unicode)
8832 return NULL;
8833 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8834}
8835
Alexander Belopolsky40018472011-02-26 01:02:56 +00008836PyObject *
8837PyUnicode_Translate(PyObject *str,
8838 PyObject *mapping,
8839 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008840{
8841 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008842
Guido van Rossumd57fd912000-03-10 22:53:23 +00008843 str = PyUnicode_FromObject(str);
8844 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008845 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008846 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008847 Py_DECREF(str);
8848 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008849
Benjamin Peterson29060642009-01-31 22:14:21 +00008850 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008851 Py_XDECREF(str);
8852 return NULL;
8853}
Tim Petersced69f82003-09-16 20:30:58 +00008854
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008855static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008856fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008857{
8858 /* No need to call PyUnicode_READY(self) because this function is only
8859 called as a callback from fixup() which does it already. */
8860 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8861 const int kind = PyUnicode_KIND(self);
8862 void *data = PyUnicode_DATA(self);
8863 Py_UCS4 maxchar = 0, ch, fixed;
8864 Py_ssize_t i;
8865
8866 for (i = 0; i < len; ++i) {
8867 ch = PyUnicode_READ(kind, data, i);
8868 fixed = 0;
8869 if (ch > 127) {
8870 if (Py_UNICODE_ISSPACE(ch))
8871 fixed = ' ';
8872 else {
8873 const int decimal = Py_UNICODE_TODECIMAL(ch);
8874 if (decimal >= 0)
8875 fixed = '0' + decimal;
8876 }
8877 if (fixed != 0) {
8878 if (fixed > maxchar)
8879 maxchar = fixed;
8880 PyUnicode_WRITE(kind, data, i, fixed);
8881 }
8882 else if (ch > maxchar)
8883 maxchar = ch;
8884 }
8885 else if (ch > maxchar)
8886 maxchar = ch;
8887 }
8888
8889 return maxchar;
8890}
8891
8892PyObject *
8893_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8894{
8895 if (!PyUnicode_Check(unicode)) {
8896 PyErr_BadInternalCall();
8897 return NULL;
8898 }
8899 if (PyUnicode_READY(unicode) == -1)
8900 return NULL;
8901 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8902 /* If the string is already ASCII, just return the same string */
8903 Py_INCREF(unicode);
8904 return unicode;
8905 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008906 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008907}
8908
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008909PyObject *
8910PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8911 Py_ssize_t length)
8912{
8913 PyObject *result;
8914 Py_UNICODE *p; /* write pointer into result */
8915 Py_ssize_t i;
8916 /* Copy to a new string */
8917 result = (PyObject *)_PyUnicode_New(length);
8918 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8919 if (result == NULL)
8920 return result;
8921 p = PyUnicode_AS_UNICODE(result);
8922 /* Iterate over code points */
8923 for (i = 0; i < length; i++) {
8924 Py_UNICODE ch =s[i];
8925 if (ch > 127) {
8926 int decimal = Py_UNICODE_TODECIMAL(ch);
8927 if (decimal >= 0)
8928 p[i] = '0' + decimal;
8929 }
8930 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008931#ifndef DONT_MAKE_RESULT_READY
8932 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008933 Py_DECREF(result);
8934 return NULL;
8935 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008936#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008937 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008938 return result;
8939}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008940/* --- Decimal Encoder ---------------------------------------------------- */
8941
Alexander Belopolsky40018472011-02-26 01:02:56 +00008942int
8943PyUnicode_EncodeDecimal(Py_UNICODE *s,
8944 Py_ssize_t length,
8945 char *output,
8946 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008947{
8948 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008949 PyObject *errorHandler = NULL;
8950 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008951 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008952 const char *encoding = "decimal";
8953 const char *reason = "invalid decimal Unicode string";
8954 /* the following variable is used for caching string comparisons
8955 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8956 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008957
8958 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008959 PyErr_BadArgument();
8960 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008961 }
8962
8963 p = s;
8964 end = s + length;
8965 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008966 register Py_UNICODE ch = *p;
8967 int decimal;
8968 PyObject *repunicode;
8969 Py_ssize_t repsize;
8970 Py_ssize_t newpos;
8971 Py_UNICODE *uni2;
8972 Py_UNICODE *collstart;
8973 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008974
Benjamin Peterson29060642009-01-31 22:14:21 +00008975 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008976 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008977 ++p;
8978 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008979 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008980 decimal = Py_UNICODE_TODECIMAL(ch);
8981 if (decimal >= 0) {
8982 *output++ = '0' + decimal;
8983 ++p;
8984 continue;
8985 }
8986 if (0 < ch && ch < 256) {
8987 *output++ = (char)ch;
8988 ++p;
8989 continue;
8990 }
8991 /* All other characters are considered unencodable */
8992 collstart = p;
8993 collend = p+1;
8994 while (collend < end) {
8995 if ((0 < *collend && *collend < 256) ||
8996 !Py_UNICODE_ISSPACE(*collend) ||
8997 Py_UNICODE_TODECIMAL(*collend))
8998 break;
8999 }
9000 /* cache callback name lookup
9001 * (if not done yet, i.e. it's the first error) */
9002 if (known_errorHandler==-1) {
9003 if ((errors==NULL) || (!strcmp(errors, "strict")))
9004 known_errorHandler = 1;
9005 else if (!strcmp(errors, "replace"))
9006 known_errorHandler = 2;
9007 else if (!strcmp(errors, "ignore"))
9008 known_errorHandler = 3;
9009 else if (!strcmp(errors, "xmlcharrefreplace"))
9010 known_errorHandler = 4;
9011 else
9012 known_errorHandler = 0;
9013 }
9014 switch (known_errorHandler) {
9015 case 1: /* strict */
9016 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
9017 goto onError;
9018 case 2: /* replace */
9019 for (p = collstart; p < collend; ++p)
9020 *output++ = '?';
9021 /* fall through */
9022 case 3: /* ignore */
9023 p = collend;
9024 break;
9025 case 4: /* xmlcharrefreplace */
9026 /* generate replacement (temporarily (mis)uses p) */
9027 for (p = collstart; p < collend; ++p)
9028 output += sprintf(output, "&#%d;", (int)*p);
9029 p = collend;
9030 break;
9031 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009032 unicode = PyUnicode_FromUnicode(s, length);
9033 if (unicode == NULL)
9034 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009035 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009036 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009037 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009038 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00009039 if (repunicode == NULL)
9040 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009041 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00009042 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009043 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
9044 Py_DECREF(repunicode);
9045 goto onError;
9046 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009047 /* generate replacement */
9048 repsize = PyUnicode_GET_SIZE(repunicode);
9049 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
9050 Py_UNICODE ch = *uni2;
9051 if (Py_UNICODE_ISSPACE(ch))
9052 *output++ = ' ';
9053 else {
9054 decimal = Py_UNICODE_TODECIMAL(ch);
9055 if (decimal >= 0)
9056 *output++ = '0' + decimal;
9057 else if (0 < ch && ch < 256)
9058 *output++ = (char)ch;
9059 else {
9060 Py_DECREF(repunicode);
9061 raise_encode_exception(&exc, encoding,
9062 s, length, collstart-s, collend-s, reason);
9063 goto onError;
9064 }
9065 }
9066 }
9067 p = s + newpos;
9068 Py_DECREF(repunicode);
9069 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00009070 }
9071 /* 0-terminate the output string */
9072 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009073 Py_XDECREF(exc);
9074 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009075 return 0;
9076
Benjamin Peterson29060642009-01-31 22:14:21 +00009077 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009078 Py_XDECREF(exc);
9079 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009080 return -1;
9081}
9082
Guido van Rossumd57fd912000-03-10 22:53:23 +00009083/* --- Helpers ------------------------------------------------------------ */
9084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009085static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009086any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009087 Py_ssize_t start,
9088 Py_ssize_t end)
9089{
9090 int kind1, kind2, kind;
9091 void *buf1, *buf2;
9092 Py_ssize_t len1, len2, result;
9093
9094 kind1 = PyUnicode_KIND(s1);
9095 kind2 = PyUnicode_KIND(s2);
9096 kind = kind1 > kind2 ? kind1 : kind2;
9097 buf1 = PyUnicode_DATA(s1);
9098 buf2 = PyUnicode_DATA(s2);
9099 if (kind1 != kind)
9100 buf1 = _PyUnicode_AsKind(s1, kind);
9101 if (!buf1)
9102 return -2;
9103 if (kind2 != kind)
9104 buf2 = _PyUnicode_AsKind(s2, kind);
9105 if (!buf2) {
9106 if (kind1 != kind) PyMem_Free(buf1);
9107 return -2;
9108 }
9109 len1 = PyUnicode_GET_LENGTH(s1);
9110 len2 = PyUnicode_GET_LENGTH(s2);
9111
Victor Stinner794d5672011-10-10 03:21:36 +02009112 if (direction > 0) {
9113 switch(kind) {
9114 case PyUnicode_1BYTE_KIND:
9115 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9116 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9117 else
9118 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9119 break;
9120 case PyUnicode_2BYTE_KIND:
9121 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9122 break;
9123 case PyUnicode_4BYTE_KIND:
9124 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9125 break;
9126 default:
9127 assert(0); result = -2;
9128 }
9129 }
9130 else {
9131 switch(kind) {
9132 case PyUnicode_1BYTE_KIND:
9133 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9134 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9135 else
9136 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9137 break;
9138 case PyUnicode_2BYTE_KIND:
9139 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9140 break;
9141 case PyUnicode_4BYTE_KIND:
9142 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9143 break;
9144 default:
9145 assert(0); result = -2;
9146 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009147 }
9148
9149 if (kind1 != kind)
9150 PyMem_Free(buf1);
9151 if (kind2 != kind)
9152 PyMem_Free(buf2);
9153
9154 return result;
9155}
9156
9157Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009158_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 Py_ssize_t n_buffer,
9160 void *digits, Py_ssize_t n_digits,
9161 Py_ssize_t min_width,
9162 const char *grouping,
9163 const char *thousands_sep)
9164{
9165 switch(kind) {
9166 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009167 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9168 return _PyUnicode_ascii_InsertThousandsGrouping(
9169 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9170 min_width, grouping, thousands_sep);
9171 else
9172 return _PyUnicode_ucs1_InsertThousandsGrouping(
9173 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9174 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009175 case PyUnicode_2BYTE_KIND:
9176 return _PyUnicode_ucs2_InsertThousandsGrouping(
9177 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9178 min_width, grouping, thousands_sep);
9179 case PyUnicode_4BYTE_KIND:
9180 return _PyUnicode_ucs4_InsertThousandsGrouping(
9181 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9182 min_width, grouping, thousands_sep);
9183 }
9184 assert(0);
9185 return -1;
9186}
9187
9188
Thomas Wouters477c8d52006-05-27 19:21:47 +00009189/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009190#define ADJUST_INDICES(start, end, len) \
9191 if (end > len) \
9192 end = len; \
9193 else if (end < 0) { \
9194 end += len; \
9195 if (end < 0) \
9196 end = 0; \
9197 } \
9198 if (start < 0) { \
9199 start += len; \
9200 if (start < 0) \
9201 start = 0; \
9202 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009203
Alexander Belopolsky40018472011-02-26 01:02:56 +00009204Py_ssize_t
9205PyUnicode_Count(PyObject *str,
9206 PyObject *substr,
9207 Py_ssize_t start,
9208 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009209{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009210 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009211 PyObject* str_obj;
9212 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009213 int kind1, kind2, kind;
9214 void *buf1 = NULL, *buf2 = NULL;
9215 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009216
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009217 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009218 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009219 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009220 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009221 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009222 Py_DECREF(str_obj);
9223 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224 }
Tim Petersced69f82003-09-16 20:30:58 +00009225
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009226 kind1 = PyUnicode_KIND(str_obj);
9227 kind2 = PyUnicode_KIND(sub_obj);
9228 kind = kind1 > kind2 ? kind1 : kind2;
9229 buf1 = PyUnicode_DATA(str_obj);
9230 if (kind1 != kind)
9231 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
9232 if (!buf1)
9233 goto onError;
9234 buf2 = PyUnicode_DATA(sub_obj);
9235 if (kind2 != kind)
9236 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
9237 if (!buf2)
9238 goto onError;
9239 len1 = PyUnicode_GET_LENGTH(str_obj);
9240 len2 = PyUnicode_GET_LENGTH(sub_obj);
9241
9242 ADJUST_INDICES(start, end, len1);
9243 switch(kind) {
9244 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009245 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9246 result = asciilib_count(
9247 ((Py_UCS1*)buf1) + start, end - start,
9248 buf2, len2, PY_SSIZE_T_MAX
9249 );
9250 else
9251 result = ucs1lib_count(
9252 ((Py_UCS1*)buf1) + start, end - start,
9253 buf2, len2, PY_SSIZE_T_MAX
9254 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009255 break;
9256 case PyUnicode_2BYTE_KIND:
9257 result = ucs2lib_count(
9258 ((Py_UCS2*)buf1) + start, end - start,
9259 buf2, len2, PY_SSIZE_T_MAX
9260 );
9261 break;
9262 case PyUnicode_4BYTE_KIND:
9263 result = ucs4lib_count(
9264 ((Py_UCS4*)buf1) + start, end - start,
9265 buf2, len2, PY_SSIZE_T_MAX
9266 );
9267 break;
9268 default:
9269 assert(0); result = 0;
9270 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009271
9272 Py_DECREF(sub_obj);
9273 Py_DECREF(str_obj);
9274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009275 if (kind1 != kind)
9276 PyMem_Free(buf1);
9277 if (kind2 != kind)
9278 PyMem_Free(buf2);
9279
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 onError:
9282 Py_DECREF(sub_obj);
9283 Py_DECREF(str_obj);
9284 if (kind1 != kind && buf1)
9285 PyMem_Free(buf1);
9286 if (kind2 != kind && buf2)
9287 PyMem_Free(buf2);
9288 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009289}
9290
Alexander Belopolsky40018472011-02-26 01:02:56 +00009291Py_ssize_t
9292PyUnicode_Find(PyObject *str,
9293 PyObject *sub,
9294 Py_ssize_t start,
9295 Py_ssize_t end,
9296 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009298 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009299
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009302 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009303 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009304 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009305 Py_DECREF(str);
9306 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009307 }
Tim Petersced69f82003-09-16 20:30:58 +00009308
Victor Stinner794d5672011-10-10 03:21:36 +02009309 result = any_find_slice(direction,
9310 str, sub, start, end
9311 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009312
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009314 Py_DECREF(sub);
9315
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316 return result;
9317}
9318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319Py_ssize_t
9320PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9321 Py_ssize_t start, Py_ssize_t end,
9322 int direction)
9323{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009325 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009326 if (PyUnicode_READY(str) == -1)
9327 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009328 if (start < 0 || end < 0) {
9329 PyErr_SetString(PyExc_IndexError, "string index out of range");
9330 return -2;
9331 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009332 if (end > PyUnicode_GET_LENGTH(str))
9333 end = PyUnicode_GET_LENGTH(str);
9334 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009335 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9336 kind, end-start, ch, direction);
9337 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009339 else
9340 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009341}
9342
Alexander Belopolsky40018472011-02-26 01:02:56 +00009343static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009344tailmatch(PyObject *self,
9345 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009346 Py_ssize_t start,
9347 Py_ssize_t end,
9348 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009349{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350 int kind_self;
9351 int kind_sub;
9352 void *data_self;
9353 void *data_sub;
9354 Py_ssize_t offset;
9355 Py_ssize_t i;
9356 Py_ssize_t end_sub;
9357
9358 if (PyUnicode_READY(self) == -1 ||
9359 PyUnicode_READY(substring) == -1)
9360 return 0;
9361
9362 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363 return 1;
9364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9366 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009370 kind_self = PyUnicode_KIND(self);
9371 data_self = PyUnicode_DATA(self);
9372 kind_sub = PyUnicode_KIND(substring);
9373 data_sub = PyUnicode_DATA(substring);
9374 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9375
9376 if (direction > 0)
9377 offset = end;
9378 else
9379 offset = start;
9380
9381 if (PyUnicode_READ(kind_self, data_self, offset) ==
9382 PyUnicode_READ(kind_sub, data_sub, 0) &&
9383 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9384 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9385 /* If both are of the same kind, memcmp is sufficient */
9386 if (kind_self == kind_sub) {
9387 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009388 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009389 data_sub,
9390 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009391 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 }
9393 /* otherwise we have to compare each character by first accesing it */
9394 else {
9395 /* We do not need to compare 0 and len(substring)-1 because
9396 the if statement above ensured already that they are equal
9397 when we end up here. */
9398 // TODO: honor direction and do a forward or backwards search
9399 for (i = 1; i < end_sub; ++i) {
9400 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9401 PyUnicode_READ(kind_sub, data_sub, i))
9402 return 0;
9403 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009404 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406 }
9407
9408 return 0;
9409}
9410
Alexander Belopolsky40018472011-02-26 01:02:56 +00009411Py_ssize_t
9412PyUnicode_Tailmatch(PyObject *str,
9413 PyObject *substr,
9414 Py_ssize_t start,
9415 Py_ssize_t end,
9416 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009417{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009418 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009419
Guido van Rossumd57fd912000-03-10 22:53:23 +00009420 str = PyUnicode_FromObject(str);
9421 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009422 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423 substr = PyUnicode_FromObject(substr);
9424 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009425 Py_DECREF(str);
9426 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009427 }
Tim Petersced69f82003-09-16 20:30:58 +00009428
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009429 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009430 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009431 Py_DECREF(str);
9432 Py_DECREF(substr);
9433 return result;
9434}
9435
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436/* Apply fixfct filter to the Unicode object self and return a
9437 reference to the modified object */
9438
Alexander Belopolsky40018472011-02-26 01:02:56 +00009439static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009440fixup(PyObject *self,
9441 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009442{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009443 PyObject *u;
9444 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 if (PyUnicode_READY(self) == -1)
9447 return NULL;
9448 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9449 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9450 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009452 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009453
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009454 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009455 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009457 /* fix functions return the new maximum character in a string,
9458 if the kind of the resulting unicode object does not change,
9459 everything is fine. Otherwise we need to change the string kind
9460 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009461 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 if (maxchar_new == 0)
9463 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9464 else if (maxchar_new <= 127)
9465 maxchar_new = 127;
9466 else if (maxchar_new <= 255)
9467 maxchar_new = 255;
9468 else if (maxchar_new <= 65535)
9469 maxchar_new = 65535;
9470 else
9471 maxchar_new = 1114111; /* 0x10ffff */
9472
9473 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009474 /* fixfct should return TRUE if it modified the buffer. If
9475 FALSE, return a reference to the original buffer instead
9476 (to save space, not time) */
9477 Py_INCREF(self);
9478 Py_DECREF(u);
9479 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 else if (maxchar_new == maxchar_old) {
9482 return u;
9483 }
9484 else {
9485 /* In case the maximum character changed, we need to
9486 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009487 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488 if (v == NULL) {
9489 Py_DECREF(u);
9490 return NULL;
9491 }
9492 if (maxchar_new > maxchar_old) {
9493 /* If the maxchar increased so that the kind changed, not all
9494 characters are representable anymore and we need to fix the
9495 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009496 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009497 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009498 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9499 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009500 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009501 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009502 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503
9504 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009505 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 return v;
9507 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009508}
9509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009510static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009511fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009513 /* No need to call PyUnicode_READY(self) because this function is only
9514 called as a callback from fixup() which does it already. */
9515 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9516 const int kind = PyUnicode_KIND(self);
9517 void *data = PyUnicode_DATA(self);
9518 int touched = 0;
9519 Py_UCS4 maxchar = 0;
9520 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009521
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 for (i = 0; i < len; ++i) {
9523 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9524 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9525 if (up != ch) {
9526 if (up > maxchar)
9527 maxchar = up;
9528 PyUnicode_WRITE(kind, data, i, up);
9529 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009530 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 else if (ch > maxchar)
9532 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009533 }
9534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 if (touched)
9536 return maxchar;
9537 else
9538 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009539}
9540
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009542fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009543{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9545 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9546 const int kind = PyUnicode_KIND(self);
9547 void *data = PyUnicode_DATA(self);
9548 int touched = 0;
9549 Py_UCS4 maxchar = 0;
9550 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 for(i = 0; i < len; ++i) {
9553 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9554 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9555 if (lo != ch) {
9556 if (lo > maxchar)
9557 maxchar = lo;
9558 PyUnicode_WRITE(kind, data, i, lo);
9559 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 else if (ch > maxchar)
9562 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563 }
9564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 if (touched)
9566 return maxchar;
9567 else
9568 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009569}
9570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009572fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009573{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9575 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9576 const int kind = PyUnicode_KIND(self);
9577 void *data = PyUnicode_DATA(self);
9578 int touched = 0;
9579 Py_UCS4 maxchar = 0;
9580 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009582 for(i = 0; i < len; ++i) {
9583 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9584 Py_UCS4 nu = 0;
9585
9586 if (Py_UNICODE_ISUPPER(ch))
9587 nu = Py_UNICODE_TOLOWER(ch);
9588 else if (Py_UNICODE_ISLOWER(ch))
9589 nu = Py_UNICODE_TOUPPER(ch);
9590
9591 if (nu != 0) {
9592 if (nu > maxchar)
9593 maxchar = nu;
9594 PyUnicode_WRITE(kind, data, i, nu);
9595 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009597 else if (ch > maxchar)
9598 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009599 }
9600
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009601 if (touched)
9602 return maxchar;
9603 else
9604 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605}
9606
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009607static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009608fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009609{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009610 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9611 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9612 const int kind = PyUnicode_KIND(self);
9613 void *data = PyUnicode_DATA(self);
9614 int touched = 0;
9615 Py_UCS4 maxchar = 0;
9616 Py_ssize_t i = 0;
9617 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009618
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009619 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009620 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621
9622 ch = PyUnicode_READ(kind, data, i);
9623 if (!Py_UNICODE_ISUPPER(ch)) {
9624 maxchar = Py_UNICODE_TOUPPER(ch);
9625 PyUnicode_WRITE(kind, data, i, maxchar);
9626 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628 ++i;
9629 for(; i < len; ++i) {
9630 ch = PyUnicode_READ(kind, data, i);
9631 if (!Py_UNICODE_ISLOWER(ch)) {
9632 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9633 if (lo > maxchar)
9634 maxchar = lo;
9635 PyUnicode_WRITE(kind, data, i, lo);
9636 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009637 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009638 else if (ch > maxchar)
9639 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009640 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009641
9642 if (touched)
9643 return maxchar;
9644 else
9645 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646}
9647
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009649fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009650{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009651 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9652 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9653 const int kind = PyUnicode_KIND(self);
9654 void *data = PyUnicode_DATA(self);
9655 Py_UCS4 maxchar = 0;
9656 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009657 int previous_is_cased;
9658
9659 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 if (len == 1) {
9661 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9662 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9663 if (ti != ch) {
9664 PyUnicode_WRITE(kind, data, i, ti);
9665 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009666 }
9667 else
9668 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009670 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009671 for(; i < len; ++i) {
9672 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9673 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009674
Benjamin Peterson29060642009-01-31 22:14:21 +00009675 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009676 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009677 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 nu = Py_UNICODE_TOTITLE(ch);
9679
9680 if (nu > maxchar)
9681 maxchar = nu;
9682 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009683
Benjamin Peterson29060642009-01-31 22:14:21 +00009684 if (Py_UNICODE_ISLOWER(ch) ||
9685 Py_UNICODE_ISUPPER(ch) ||
9686 Py_UNICODE_ISTITLE(ch))
9687 previous_is_cased = 1;
9688 else
9689 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009691 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009692}
9693
Tim Peters8ce9f162004-08-27 01:49:32 +00009694PyObject *
9695PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009697 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009698 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009699 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009700 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009701 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9702 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009703 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009704 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009705 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009706 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009707 int use_memcpy;
9708 unsigned char *res_data = NULL, *sep_data = NULL;
9709 PyObject *last_obj;
9710 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009711
Tim Peters05eba1f2004-08-27 21:32:02 +00009712 fseq = PySequence_Fast(seq, "");
9713 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009714 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009715 }
9716
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009717 /* NOTE: the following code can't call back into Python code,
9718 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009719 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009720
Tim Peters05eba1f2004-08-27 21:32:02 +00009721 seqlen = PySequence_Fast_GET_SIZE(fseq);
9722 /* If empty sequence, return u"". */
9723 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009724 Py_DECREF(fseq);
9725 Py_INCREF(unicode_empty);
9726 res = unicode_empty;
9727 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009728 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009729
Tim Peters05eba1f2004-08-27 21:32:02 +00009730 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009731 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009732 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009733 if (seqlen == 1) {
9734 if (PyUnicode_CheckExact(items[0])) {
9735 res = items[0];
9736 Py_INCREF(res);
9737 Py_DECREF(fseq);
9738 return res;
9739 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009741 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009742 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009743 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009744 /* Set up sep and seplen */
9745 if (separator == NULL) {
9746 /* fall back to a blank space separator */
9747 sep = PyUnicode_FromOrdinal(' ');
9748 if (!sep)
9749 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009750 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009751 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009752 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009753 else {
9754 if (!PyUnicode_Check(separator)) {
9755 PyErr_Format(PyExc_TypeError,
9756 "separator: expected str instance,"
9757 " %.80s found",
9758 Py_TYPE(separator)->tp_name);
9759 goto onError;
9760 }
9761 if (PyUnicode_READY(separator))
9762 goto onError;
9763 sep = separator;
9764 seplen = PyUnicode_GET_LENGTH(separator);
9765 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9766 /* inc refcount to keep this code path symmetric with the
9767 above case of a blank separator */
9768 Py_INCREF(sep);
9769 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009770 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009771 }
9772
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009773 /* There are at least two things to join, or else we have a subclass
9774 * of str in the sequence.
9775 * Do a pre-pass to figure out the total amount of space we'll
9776 * need (sz), and see whether all argument are strings.
9777 */
9778 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009779#ifdef Py_DEBUG
9780 use_memcpy = 0;
9781#else
9782 use_memcpy = 1;
9783#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009784 for (i = 0; i < seqlen; i++) {
9785 const Py_ssize_t old_sz = sz;
9786 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009787 if (!PyUnicode_Check(item)) {
9788 PyErr_Format(PyExc_TypeError,
9789 "sequence item %zd: expected str instance,"
9790 " %.80s found",
9791 i, Py_TYPE(item)->tp_name);
9792 goto onError;
9793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009794 if (PyUnicode_READY(item) == -1)
9795 goto onError;
9796 sz += PyUnicode_GET_LENGTH(item);
9797 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009798 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009799 if (i != 0)
9800 sz += seplen;
9801 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9802 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009803 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009804 goto onError;
9805 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009806 if (use_memcpy && last_obj != NULL) {
9807 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9808 use_memcpy = 0;
9809 }
9810 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009811 }
Tim Petersced69f82003-09-16 20:30:58 +00009812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009813 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009814 if (res == NULL)
9815 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009816
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009817 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009818#ifdef Py_DEBUG
9819 use_memcpy = 0;
9820#else
9821 if (use_memcpy) {
9822 res_data = PyUnicode_1BYTE_DATA(res);
9823 kind = PyUnicode_KIND(res);
9824 if (seplen != 0)
9825 sep_data = PyUnicode_1BYTE_DATA(sep);
9826 }
9827#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009829 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009830 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009831 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009832 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009833 if (use_memcpy) {
9834 Py_MEMCPY(res_data,
9835 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009836 kind * seplen);
9837 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009838 }
9839 else {
9840 copy_characters(res, res_offset, sep, 0, seplen);
9841 res_offset += seplen;
9842 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009843 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009844 itemlen = PyUnicode_GET_LENGTH(item);
9845 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009846 if (use_memcpy) {
9847 Py_MEMCPY(res_data,
9848 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009849 kind * itemlen);
9850 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009851 }
9852 else {
9853 copy_characters(res, res_offset, item, 0, itemlen);
9854 res_offset += itemlen;
9855 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009856 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009857 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009858 if (use_memcpy)
9859 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009860 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009861 else
9862 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009863
Tim Peters05eba1f2004-08-27 21:32:02 +00009864 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009865 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009866 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009867 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009868
Benjamin Peterson29060642009-01-31 22:14:21 +00009869 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009870 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009871 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009872 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009873 return NULL;
9874}
9875
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876#define FILL(kind, data, value, start, length) \
9877 do { \
9878 Py_ssize_t i_ = 0; \
9879 assert(kind != PyUnicode_WCHAR_KIND); \
9880 switch ((kind)) { \
9881 case PyUnicode_1BYTE_KIND: { \
9882 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9883 memset(to_, (unsigned char)value, length); \
9884 break; \
9885 } \
9886 case PyUnicode_2BYTE_KIND: { \
9887 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9888 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9889 break; \
9890 } \
9891 default: { \
9892 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9893 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9894 break; \
9895 } \
9896 } \
9897 } while (0)
9898
Victor Stinner9310abb2011-10-05 00:59:23 +02009899static PyObject *
9900pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009901 Py_ssize_t left,
9902 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009904{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 PyObject *u;
9906 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009907 int kind;
9908 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009909
9910 if (left < 0)
9911 left = 0;
9912 if (right < 0)
9913 right = 0;
9914
Tim Peters7a29bd52001-09-12 03:03:31 +00009915 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009916 Py_INCREF(self);
9917 return self;
9918 }
9919
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9921 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009922 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9923 return NULL;
9924 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9926 if (fill > maxchar)
9927 maxchar = fill;
9928 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009929 if (!u)
9930 return NULL;
9931
9932 kind = PyUnicode_KIND(u);
9933 data = PyUnicode_DATA(u);
9934 if (left)
9935 FILL(kind, data, fill, 0, left);
9936 if (right)
9937 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009938 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009939 assert(_PyUnicode_CheckConsistency(u, 1));
9940 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009941}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009943
Alexander Belopolsky40018472011-02-26 01:02:56 +00009944PyObject *
9945PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009946{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009947 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009948
9949 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009950 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009951 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009953 switch(PyUnicode_KIND(string)) {
9954 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009955 if (PyUnicode_IS_ASCII(string))
9956 list = asciilib_splitlines(
9957 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9958 PyUnicode_GET_LENGTH(string), keepends);
9959 else
9960 list = ucs1lib_splitlines(
9961 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9962 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009963 break;
9964 case PyUnicode_2BYTE_KIND:
9965 list = ucs2lib_splitlines(
9966 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9967 PyUnicode_GET_LENGTH(string), keepends);
9968 break;
9969 case PyUnicode_4BYTE_KIND:
9970 list = ucs4lib_splitlines(
9971 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9972 PyUnicode_GET_LENGTH(string), keepends);
9973 break;
9974 default:
9975 assert(0);
9976 list = 0;
9977 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009978 Py_DECREF(string);
9979 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980}
9981
Alexander Belopolsky40018472011-02-26 01:02:56 +00009982static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009983split(PyObject *self,
9984 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009985 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009986{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 int kind1, kind2, kind;
9988 void *buf1, *buf2;
9989 Py_ssize_t len1, len2;
9990 PyObject* out;
9991
Guido van Rossumd57fd912000-03-10 22:53:23 +00009992 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009993 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009994
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 if (PyUnicode_READY(self) == -1)
9996 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009998 if (substring == NULL)
9999 switch(PyUnicode_KIND(self)) {
10000 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010001 if (PyUnicode_IS_ASCII(self))
10002 return asciilib_split_whitespace(
10003 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10004 PyUnicode_GET_LENGTH(self), maxcount
10005 );
10006 else
10007 return ucs1lib_split_whitespace(
10008 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10009 PyUnicode_GET_LENGTH(self), maxcount
10010 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010011 case PyUnicode_2BYTE_KIND:
10012 return ucs2lib_split_whitespace(
10013 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10014 PyUnicode_GET_LENGTH(self), maxcount
10015 );
10016 case PyUnicode_4BYTE_KIND:
10017 return ucs4lib_split_whitespace(
10018 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10019 PyUnicode_GET_LENGTH(self), maxcount
10020 );
10021 default:
10022 assert(0);
10023 return NULL;
10024 }
10025
10026 if (PyUnicode_READY(substring) == -1)
10027 return NULL;
10028
10029 kind1 = PyUnicode_KIND(self);
10030 kind2 = PyUnicode_KIND(substring);
10031 kind = kind1 > kind2 ? kind1 : kind2;
10032 buf1 = PyUnicode_DATA(self);
10033 buf2 = PyUnicode_DATA(substring);
10034 if (kind1 != kind)
10035 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10036 if (!buf1)
10037 return NULL;
10038 if (kind2 != kind)
10039 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10040 if (!buf2) {
10041 if (kind1 != kind) PyMem_Free(buf1);
10042 return NULL;
10043 }
10044 len1 = PyUnicode_GET_LENGTH(self);
10045 len2 = PyUnicode_GET_LENGTH(substring);
10046
10047 switch(kind) {
10048 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010049 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10050 out = asciilib_split(
10051 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10052 else
10053 out = ucs1lib_split(
10054 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010055 break;
10056 case PyUnicode_2BYTE_KIND:
10057 out = ucs2lib_split(
10058 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10059 break;
10060 case PyUnicode_4BYTE_KIND:
10061 out = ucs4lib_split(
10062 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10063 break;
10064 default:
10065 out = NULL;
10066 }
10067 if (kind1 != kind)
10068 PyMem_Free(buf1);
10069 if (kind2 != kind)
10070 PyMem_Free(buf2);
10071 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010072}
10073
Alexander Belopolsky40018472011-02-26 01:02:56 +000010074static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010075rsplit(PyObject *self,
10076 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010077 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010078{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 int kind1, kind2, kind;
10080 void *buf1, *buf2;
10081 Py_ssize_t len1, len2;
10082 PyObject* out;
10083
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010084 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010085 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 if (PyUnicode_READY(self) == -1)
10088 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010090 if (substring == NULL)
10091 switch(PyUnicode_KIND(self)) {
10092 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010093 if (PyUnicode_IS_ASCII(self))
10094 return asciilib_rsplit_whitespace(
10095 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10096 PyUnicode_GET_LENGTH(self), maxcount
10097 );
10098 else
10099 return ucs1lib_rsplit_whitespace(
10100 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10101 PyUnicode_GET_LENGTH(self), maxcount
10102 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 case PyUnicode_2BYTE_KIND:
10104 return ucs2lib_rsplit_whitespace(
10105 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10106 PyUnicode_GET_LENGTH(self), maxcount
10107 );
10108 case PyUnicode_4BYTE_KIND:
10109 return ucs4lib_rsplit_whitespace(
10110 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10111 PyUnicode_GET_LENGTH(self), maxcount
10112 );
10113 default:
10114 assert(0);
10115 return NULL;
10116 }
10117
10118 if (PyUnicode_READY(substring) == -1)
10119 return NULL;
10120
10121 kind1 = PyUnicode_KIND(self);
10122 kind2 = PyUnicode_KIND(substring);
10123 kind = kind1 > kind2 ? kind1 : kind2;
10124 buf1 = PyUnicode_DATA(self);
10125 buf2 = PyUnicode_DATA(substring);
10126 if (kind1 != kind)
10127 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10128 if (!buf1)
10129 return NULL;
10130 if (kind2 != kind)
10131 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10132 if (!buf2) {
10133 if (kind1 != kind) PyMem_Free(buf1);
10134 return NULL;
10135 }
10136 len1 = PyUnicode_GET_LENGTH(self);
10137 len2 = PyUnicode_GET_LENGTH(substring);
10138
10139 switch(kind) {
10140 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010141 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10142 out = asciilib_rsplit(
10143 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10144 else
10145 out = ucs1lib_rsplit(
10146 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 break;
10148 case PyUnicode_2BYTE_KIND:
10149 out = ucs2lib_rsplit(
10150 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10151 break;
10152 case PyUnicode_4BYTE_KIND:
10153 out = ucs4lib_rsplit(
10154 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10155 break;
10156 default:
10157 out = NULL;
10158 }
10159 if (kind1 != kind)
10160 PyMem_Free(buf1);
10161 if (kind2 != kind)
10162 PyMem_Free(buf2);
10163 return out;
10164}
10165
10166static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010167anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10168 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010169{
10170 switch(kind) {
10171 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010172 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10173 return asciilib_find(buf1, len1, buf2, len2, offset);
10174 else
10175 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010176 case PyUnicode_2BYTE_KIND:
10177 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10178 case PyUnicode_4BYTE_KIND:
10179 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10180 }
10181 assert(0);
10182 return -1;
10183}
10184
10185static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010186anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10187 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188{
10189 switch(kind) {
10190 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010191 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10192 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10193 else
10194 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 case PyUnicode_2BYTE_KIND:
10196 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10197 case PyUnicode_4BYTE_KIND:
10198 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10199 }
10200 assert(0);
10201 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010202}
10203
Alexander Belopolsky40018472011-02-26 01:02:56 +000010204static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010205replace(PyObject *self, PyObject *str1,
10206 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010207{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 PyObject *u;
10209 char *sbuf = PyUnicode_DATA(self);
10210 char *buf1 = PyUnicode_DATA(str1);
10211 char *buf2 = PyUnicode_DATA(str2);
10212 int srelease = 0, release1 = 0, release2 = 0;
10213 int skind = PyUnicode_KIND(self);
10214 int kind1 = PyUnicode_KIND(str1);
10215 int kind2 = PyUnicode_KIND(str2);
10216 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10217 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10218 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010219 int mayshrink;
10220 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221
10222 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010223 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010225 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010226
Victor Stinner59de0ee2011-10-07 10:01:28 +020010227 if (str1 == str2)
10228 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 if (skind < kind1)
10230 /* substring too wide to be present */
10231 goto nothing;
10232
Victor Stinner49a0a212011-10-12 23:46:10 +020010233 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10234 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10235 /* Replacing str1 with str2 may cause a maxchar reduction in the
10236 result string. */
10237 mayshrink = (maxchar_str2 < maxchar);
10238 maxchar = Py_MAX(maxchar, maxchar_str2);
10239
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010241 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010244 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010245 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010246 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010247 Py_UCS4 u1, u2;
10248 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010249 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010250 if (findchar(sbuf, PyUnicode_KIND(self),
10251 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010252 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010255 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010257 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 rkind = PyUnicode_KIND(u);
10259 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10260 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 if (--maxcount < 0)
10262 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010264 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010265 }
10266 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010267 int rkind = skind;
10268 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010269
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 if (kind1 < rkind) {
10271 /* widen substring */
10272 buf1 = _PyUnicode_AsKind(str1, rkind);
10273 if (!buf1) goto error;
10274 release1 = 1;
10275 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010277 if (i < 0)
10278 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010279 if (rkind > kind2) {
10280 /* widen replacement */
10281 buf2 = _PyUnicode_AsKind(str2, rkind);
10282 if (!buf2) goto error;
10283 release2 = 1;
10284 }
10285 else if (rkind < kind2) {
10286 /* widen self and buf1 */
10287 rkind = kind2;
10288 if (release1) PyMem_Free(buf1);
10289 sbuf = _PyUnicode_AsKind(self, rkind);
10290 if (!sbuf) goto error;
10291 srelease = 1;
10292 buf1 = _PyUnicode_AsKind(str1, rkind);
10293 if (!buf1) goto error;
10294 release1 = 1;
10295 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010296 u = PyUnicode_New(slen, maxchar);
10297 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010298 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010299 assert(PyUnicode_KIND(u) == rkind);
10300 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010301
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010302 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010303 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010304 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010306 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010308
10309 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010310 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010311 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010312 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010313 if (i == -1)
10314 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010315 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010317 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010318 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010319 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010320 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010321 }
10322 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 Py_ssize_t n, i, j, ires;
10324 Py_ssize_t product, new_size;
10325 int rkind = skind;
10326 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010329 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010330 buf1 = _PyUnicode_AsKind(str1, rkind);
10331 if (!buf1) goto error;
10332 release1 = 1;
10333 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010334 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010335 if (n == 0)
10336 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010337 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010338 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010339 buf2 = _PyUnicode_AsKind(str2, rkind);
10340 if (!buf2) goto error;
10341 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010342 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010343 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010344 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 rkind = kind2;
10346 sbuf = _PyUnicode_AsKind(self, rkind);
10347 if (!sbuf) goto error;
10348 srelease = 1;
10349 if (release1) PyMem_Free(buf1);
10350 buf1 = _PyUnicode_AsKind(str1, rkind);
10351 if (!buf1) goto error;
10352 release1 = 1;
10353 }
10354 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10355 PyUnicode_GET_LENGTH(str1))); */
10356 product = n * (len2-len1);
10357 if ((product / (len2-len1)) != n) {
10358 PyErr_SetString(PyExc_OverflowError,
10359 "replace string is too long");
10360 goto error;
10361 }
10362 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010363 if (new_size == 0) {
10364 Py_INCREF(unicode_empty);
10365 u = unicode_empty;
10366 goto done;
10367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010368 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10369 PyErr_SetString(PyExc_OverflowError,
10370 "replace string is too long");
10371 goto error;
10372 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010373 u = PyUnicode_New(new_size, maxchar);
10374 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010376 assert(PyUnicode_KIND(u) == rkind);
10377 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 ires = i = 0;
10379 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010380 while (n-- > 0) {
10381 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010382 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010383 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010384 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010385 if (j == -1)
10386 break;
10387 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010388 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010389 memcpy(res + rkind * ires,
10390 sbuf + rkind * i,
10391 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010393 }
10394 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010395 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010396 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010398 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010400 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010401 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010402 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010404 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010405 memcpy(res + rkind * ires,
10406 sbuf + rkind * i,
10407 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010408 }
10409 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010410 /* interleave */
10411 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010412 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010413 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010414 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010415 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010416 if (--n <= 0)
10417 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010418 memcpy(res + rkind * ires,
10419 sbuf + rkind * i,
10420 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 ires++;
10422 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010423 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010424 memcpy(res + rkind * ires,
10425 sbuf + rkind * i,
10426 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010427 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010428 }
10429
10430 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010431 unicode_adjust_maxchar(&u);
10432 if (u == NULL)
10433 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010434 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010435
10436 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 if (srelease)
10438 PyMem_FREE(sbuf);
10439 if (release1)
10440 PyMem_FREE(buf1);
10441 if (release2)
10442 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010443 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010445
Benjamin Peterson29060642009-01-31 22:14:21 +000010446 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010447 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 if (srelease)
10449 PyMem_FREE(sbuf);
10450 if (release1)
10451 PyMem_FREE(buf1);
10452 if (release2)
10453 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010454 if (PyUnicode_CheckExact(self)) {
10455 Py_INCREF(self);
10456 return (PyObject *) self;
10457 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010458 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 error:
10460 if (srelease && sbuf)
10461 PyMem_FREE(sbuf);
10462 if (release1 && buf1)
10463 PyMem_FREE(buf1);
10464 if (release2 && buf2)
10465 PyMem_FREE(buf2);
10466 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467}
10468
10469/* --- Unicode Object Methods --------------------------------------------- */
10470
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010471PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010472 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010473\n\
10474Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010475characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010476
10477static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010478unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010479{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480 return fixup(self, fixtitle);
10481}
10482
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010483PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010484 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010485\n\
10486Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010487have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010488
10489static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010490unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010491{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492 return fixup(self, fixcapitalize);
10493}
10494
10495#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010496PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010497 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010498\n\
10499Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010500normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010501
10502static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010503unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010504{
10505 PyObject *list;
10506 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010507 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010508
Guido van Rossumd57fd912000-03-10 22:53:23 +000010509 /* Split into words */
10510 list = split(self, NULL, -1);
10511 if (!list)
10512 return NULL;
10513
10514 /* Capitalize each word */
10515 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010516 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010517 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010518 if (item == NULL)
10519 goto onError;
10520 Py_DECREF(PyList_GET_ITEM(list, i));
10521 PyList_SET_ITEM(list, i, item);
10522 }
10523
10524 /* Join the words to form a new string */
10525 item = PyUnicode_Join(NULL, list);
10526
Benjamin Peterson29060642009-01-31 22:14:21 +000010527 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010528 Py_DECREF(list);
10529 return (PyObject *)item;
10530}
10531#endif
10532
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010533/* Argument converter. Coerces to a single unicode character */
10534
10535static int
10536convert_uc(PyObject *obj, void *addr)
10537{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010538 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010539 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010540
Benjamin Peterson14339b62009-01-31 16:36:08 +000010541 uniobj = PyUnicode_FromObject(obj);
10542 if (uniobj == NULL) {
10543 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010544 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010545 return 0;
10546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010547 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010548 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010549 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010550 Py_DECREF(uniobj);
10551 return 0;
10552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010554 Py_DECREF(uniobj);
10555 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010556}
10557
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010558PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010559 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010561Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010562done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563
10564static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010565unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010567 Py_ssize_t marg, left;
10568 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010569 Py_UCS4 fillchar = ' ';
10570
Victor Stinnere9a29352011-10-01 02:14:59 +020010571 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010573
Victor Stinnere9a29352011-10-01 02:14:59 +020010574 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010575 return NULL;
10576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010578 Py_INCREF(self);
10579 return (PyObject*) self;
10580 }
10581
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010582 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010583 left = marg / 2 + (marg & width & 1);
10584
Victor Stinner9310abb2011-10-05 00:59:23 +020010585 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010586}
10587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588/* This function assumes that str1 and str2 are readied by the caller. */
10589
Marc-André Lemburge5034372000-08-08 08:04:29 +000010590static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010591unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010593 int kind1, kind2;
10594 void *data1, *data2;
10595 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010597 kind1 = PyUnicode_KIND(str1);
10598 kind2 = PyUnicode_KIND(str2);
10599 data1 = PyUnicode_DATA(str1);
10600 data2 = PyUnicode_DATA(str2);
10601 len1 = PyUnicode_GET_LENGTH(str1);
10602 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010603
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010604 for (i = 0; i < len1 && i < len2; ++i) {
10605 Py_UCS4 c1, c2;
10606 c1 = PyUnicode_READ(kind1, data1, i);
10607 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010608
10609 if (c1 != c2)
10610 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010611 }
10612
10613 return (len1 < len2) ? -1 : (len1 != len2);
10614}
10615
Alexander Belopolsky40018472011-02-26 01:02:56 +000010616int
10617PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010618{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10620 if (PyUnicode_READY(left) == -1 ||
10621 PyUnicode_READY(right) == -1)
10622 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010623 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010625 PyErr_Format(PyExc_TypeError,
10626 "Can't compare %.100s and %.100s",
10627 left->ob_type->tp_name,
10628 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010629 return -1;
10630}
10631
Martin v. Löwis5b222132007-06-10 09:51:05 +000010632int
10633PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 Py_ssize_t i;
10636 int kind;
10637 void *data;
10638 Py_UCS4 chr;
10639
Victor Stinner910337b2011-10-03 03:20:16 +020010640 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 if (PyUnicode_READY(uni) == -1)
10642 return -1;
10643 kind = PyUnicode_KIND(uni);
10644 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010645 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10647 if (chr != str[i])
10648 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010649 /* This check keeps Python strings that end in '\0' from comparing equal
10650 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010652 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010653 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010654 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010655 return 0;
10656}
10657
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010658
Benjamin Peterson29060642009-01-31 22:14:21 +000010659#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010660 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010661
Alexander Belopolsky40018472011-02-26 01:02:56 +000010662PyObject *
10663PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010664{
10665 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010666
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010667 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10668 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 if (PyUnicode_READY(left) == -1 ||
10670 PyUnicode_READY(right) == -1)
10671 return NULL;
10672 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10673 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010674 if (op == Py_EQ) {
10675 Py_INCREF(Py_False);
10676 return Py_False;
10677 }
10678 if (op == Py_NE) {
10679 Py_INCREF(Py_True);
10680 return Py_True;
10681 }
10682 }
10683 if (left == right)
10684 result = 0;
10685 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010686 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010687
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010688 /* Convert the return value to a Boolean */
10689 switch (op) {
10690 case Py_EQ:
10691 v = TEST_COND(result == 0);
10692 break;
10693 case Py_NE:
10694 v = TEST_COND(result != 0);
10695 break;
10696 case Py_LE:
10697 v = TEST_COND(result <= 0);
10698 break;
10699 case Py_GE:
10700 v = TEST_COND(result >= 0);
10701 break;
10702 case Py_LT:
10703 v = TEST_COND(result == -1);
10704 break;
10705 case Py_GT:
10706 v = TEST_COND(result == 1);
10707 break;
10708 default:
10709 PyErr_BadArgument();
10710 return NULL;
10711 }
10712 Py_INCREF(v);
10713 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010714 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010715
Brian Curtindfc80e32011-08-10 20:28:54 -050010716 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010717}
10718
Alexander Belopolsky40018472011-02-26 01:02:56 +000010719int
10720PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010721{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010722 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010723 int kind1, kind2, kind;
10724 void *buf1, *buf2;
10725 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010726 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010727
10728 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010729 sub = PyUnicode_FromObject(element);
10730 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010731 PyErr_Format(PyExc_TypeError,
10732 "'in <string>' requires string as left operand, not %s",
10733 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010734 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010735 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010736 if (PyUnicode_READY(sub) == -1)
10737 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010738
Thomas Wouters477c8d52006-05-27 19:21:47 +000010739 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010740 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010741 Py_DECREF(sub);
10742 return -1;
10743 }
10744
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010745 kind1 = PyUnicode_KIND(str);
10746 kind2 = PyUnicode_KIND(sub);
10747 kind = kind1 > kind2 ? kind1 : kind2;
10748 buf1 = PyUnicode_DATA(str);
10749 buf2 = PyUnicode_DATA(sub);
10750 if (kind1 != kind)
10751 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10752 if (!buf1) {
10753 Py_DECREF(sub);
10754 return -1;
10755 }
10756 if (kind2 != kind)
10757 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10758 if (!buf2) {
10759 Py_DECREF(sub);
10760 if (kind1 != kind) PyMem_Free(buf1);
10761 return -1;
10762 }
10763 len1 = PyUnicode_GET_LENGTH(str);
10764 len2 = PyUnicode_GET_LENGTH(sub);
10765
10766 switch(kind) {
10767 case PyUnicode_1BYTE_KIND:
10768 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10769 break;
10770 case PyUnicode_2BYTE_KIND:
10771 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10772 break;
10773 case PyUnicode_4BYTE_KIND:
10774 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10775 break;
10776 default:
10777 result = -1;
10778 assert(0);
10779 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010780
10781 Py_DECREF(str);
10782 Py_DECREF(sub);
10783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 if (kind1 != kind)
10785 PyMem_Free(buf1);
10786 if (kind2 != kind)
10787 PyMem_Free(buf2);
10788
Guido van Rossum403d68b2000-03-13 15:55:09 +000010789 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010790}
10791
Guido van Rossumd57fd912000-03-10 22:53:23 +000010792/* Concat to string or Unicode object giving a new Unicode object. */
10793
Alexander Belopolsky40018472011-02-26 01:02:56 +000010794PyObject *
10795PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010797 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010798 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799
10800 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010802 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010803 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010806 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807
10808 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010809 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010810 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010811 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010813 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010814 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010816 }
10817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010818 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010819 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10820 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010821
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010823 w = PyUnicode_New(
10824 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10825 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010826 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010827 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010828 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10829 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830 Py_DECREF(u);
10831 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010832 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010833 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010834
Benjamin Peterson29060642009-01-31 22:14:21 +000010835 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010836 Py_XDECREF(u);
10837 Py_XDECREF(v);
10838 return NULL;
10839}
10840
Victor Stinnerb0923652011-10-04 01:17:31 +020010841static void
10842unicode_append_inplace(PyObject **p_left, PyObject *right)
10843{
10844 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010845
10846 assert(PyUnicode_IS_READY(*p_left));
10847 assert(PyUnicode_IS_READY(right));
10848
10849 left_len = PyUnicode_GET_LENGTH(*p_left);
10850 right_len = PyUnicode_GET_LENGTH(right);
10851 if (left_len > PY_SSIZE_T_MAX - right_len) {
10852 PyErr_SetString(PyExc_OverflowError,
10853 "strings are too large to concat");
10854 goto error;
10855 }
10856 new_len = left_len + right_len;
10857
10858 /* Now we own the last reference to 'left', so we can resize it
10859 * in-place.
10860 */
10861 if (unicode_resize(p_left, new_len) != 0) {
10862 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10863 * deallocated so it cannot be put back into
10864 * 'variable'. The MemoryError is raised when there
10865 * is no value in 'variable', which might (very
10866 * remotely) be a cause of incompatibilities.
10867 */
10868 goto error;
10869 }
10870 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010871 copy_characters(*p_left, left_len, right, 0, right_len);
10872 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010873 return;
10874
10875error:
10876 Py_DECREF(*p_left);
10877 *p_left = NULL;
10878}
10879
Walter Dörwald1ab83302007-05-18 17:15:44 +000010880void
Victor Stinner23e56682011-10-03 03:54:37 +020010881PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010882{
Victor Stinner23e56682011-10-03 03:54:37 +020010883 PyObject *left, *res;
10884
10885 if (p_left == NULL) {
10886 if (!PyErr_Occurred())
10887 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010888 return;
10889 }
Victor Stinner23e56682011-10-03 03:54:37 +020010890 left = *p_left;
10891 if (right == NULL || !PyUnicode_Check(left)) {
10892 if (!PyErr_Occurred())
10893 PyErr_BadInternalCall();
10894 goto error;
10895 }
10896
Victor Stinnere1335c72011-10-04 20:53:03 +020010897 if (PyUnicode_READY(left))
10898 goto error;
10899 if (PyUnicode_READY(right))
10900 goto error;
10901
Victor Stinner23e56682011-10-03 03:54:37 +020010902 if (PyUnicode_CheckExact(left) && left != unicode_empty
10903 && PyUnicode_CheckExact(right) && right != unicode_empty
10904 && unicode_resizable(left)
10905 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10906 || _PyUnicode_WSTR(left) != NULL))
10907 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010908 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10909 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010910 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010911 not so different than duplicating the string. */
10912 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010913 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010914 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010915 if (p_left != NULL)
10916 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010917 return;
10918 }
10919 }
10920
10921 res = PyUnicode_Concat(left, right);
10922 if (res == NULL)
10923 goto error;
10924 Py_DECREF(left);
10925 *p_left = res;
10926 return;
10927
10928error:
10929 Py_DECREF(*p_left);
10930 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010931}
10932
10933void
10934PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10935{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010936 PyUnicode_Append(pleft, right);
10937 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010938}
10939
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010940PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010941 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010943Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010944string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010945interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010946
10947static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010948unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010949{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010950 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010951 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010952 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010953 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010954 int kind1, kind2, kind;
10955 void *buf1, *buf2;
10956 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957
Jesus Ceaac451502011-04-20 17:09:23 +020010958 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10959 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010960 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010961
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010962 kind1 = PyUnicode_KIND(self);
10963 kind2 = PyUnicode_KIND(substring);
10964 kind = kind1 > kind2 ? kind1 : kind2;
10965 buf1 = PyUnicode_DATA(self);
10966 buf2 = PyUnicode_DATA(substring);
10967 if (kind1 != kind)
10968 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10969 if (!buf1) {
10970 Py_DECREF(substring);
10971 return NULL;
10972 }
10973 if (kind2 != kind)
10974 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10975 if (!buf2) {
10976 Py_DECREF(substring);
10977 if (kind1 != kind) PyMem_Free(buf1);
10978 return NULL;
10979 }
10980 len1 = PyUnicode_GET_LENGTH(self);
10981 len2 = PyUnicode_GET_LENGTH(substring);
10982
10983 ADJUST_INDICES(start, end, len1);
10984 switch(kind) {
10985 case PyUnicode_1BYTE_KIND:
10986 iresult = ucs1lib_count(
10987 ((Py_UCS1*)buf1) + start, end - start,
10988 buf2, len2, PY_SSIZE_T_MAX
10989 );
10990 break;
10991 case PyUnicode_2BYTE_KIND:
10992 iresult = ucs2lib_count(
10993 ((Py_UCS2*)buf1) + start, end - start,
10994 buf2, len2, PY_SSIZE_T_MAX
10995 );
10996 break;
10997 case PyUnicode_4BYTE_KIND:
10998 iresult = ucs4lib_count(
10999 ((Py_UCS4*)buf1) + start, end - start,
11000 buf2, len2, PY_SSIZE_T_MAX
11001 );
11002 break;
11003 default:
11004 assert(0); iresult = 0;
11005 }
11006
11007 result = PyLong_FromSsize_t(iresult);
11008
11009 if (kind1 != kind)
11010 PyMem_Free(buf1);
11011 if (kind2 != kind)
11012 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013
11014 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011015
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 return result;
11017}
11018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011019PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011020 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011022Encode S using the codec registered for encoding. Default encoding\n\
11023is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011024handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011025a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11026'xmlcharrefreplace' as well as any other name registered with\n\
11027codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028
11029static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011030unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011032 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033 char *encoding = NULL;
11034 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011035
Benjamin Peterson308d6372009-09-18 21:42:35 +000011036 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11037 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011039 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011040}
11041
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011042PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011043 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044\n\
11045Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011046If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047
11048static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011049unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011051 Py_ssize_t i, j, line_pos, src_len, incr;
11052 Py_UCS4 ch;
11053 PyObject *u;
11054 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011056 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011057 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011058
11059 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011060 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011061
Antoine Pitrou22425222011-10-04 19:10:51 +020011062 if (PyUnicode_READY(self) == -1)
11063 return NULL;
11064
Thomas Wouters7e474022000-07-16 12:04:32 +000011065 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011066 src_len = PyUnicode_GET_LENGTH(self);
11067 i = j = line_pos = 0;
11068 kind = PyUnicode_KIND(self);
11069 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011070 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011071 for (; i < src_len; i++) {
11072 ch = PyUnicode_READ(kind, src_data, i);
11073 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011074 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011075 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011076 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011077 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011078 goto overflow;
11079 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011080 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011081 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011082 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011084 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011085 goto overflow;
11086 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011088 if (ch == '\n' || ch == '\r')
11089 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011091 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011092 if (!found && PyUnicode_CheckExact(self)) {
11093 Py_INCREF((PyObject *) self);
11094 return (PyObject *) self;
11095 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011096
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011098 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011099 if (!u)
11100 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011101 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011102
Antoine Pitroue71d5742011-10-04 15:55:09 +020011103 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104
Antoine Pitroue71d5742011-10-04 15:55:09 +020011105 for (; i < src_len; i++) {
11106 ch = PyUnicode_READ(kind, src_data, i);
11107 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011108 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011109 incr = tabsize - (line_pos % tabsize);
11110 line_pos += incr;
11111 while (incr--) {
11112 PyUnicode_WRITE(kind, dest_data, j, ' ');
11113 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011114 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011115 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011116 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011117 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011118 line_pos++;
11119 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011120 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011121 if (ch == '\n' || ch == '\r')
11122 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011124 }
11125 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011126#ifndef DONT_MAKE_RESULT_READY
11127 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011128 Py_DECREF(u);
11129 return NULL;
11130 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011131#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011132 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011134
Antoine Pitroue71d5742011-10-04 15:55:09 +020011135 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011136 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11137 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138}
11139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011140PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011141 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142\n\
11143Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011144such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011145arguments start and end are interpreted as in slice notation.\n\
11146\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011147Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011148
11149static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011152 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011153 Py_ssize_t start;
11154 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011155 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156
Jesus Ceaac451502011-04-20 17:09:23 +020011157 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11158 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011161 if (PyUnicode_READY(self) == -1)
11162 return NULL;
11163 if (PyUnicode_READY(substring) == -1)
11164 return NULL;
11165
Victor Stinner794d5672011-10-10 03:21:36 +020011166 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011168 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169
11170 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011171
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011172 if (result == -2)
11173 return NULL;
11174
Christian Heimes217cfd12007-12-02 14:31:20 +000011175 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176}
11177
11178static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011179unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011180{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011181 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11182 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011184 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185}
11186
Guido van Rossumc2504932007-09-18 19:42:40 +000011187/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011188 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011189static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011190unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191{
Guido van Rossumc2504932007-09-18 19:42:40 +000011192 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011193 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011195 if (_PyUnicode_HASH(self) != -1)
11196 return _PyUnicode_HASH(self);
11197 if (PyUnicode_READY(self) == -1)
11198 return -1;
11199 len = PyUnicode_GET_LENGTH(self);
11200
11201 /* The hash function as a macro, gets expanded three times below. */
11202#define HASH(P) \
11203 x = (Py_uhash_t)*P << 7; \
11204 while (--len >= 0) \
11205 x = (1000003*x) ^ (Py_uhash_t)*P++;
11206
11207 switch (PyUnicode_KIND(self)) {
11208 case PyUnicode_1BYTE_KIND: {
11209 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11210 HASH(c);
11211 break;
11212 }
11213 case PyUnicode_2BYTE_KIND: {
11214 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11215 HASH(s);
11216 break;
11217 }
11218 default: {
11219 Py_UCS4 *l;
11220 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11221 "Impossible switch case in unicode_hash");
11222 l = PyUnicode_4BYTE_DATA(self);
11223 HASH(l);
11224 break;
11225 }
11226 }
11227 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11228
Guido van Rossumc2504932007-09-18 19:42:40 +000011229 if (x == -1)
11230 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011232 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011233}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011236PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011237 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011238\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011239Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240
11241static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011243{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011244 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011245 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011246 Py_ssize_t start;
11247 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011248
Jesus Ceaac451502011-04-20 17:09:23 +020011249 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11250 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 if (PyUnicode_READY(self) == -1)
11254 return NULL;
11255 if (PyUnicode_READY(substring) == -1)
11256 return NULL;
11257
Victor Stinner794d5672011-10-10 03:21:36 +020011258 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011259 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011260 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261
11262 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 if (result == -2)
11265 return NULL;
11266
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267 if (result < 0) {
11268 PyErr_SetString(PyExc_ValueError, "substring not found");
11269 return NULL;
11270 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011271
Christian Heimes217cfd12007-12-02 14:31:20 +000011272 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011273}
11274
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011275PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011276 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011278Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011279at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011280
11281static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011282unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 Py_ssize_t i, length;
11285 int kind;
11286 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287 int cased;
11288
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 if (PyUnicode_READY(self) == -1)
11290 return NULL;
11291 length = PyUnicode_GET_LENGTH(self);
11292 kind = PyUnicode_KIND(self);
11293 data = PyUnicode_DATA(self);
11294
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011296 if (length == 1)
11297 return PyBool_FromLong(
11298 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011299
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011300 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011301 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011302 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011303
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 for (i = 0; i < length; i++) {
11306 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011307
Benjamin Peterson29060642009-01-31 22:14:21 +000011308 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11309 return PyBool_FromLong(0);
11310 else if (!cased && Py_UNICODE_ISLOWER(ch))
11311 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011313 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314}
11315
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011316PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011317 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011319Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011320at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011321
11322static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011323unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 Py_ssize_t i, length;
11326 int kind;
11327 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328 int cased;
11329
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 if (PyUnicode_READY(self) == -1)
11331 return NULL;
11332 length = PyUnicode_GET_LENGTH(self);
11333 kind = PyUnicode_KIND(self);
11334 data = PyUnicode_DATA(self);
11335
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 if (length == 1)
11338 return PyBool_FromLong(
11339 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011341 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011342 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011343 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011344
Guido van Rossumd57fd912000-03-10 22:53:23 +000011345 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 for (i = 0; i < length; i++) {
11347 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011348
Benjamin Peterson29060642009-01-31 22:14:21 +000011349 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11350 return PyBool_FromLong(0);
11351 else if (!cased && Py_UNICODE_ISUPPER(ch))
11352 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011353 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011354 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355}
11356
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011357PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011359\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011360Return True if S is a titlecased string and there is at least one\n\
11361character in S, i.e. upper- and titlecase characters may only\n\
11362follow uncased characters and lowercase characters only cased ones.\n\
11363Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011364
11365static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011366unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011368 Py_ssize_t i, length;
11369 int kind;
11370 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011371 int cased, previous_is_cased;
11372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 if (PyUnicode_READY(self) == -1)
11374 return NULL;
11375 length = PyUnicode_GET_LENGTH(self);
11376 kind = PyUnicode_KIND(self);
11377 data = PyUnicode_DATA(self);
11378
Guido van Rossumd57fd912000-03-10 22:53:23 +000011379 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011380 if (length == 1) {
11381 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11382 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11383 (Py_UNICODE_ISUPPER(ch) != 0));
11384 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011386 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011388 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011389
Guido van Rossumd57fd912000-03-10 22:53:23 +000011390 cased = 0;
11391 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 for (i = 0; i < length; i++) {
11393 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011394
Benjamin Peterson29060642009-01-31 22:14:21 +000011395 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11396 if (previous_is_cased)
11397 return PyBool_FromLong(0);
11398 previous_is_cased = 1;
11399 cased = 1;
11400 }
11401 else if (Py_UNICODE_ISLOWER(ch)) {
11402 if (!previous_is_cased)
11403 return PyBool_FromLong(0);
11404 previous_is_cased = 1;
11405 cased = 1;
11406 }
11407 else
11408 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011410 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411}
11412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011413PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011414 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011416Return True if all characters in S are whitespace\n\
11417and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418
11419static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011420unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 Py_ssize_t i, length;
11423 int kind;
11424 void *data;
11425
11426 if (PyUnicode_READY(self) == -1)
11427 return NULL;
11428 length = PyUnicode_GET_LENGTH(self);
11429 kind = PyUnicode_KIND(self);
11430 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011433 if (length == 1)
11434 return PyBool_FromLong(
11435 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011437 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 for (i = 0; i < length; i++) {
11442 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011443 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011445 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011446 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447}
11448
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011449PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011450 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011451\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011452Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011453and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011454
11455static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011456unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011457{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 Py_ssize_t i, length;
11459 int kind;
11460 void *data;
11461
11462 if (PyUnicode_READY(self) == -1)
11463 return NULL;
11464 length = PyUnicode_GET_LENGTH(self);
11465 kind = PyUnicode_KIND(self);
11466 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011467
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011468 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (length == 1)
11470 return PyBool_FromLong(
11471 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011472
11473 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011475 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011476
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 for (i = 0; i < length; i++) {
11478 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011479 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011480 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011481 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011482}
11483
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011484PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011486\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011487Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011488and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011489
11490static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011491unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011492{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011493 int kind;
11494 void *data;
11495 Py_ssize_t len, i;
11496
11497 if (PyUnicode_READY(self) == -1)
11498 return NULL;
11499
11500 kind = PyUnicode_KIND(self);
11501 data = PyUnicode_DATA(self);
11502 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011503
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011504 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011505 if (len == 1) {
11506 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11507 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11508 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011509
11510 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011513
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 for (i = 0; i < len; i++) {
11515 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011516 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011518 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011519 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011520}
11521
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011522PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011523 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011525Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011526False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527
11528static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011529unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011530{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 Py_ssize_t i, length;
11532 int kind;
11533 void *data;
11534
11535 if (PyUnicode_READY(self) == -1)
11536 return NULL;
11537 length = PyUnicode_GET_LENGTH(self);
11538 kind = PyUnicode_KIND(self);
11539 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011540
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011542 if (length == 1)
11543 return PyBool_FromLong(
11544 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011546 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011548 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011549
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 for (i = 0; i < length; i++) {
11551 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011552 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011554 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555}
11556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011557PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011558 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011560Return True if all characters in S are digits\n\
11561and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562
11563static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011564unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 Py_ssize_t i, length;
11567 int kind;
11568 void *data;
11569
11570 if (PyUnicode_READY(self) == -1)
11571 return NULL;
11572 length = PyUnicode_GET_LENGTH(self);
11573 kind = PyUnicode_KIND(self);
11574 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
Guido van Rossumd57fd912000-03-10 22:53:23 +000011576 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011577 if (length == 1) {
11578 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11579 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11580 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011582 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011583 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011584 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011585
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 for (i = 0; i < length; i++) {
11587 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011588 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011590 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011591}
11592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011593PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011594 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011596Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011597False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598
11599static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011600unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 Py_ssize_t i, length;
11603 int kind;
11604 void *data;
11605
11606 if (PyUnicode_READY(self) == -1)
11607 return NULL;
11608 length = PyUnicode_GET_LENGTH(self);
11609 kind = PyUnicode_KIND(self);
11610 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611
Guido van Rossumd57fd912000-03-10 22:53:23 +000011612 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011613 if (length == 1)
11614 return PyBool_FromLong(
11615 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011616
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011617 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011618 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011619 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011621 for (i = 0; i < length; i++) {
11622 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011623 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011625 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011626}
11627
Martin v. Löwis47383402007-08-15 07:32:56 +000011628int
11629PyUnicode_IsIdentifier(PyObject *self)
11630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011631 int kind;
11632 void *data;
11633 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011634 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011636 if (PyUnicode_READY(self) == -1) {
11637 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011638 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 }
11640
11641 /* Special case for empty strings */
11642 if (PyUnicode_GET_LENGTH(self) == 0)
11643 return 0;
11644 kind = PyUnicode_KIND(self);
11645 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011646
11647 /* PEP 3131 says that the first character must be in
11648 XID_Start and subsequent characters in XID_Continue,
11649 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011650 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011651 letters, digits, underscore). However, given the current
11652 definition of XID_Start and XID_Continue, it is sufficient
11653 to check just for these, except that _ must be allowed
11654 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011655 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011656 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011657 return 0;
11658
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011659 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011660 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011662 return 1;
11663}
11664
11665PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011666 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011667\n\
11668Return True if S is a valid identifier according\n\
11669to the language definition.");
11670
11671static PyObject*
11672unicode_isidentifier(PyObject *self)
11673{
11674 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11675}
11676
Georg Brandl559e5d72008-06-11 18:37:52 +000011677PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011678 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011679\n\
11680Return True if all characters in S are considered\n\
11681printable in repr() or S is empty, False otherwise.");
11682
11683static PyObject*
11684unicode_isprintable(PyObject *self)
11685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011686 Py_ssize_t i, length;
11687 int kind;
11688 void *data;
11689
11690 if (PyUnicode_READY(self) == -1)
11691 return NULL;
11692 length = PyUnicode_GET_LENGTH(self);
11693 kind = PyUnicode_KIND(self);
11694 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011695
11696 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 if (length == 1)
11698 return PyBool_FromLong(
11699 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011701 for (i = 0; i < length; i++) {
11702 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011703 Py_RETURN_FALSE;
11704 }
11705 }
11706 Py_RETURN_TRUE;
11707}
11708
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011709PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011710 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711\n\
11712Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011713iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714
11715static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011716unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011718 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719}
11720
Martin v. Löwis18e16552006-02-15 17:27:45 +000011721static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011722unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011724 if (PyUnicode_READY(self) == -1)
11725 return -1;
11726 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011727}
11728
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011729PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011730 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011732Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011733done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011734
11735static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011736unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011738 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011739 Py_UCS4 fillchar = ' ';
11740
11741 if (PyUnicode_READY(self) == -1)
11742 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011743
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011744 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745 return NULL;
11746
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011747 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011748 Py_INCREF(self);
11749 return (PyObject*) self;
11750 }
11751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011753}
11754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011755PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011758Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011759
11760static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011761unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011762{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011763 return fixup(self, fixlower);
11764}
11765
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766#define LEFTSTRIP 0
11767#define RIGHTSTRIP 1
11768#define BOTHSTRIP 2
11769
11770/* Arrays indexed by above */
11771static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11772
11773#define STRIPNAME(i) (stripformat[i]+3)
11774
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775/* externally visible for str.strip(unicode) */
11776PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011777_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 void *data;
11780 int kind;
11781 Py_ssize_t i, j, len;
11782 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011784 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11785 return NULL;
11786
11787 kind = PyUnicode_KIND(self);
11788 data = PyUnicode_DATA(self);
11789 len = PyUnicode_GET_LENGTH(self);
11790 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11791 PyUnicode_DATA(sepobj),
11792 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011793
Benjamin Peterson14339b62009-01-31 16:36:08 +000011794 i = 0;
11795 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011796 while (i < len &&
11797 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011798 i++;
11799 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011800 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011801
Benjamin Peterson14339b62009-01-31 16:36:08 +000011802 j = len;
11803 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011804 do {
11805 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 } while (j >= i &&
11807 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011808 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011809 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011810
Victor Stinner12bab6d2011-10-01 01:53:49 +020011811 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812}
11813
11814PyObject*
11815PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11816{
11817 unsigned char *data;
11818 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011819 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011820
Victor Stinnerde636f32011-10-01 03:55:54 +020011821 if (PyUnicode_READY(self) == -1)
11822 return NULL;
11823
11824 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11825
Victor Stinner12bab6d2011-10-01 01:53:49 +020011826 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011827 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011828 if (PyUnicode_CheckExact(self)) {
11829 Py_INCREF(self);
11830 return self;
11831 }
11832 else
11833 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011834 }
11835
Victor Stinner12bab6d2011-10-01 01:53:49 +020011836 length = end - start;
11837 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011838 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011839
Victor Stinnerde636f32011-10-01 03:55:54 +020011840 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011841 PyErr_SetString(PyExc_IndexError, "string index out of range");
11842 return NULL;
11843 }
11844
Victor Stinnerb9275c12011-10-05 14:01:42 +020011845 if (PyUnicode_IS_ASCII(self)) {
11846 kind = PyUnicode_KIND(self);
11847 data = PyUnicode_1BYTE_DATA(self);
11848 return unicode_fromascii(data + start, length);
11849 }
11850 else {
11851 kind = PyUnicode_KIND(self);
11852 data = PyUnicode_1BYTE_DATA(self);
11853 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011854 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011855 length);
11856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011858
11859static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011860do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 int kind;
11863 void *data;
11864 Py_ssize_t len, i, j;
11865
11866 if (PyUnicode_READY(self) == -1)
11867 return NULL;
11868
11869 kind = PyUnicode_KIND(self);
11870 data = PyUnicode_DATA(self);
11871 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011872
Benjamin Peterson14339b62009-01-31 16:36:08 +000011873 i = 0;
11874 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011876 i++;
11877 }
11878 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011879
Benjamin Peterson14339b62009-01-31 16:36:08 +000011880 j = len;
11881 if (striptype != LEFTSTRIP) {
11882 do {
11883 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011885 j++;
11886 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011887
Victor Stinner12bab6d2011-10-01 01:53:49 +020011888 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011889}
11890
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011891
11892static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011893do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011894{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011895 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011896
Benjamin Peterson14339b62009-01-31 16:36:08 +000011897 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11898 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011899
Benjamin Peterson14339b62009-01-31 16:36:08 +000011900 if (sep != NULL && sep != Py_None) {
11901 if (PyUnicode_Check(sep))
11902 return _PyUnicode_XStrip(self, striptype, sep);
11903 else {
11904 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011905 "%s arg must be None or str",
11906 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011907 return NULL;
11908 }
11909 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011910
Benjamin Peterson14339b62009-01-31 16:36:08 +000011911 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011912}
11913
11914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011915PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011917\n\
11918Return a copy of the string S with leading and trailing\n\
11919whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011920If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011921
11922static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011923unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011924{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011925 if (PyTuple_GET_SIZE(args) == 0)
11926 return do_strip(self, BOTHSTRIP); /* Common case */
11927 else
11928 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011929}
11930
11931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011932PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011933 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934\n\
11935Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011936If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011937
11938static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011939unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011940{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011941 if (PyTuple_GET_SIZE(args) == 0)
11942 return do_strip(self, LEFTSTRIP); /* Common case */
11943 else
11944 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011945}
11946
11947
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011948PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011949 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011950\n\
11951Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011952If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011953
11954static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011955unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011956{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011957 if (PyTuple_GET_SIZE(args) == 0)
11958 return do_strip(self, RIGHTSTRIP); /* Common case */
11959 else
11960 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011961}
11962
11963
Guido van Rossumd57fd912000-03-10 22:53:23 +000011964static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011965unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011967 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011968 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969
Georg Brandl222de0f2009-04-12 12:01:50 +000011970 if (len < 1) {
11971 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011972 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011973 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011974
Tim Peters7a29bd52001-09-12 03:03:31 +000011975 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976 /* no repeat, return original string */
11977 Py_INCREF(str);
11978 return (PyObject*) str;
11979 }
Tim Peters8f422462000-09-09 06:13:41 +000011980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 if (PyUnicode_READY(str) == -1)
11982 return NULL;
11983
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011984 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011985 PyErr_SetString(PyExc_OverflowError,
11986 "repeated string is too long");
11987 return NULL;
11988 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011990
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011991 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992 if (!u)
11993 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011994 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011995
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011996 if (PyUnicode_GET_LENGTH(str) == 1) {
11997 const int kind = PyUnicode_KIND(str);
11998 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11999 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020012000 if (kind == PyUnicode_1BYTE_KIND)
12001 memset(to, (unsigned char)fill_char, len);
12002 else {
12003 for (n = 0; n < len; ++n)
12004 PyUnicode_WRITE(kind, to, n, fill_char);
12005 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012006 }
12007 else {
12008 /* number of characters copied this far */
12009 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012010 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 char *to = (char *) PyUnicode_DATA(u);
12012 Py_MEMCPY(to, PyUnicode_DATA(str),
12013 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000012014 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 n = (done <= nchars-done) ? done : nchars-done;
12016 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012017 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012018 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012019 }
12020
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012021 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012022 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023}
12024
Alexander Belopolsky40018472011-02-26 01:02:56 +000012025PyObject *
12026PyUnicode_Replace(PyObject *obj,
12027 PyObject *subobj,
12028 PyObject *replobj,
12029 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012030{
12031 PyObject *self;
12032 PyObject *str1;
12033 PyObject *str2;
12034 PyObject *result;
12035
12036 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012037 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012038 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012040 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012041 Py_DECREF(self);
12042 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043 }
12044 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012045 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012046 Py_DECREF(self);
12047 Py_DECREF(str1);
12048 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012051 Py_DECREF(self);
12052 Py_DECREF(str1);
12053 Py_DECREF(str2);
12054 return result;
12055}
12056
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012057PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012058 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012059\n\
12060Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012061old replaced by new. If the optional argument count is\n\
12062given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012063
12064static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012065unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012066{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 PyObject *str1;
12068 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012069 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012070 PyObject *result;
12071
Martin v. Löwis18e16552006-02-15 17:27:45 +000012072 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012073 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012075 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012076 str1 = PyUnicode_FromObject(str1);
12077 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12078 return NULL;
12079 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012080 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012081 Py_DECREF(str1);
12082 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012083 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084
12085 result = replace(self, str1, str2, maxcount);
12086
12087 Py_DECREF(str1);
12088 Py_DECREF(str2);
12089 return result;
12090}
12091
Alexander Belopolsky40018472011-02-26 01:02:56 +000012092static PyObject *
12093unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012094{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012095 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012096 Py_ssize_t isize;
12097 Py_ssize_t osize, squote, dquote, i, o;
12098 Py_UCS4 max, quote;
12099 int ikind, okind;
12100 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012101
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012102 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012103 return NULL;
12104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012105 isize = PyUnicode_GET_LENGTH(unicode);
12106 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012107
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012108 /* Compute length of output, quote characters, and
12109 maximum character */
12110 osize = 2; /* quotes */
12111 max = 127;
12112 squote = dquote = 0;
12113 ikind = PyUnicode_KIND(unicode);
12114 for (i = 0; i < isize; i++) {
12115 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12116 switch (ch) {
12117 case '\'': squote++; osize++; break;
12118 case '"': dquote++; osize++; break;
12119 case '\\': case '\t': case '\r': case '\n':
12120 osize += 2; break;
12121 default:
12122 /* Fast-path ASCII */
12123 if (ch < ' ' || ch == 0x7f)
12124 osize += 4; /* \xHH */
12125 else if (ch < 0x7f)
12126 osize++;
12127 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12128 osize++;
12129 max = ch > max ? ch : max;
12130 }
12131 else if (ch < 0x100)
12132 osize += 4; /* \xHH */
12133 else if (ch < 0x10000)
12134 osize += 6; /* \uHHHH */
12135 else
12136 osize += 10; /* \uHHHHHHHH */
12137 }
12138 }
12139
12140 quote = '\'';
12141 if (squote) {
12142 if (dquote)
12143 /* Both squote and dquote present. Use squote,
12144 and escape them */
12145 osize += squote;
12146 else
12147 quote = '"';
12148 }
12149
12150 repr = PyUnicode_New(osize, max);
12151 if (repr == NULL)
12152 return NULL;
12153 okind = PyUnicode_KIND(repr);
12154 odata = PyUnicode_DATA(repr);
12155
12156 PyUnicode_WRITE(okind, odata, 0, quote);
12157 PyUnicode_WRITE(okind, odata, osize-1, quote);
12158
12159 for (i = 0, o = 1; i < isize; i++) {
12160 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012161
12162 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 if ((ch == quote) || (ch == '\\')) {
12164 PyUnicode_WRITE(okind, odata, o++, '\\');
12165 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012166 continue;
12167 }
12168
Benjamin Peterson29060642009-01-31 22:14:21 +000012169 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012170 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012171 PyUnicode_WRITE(okind, odata, o++, '\\');
12172 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012173 }
12174 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012175 PyUnicode_WRITE(okind, odata, o++, '\\');
12176 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012177 }
12178 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012179 PyUnicode_WRITE(okind, odata, o++, '\\');
12180 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012181 }
12182
12183 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012184 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 PyUnicode_WRITE(okind, odata, o++, '\\');
12186 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012187 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12188 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012189 }
12190
Georg Brandl559e5d72008-06-11 18:37:52 +000012191 /* Copy ASCII characters as-is */
12192 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012194 }
12195
Benjamin Peterson29060642009-01-31 22:14:21 +000012196 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012197 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012198 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012199 (categories Z* and C* except ASCII space)
12200 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012201 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012202 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012203 if (ch <= 0xff) {
12204 PyUnicode_WRITE(okind, odata, o++, '\\');
12205 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012206 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12207 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012208 }
12209 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012210 else if (ch >= 0x10000) {
12211 PyUnicode_WRITE(okind, odata, o++, '\\');
12212 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012213 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12214 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12215 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12216 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12217 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12218 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12219 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12220 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012221 }
12222 /* Map 16-bit characters to '\uxxxx' */
12223 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012224 PyUnicode_WRITE(okind, odata, o++, '\\');
12225 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012226 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12227 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12228 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12229 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012230 }
12231 }
12232 /* Copy characters as-is */
12233 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012234 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012235 }
12236 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012238 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012239 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012240 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012241}
12242
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012243PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012244 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012245\n\
12246Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012247such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248arguments start and end are interpreted as in slice notation.\n\
12249\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012250Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012251
12252static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012255 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012256 Py_ssize_t start;
12257 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012258 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
Jesus Ceaac451502011-04-20 17:09:23 +020012260 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12261 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012262 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012264 if (PyUnicode_READY(self) == -1)
12265 return NULL;
12266 if (PyUnicode_READY(substring) == -1)
12267 return NULL;
12268
Victor Stinner794d5672011-10-10 03:21:36 +020012269 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012271 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272
12273 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012274
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012275 if (result == -2)
12276 return NULL;
12277
Christian Heimes217cfd12007-12-02 14:31:20 +000012278 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279}
12280
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012281PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012282 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012283\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012284Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285
12286static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012288{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012289 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012290 Py_ssize_t start;
12291 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012293
Jesus Ceaac451502011-04-20 17:09:23 +020012294 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12295 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012296 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012298 if (PyUnicode_READY(self) == -1)
12299 return NULL;
12300 if (PyUnicode_READY(substring) == -1)
12301 return NULL;
12302
Victor Stinner794d5672011-10-10 03:21:36 +020012303 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012304 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012305 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306
12307 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012309 if (result == -2)
12310 return NULL;
12311
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312 if (result < 0) {
12313 PyErr_SetString(PyExc_ValueError, "substring not found");
12314 return NULL;
12315 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316
Christian Heimes217cfd12007-12-02 14:31:20 +000012317 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012318}
12319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012320PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012321 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012323Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012324done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012325
12326static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012327unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012329 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 Py_UCS4 fillchar = ' ';
12331
Victor Stinnere9a29352011-10-01 02:14:59 +020012332 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012334
Victor Stinnere9a29352011-10-01 02:14:59 +020012335 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012336 return NULL;
12337
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012338 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012339 Py_INCREF(self);
12340 return (PyObject*) self;
12341 }
12342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344}
12345
Alexander Belopolsky40018472011-02-26 01:02:56 +000012346PyObject *
12347PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012348{
12349 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012350
Guido van Rossumd57fd912000-03-10 22:53:23 +000012351 s = PyUnicode_FromObject(s);
12352 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012353 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012354 if (sep != NULL) {
12355 sep = PyUnicode_FromObject(sep);
12356 if (sep == NULL) {
12357 Py_DECREF(s);
12358 return NULL;
12359 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360 }
12361
Victor Stinner9310abb2011-10-05 00:59:23 +020012362 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363
12364 Py_DECREF(s);
12365 Py_XDECREF(sep);
12366 return result;
12367}
12368
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012369PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012370 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012371\n\
12372Return a list of the words in S, using sep as the\n\
12373delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012374splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012375whitespace string is a separator and empty strings are\n\
12376removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377
12378static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012379unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012380{
12381 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012382 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012383
Martin v. Löwis18e16552006-02-15 17:27:45 +000012384 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012385 return NULL;
12386
12387 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012388 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012389 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012390 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012391 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012392 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012393}
12394
Thomas Wouters477c8d52006-05-27 19:21:47 +000012395PyObject *
12396PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12397{
12398 PyObject* str_obj;
12399 PyObject* sep_obj;
12400 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 int kind1, kind2, kind;
12402 void *buf1 = NULL, *buf2 = NULL;
12403 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404
12405 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012406 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012407 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012408 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012409 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410 Py_DECREF(str_obj);
12411 return NULL;
12412 }
12413
Victor Stinner14f8f022011-10-05 20:58:25 +020012414 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012416 kind = Py_MAX(kind1, kind2);
12417 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012419 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 if (!buf1)
12421 goto onError;
12422 buf2 = PyUnicode_DATA(sep_obj);
12423 if (kind2 != kind)
12424 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12425 if (!buf2)
12426 goto onError;
12427 len1 = PyUnicode_GET_LENGTH(str_obj);
12428 len2 = PyUnicode_GET_LENGTH(sep_obj);
12429
Victor Stinner14f8f022011-10-05 20:58:25 +020012430 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012431 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012432 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12433 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12434 else
12435 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012436 break;
12437 case PyUnicode_2BYTE_KIND:
12438 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12439 break;
12440 case PyUnicode_4BYTE_KIND:
12441 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12442 break;
12443 default:
12444 assert(0);
12445 out = 0;
12446 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447
12448 Py_DECREF(sep_obj);
12449 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012450 if (kind1 != kind)
12451 PyMem_Free(buf1);
12452 if (kind2 != kind)
12453 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012454
12455 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 onError:
12457 Py_DECREF(sep_obj);
12458 Py_DECREF(str_obj);
12459 if (kind1 != kind && buf1)
12460 PyMem_Free(buf1);
12461 if (kind2 != kind && buf2)
12462 PyMem_Free(buf2);
12463 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012464}
12465
12466
12467PyObject *
12468PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12469{
12470 PyObject* str_obj;
12471 PyObject* sep_obj;
12472 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 int kind1, kind2, kind;
12474 void *buf1 = NULL, *buf2 = NULL;
12475 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012476
12477 str_obj = PyUnicode_FromObject(str_in);
12478 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012479 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012480 sep_obj = PyUnicode_FromObject(sep_in);
12481 if (!sep_obj) {
12482 Py_DECREF(str_obj);
12483 return NULL;
12484 }
12485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012486 kind1 = PyUnicode_KIND(str_in);
12487 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012488 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012489 buf1 = PyUnicode_DATA(str_in);
12490 if (kind1 != kind)
12491 buf1 = _PyUnicode_AsKind(str_in, kind);
12492 if (!buf1)
12493 goto onError;
12494 buf2 = PyUnicode_DATA(sep_obj);
12495 if (kind2 != kind)
12496 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12497 if (!buf2)
12498 goto onError;
12499 len1 = PyUnicode_GET_LENGTH(str_obj);
12500 len2 = PyUnicode_GET_LENGTH(sep_obj);
12501
12502 switch(PyUnicode_KIND(str_in)) {
12503 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012504 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12505 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12506 else
12507 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012508 break;
12509 case PyUnicode_2BYTE_KIND:
12510 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12511 break;
12512 case PyUnicode_4BYTE_KIND:
12513 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12514 break;
12515 default:
12516 assert(0);
12517 out = 0;
12518 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519
12520 Py_DECREF(sep_obj);
12521 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012522 if (kind1 != kind)
12523 PyMem_Free(buf1);
12524 if (kind2 != kind)
12525 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526
12527 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012528 onError:
12529 Py_DECREF(sep_obj);
12530 Py_DECREF(str_obj);
12531 if (kind1 != kind && buf1)
12532 PyMem_Free(buf1);
12533 if (kind2 != kind && buf2)
12534 PyMem_Free(buf2);
12535 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012536}
12537
12538PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012539 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012540\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012541Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012542the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012543found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012544
12545static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012546unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012547{
Victor Stinner9310abb2011-10-05 00:59:23 +020012548 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012549}
12550
12551PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012552 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012553\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012554Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012555the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012556separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012557
12558static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012559unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012560{
Victor Stinner9310abb2011-10-05 00:59:23 +020012561 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012562}
12563
Alexander Belopolsky40018472011-02-26 01:02:56 +000012564PyObject *
12565PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012566{
12567 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012568
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012569 s = PyUnicode_FromObject(s);
12570 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012571 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 if (sep != NULL) {
12573 sep = PyUnicode_FromObject(sep);
12574 if (sep == NULL) {
12575 Py_DECREF(s);
12576 return NULL;
12577 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012578 }
12579
Victor Stinner9310abb2011-10-05 00:59:23 +020012580 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012581
12582 Py_DECREF(s);
12583 Py_XDECREF(sep);
12584 return result;
12585}
12586
12587PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012588 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012589\n\
12590Return a list of the words in S, using sep as the\n\
12591delimiter string, starting at the end of the string and\n\
12592working to the front. If maxsplit is given, at most maxsplit\n\
12593splits are done. If sep is not specified, any whitespace string\n\
12594is a separator.");
12595
12596static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012597unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012598{
12599 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012600 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012601
Martin v. Löwis18e16552006-02-15 17:27:45 +000012602 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012603 return NULL;
12604
12605 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012606 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012607 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012608 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012609 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012610 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012611}
12612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012613PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012614 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615\n\
12616Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012617Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012618is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619
12620static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012621unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012623 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012624 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012626 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12627 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012628 return NULL;
12629
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012630 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631}
12632
12633static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012634PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635{
Walter Dörwald346737f2007-05-31 10:44:43 +000012636 if (PyUnicode_CheckExact(self)) {
12637 Py_INCREF(self);
12638 return self;
12639 } else
12640 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012641 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642}
12643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012644PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012645 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646\n\
12647Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012648and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012649
12650static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012651unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653 return fixup(self, fixswapcase);
12654}
12655
Georg Brandlceee0772007-11-27 23:48:05 +000012656PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012657 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012658\n\
12659Return a translation table usable for str.translate().\n\
12660If there is only one argument, it must be a dictionary mapping Unicode\n\
12661ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012662Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012663If there are two arguments, they must be strings of equal length, and\n\
12664in the resulting dictionary, each character in x will be mapped to the\n\
12665character at the same position in y. If there is a third argument, it\n\
12666must be a string, whose characters will be mapped to None in the result.");
12667
12668static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012669unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012670{
12671 PyObject *x, *y = NULL, *z = NULL;
12672 PyObject *new = NULL, *key, *value;
12673 Py_ssize_t i = 0;
12674 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012675
Georg Brandlceee0772007-11-27 23:48:05 +000012676 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12677 return NULL;
12678 new = PyDict_New();
12679 if (!new)
12680 return NULL;
12681 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012682 int x_kind, y_kind, z_kind;
12683 void *x_data, *y_data, *z_data;
12684
Georg Brandlceee0772007-11-27 23:48:05 +000012685 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012686 if (!PyUnicode_Check(x)) {
12687 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12688 "be a string if there is a second argument");
12689 goto err;
12690 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012691 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012692 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12693 "arguments must have equal length");
12694 goto err;
12695 }
12696 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012697 x_kind = PyUnicode_KIND(x);
12698 y_kind = PyUnicode_KIND(y);
12699 x_data = PyUnicode_DATA(x);
12700 y_data = PyUnicode_DATA(y);
12701 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12702 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12703 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012704 if (!key || !value)
12705 goto err;
12706 res = PyDict_SetItem(new, key, value);
12707 Py_DECREF(key);
12708 Py_DECREF(value);
12709 if (res < 0)
12710 goto err;
12711 }
12712 /* create entries for deleting chars in z */
12713 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012714 z_kind = PyUnicode_KIND(z);
12715 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012716 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012717 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012718 if (!key)
12719 goto err;
12720 res = PyDict_SetItem(new, key, Py_None);
12721 Py_DECREF(key);
12722 if (res < 0)
12723 goto err;
12724 }
12725 }
12726 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012727 int kind;
12728 void *data;
12729
Georg Brandlceee0772007-11-27 23:48:05 +000012730 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012731 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012732 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12733 "to maketrans it must be a dict");
12734 goto err;
12735 }
12736 /* copy entries into the new dict, converting string keys to int keys */
12737 while (PyDict_Next(x, &i, &key, &value)) {
12738 if (PyUnicode_Check(key)) {
12739 /* convert string keys to integer keys */
12740 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012741 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012742 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12743 "table must be of length 1");
12744 goto err;
12745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012746 kind = PyUnicode_KIND(key);
12747 data = PyUnicode_DATA(key);
12748 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012749 if (!newkey)
12750 goto err;
12751 res = PyDict_SetItem(new, newkey, value);
12752 Py_DECREF(newkey);
12753 if (res < 0)
12754 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012755 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012756 /* just keep integer keys */
12757 if (PyDict_SetItem(new, key, value) < 0)
12758 goto err;
12759 } else {
12760 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12761 "be strings or integers");
12762 goto err;
12763 }
12764 }
12765 }
12766 return new;
12767 err:
12768 Py_DECREF(new);
12769 return NULL;
12770}
12771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012772PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774\n\
12775Return a copy of the string S, where all characters have been mapped\n\
12776through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012777Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012778Unmapped characters are left untouched. Characters mapped to None\n\
12779are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780
12781static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012782unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012784 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012785}
12786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012787PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012788 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012790Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012791
12792static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012793unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012794{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012795 return fixup(self, fixupper);
12796}
12797
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012798PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012799 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012801Pad a numeric string S with zeros on the left, to fill a field\n\
12802of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012803
12804static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012805unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012807 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012808 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012809 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810 int kind;
12811 void *data;
12812 Py_UCS4 chr;
12813
12814 if (PyUnicode_READY(self) == -1)
12815 return NULL;
12816
Martin v. Löwis18e16552006-02-15 17:27:45 +000012817 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818 return NULL;
12819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012820 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012821 if (PyUnicode_CheckExact(self)) {
12822 Py_INCREF(self);
12823 return (PyObject*) self;
12824 }
12825 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012826 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827 }
12828
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830
12831 u = pad(self, fill, 0, '0');
12832
Walter Dörwald068325e2002-04-15 13:36:47 +000012833 if (u == NULL)
12834 return NULL;
12835
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 kind = PyUnicode_KIND(u);
12837 data = PyUnicode_DATA(u);
12838 chr = PyUnicode_READ(kind, data, fill);
12839
12840 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012841 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012842 PyUnicode_WRITE(kind, data, 0, chr);
12843 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844 }
12845
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012846 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012847 return (PyObject*) u;
12848}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849
12850#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012851static PyObject *
12852unicode__decimal2ascii(PyObject *self)
12853{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012855}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012856#endif
12857
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012858PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012859 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012860\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012861Return True if S starts with the specified prefix, False otherwise.\n\
12862With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012863With optional end, stop comparing S at that position.\n\
12864prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012865
12866static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012867unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012868 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012869{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012870 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012871 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012872 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012873 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012874 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012875
Jesus Ceaac451502011-04-20 17:09:23 +020012876 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012877 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012878 if (PyTuple_Check(subobj)) {
12879 Py_ssize_t i;
12880 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012881 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012882 if (substring == NULL)
12883 return NULL;
12884 result = tailmatch(self, substring, start, end, -1);
12885 Py_DECREF(substring);
12886 if (result) {
12887 Py_RETURN_TRUE;
12888 }
12889 }
12890 /* nothing matched */
12891 Py_RETURN_FALSE;
12892 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012893 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012894 if (substring == NULL) {
12895 if (PyErr_ExceptionMatches(PyExc_TypeError))
12896 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12897 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012898 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012899 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012900 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012902 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012903}
12904
12905
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012906PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012907 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012908\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012909Return True if S ends with the specified suffix, False otherwise.\n\
12910With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012911With optional end, stop comparing S at that position.\n\
12912suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012913
12914static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012915unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012916 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012917{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012918 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012919 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012920 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012921 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012922 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012923
Jesus Ceaac451502011-04-20 17:09:23 +020012924 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012925 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012926 if (PyTuple_Check(subobj)) {
12927 Py_ssize_t i;
12928 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012929 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012930 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012931 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012932 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012933 result = tailmatch(self, substring, start, end, +1);
12934 Py_DECREF(substring);
12935 if (result) {
12936 Py_RETURN_TRUE;
12937 }
12938 }
12939 Py_RETURN_FALSE;
12940 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012941 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012942 if (substring == NULL) {
12943 if (PyErr_ExceptionMatches(PyExc_TypeError))
12944 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12945 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012946 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012947 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012948 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012949 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012950 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012951}
12952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012953#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012954
12955PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012956 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012957\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012958Return a formatted version of S, using substitutions from args and kwargs.\n\
12959The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012960
Eric Smith27bbca62010-11-04 17:06:58 +000012961PyDoc_STRVAR(format_map__doc__,
12962 "S.format_map(mapping) -> str\n\
12963\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012964Return a formatted version of S, using substitutions from mapping.\n\
12965The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012966
Eric Smith4a7d76d2008-05-30 18:10:19 +000012967static PyObject *
12968unicode__format__(PyObject* self, PyObject* args)
12969{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012970 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012971
12972 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12973 return NULL;
12974
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012975 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012976 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012977 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012978}
12979
Eric Smith8c663262007-08-25 02:26:07 +000012980PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012981 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012982\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012983Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012984
12985static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012986unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012987{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012988 Py_ssize_t size;
12989
12990 /* If it's a compact object, account for base structure +
12991 character data. */
12992 if (PyUnicode_IS_COMPACT_ASCII(v))
12993 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12994 else if (PyUnicode_IS_COMPACT(v))
12995 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012996 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012997 else {
12998 /* If it is a two-block object, account for base object, and
12999 for character block if present. */
13000 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020013001 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013002 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013003 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013004 }
13005 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020013006 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020013007 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013008 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020013009 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020013010 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013011
13012 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013013}
13014
13015PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013016 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013017
13018static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013019unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013020{
Victor Stinner034f6cf2011-09-30 02:26:44 +020013021 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013022 if (!copy)
13023 return NULL;
13024 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013025}
13026
Guido van Rossumd57fd912000-03-10 22:53:23 +000013027static PyMethodDef unicode_methods[] = {
13028
13029 /* Order is according to common usage: often used methods should
13030 appear first, since lookup is done sequentially. */
13031
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013032 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013033 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13034 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013035 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013036 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13037 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13038 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13039 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13040 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13041 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13042 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013043 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013044 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13045 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13046 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013047 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013048 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13049 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13050 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013051 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013052 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013053 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013054 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013055 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13056 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13057 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13058 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13059 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13060 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13061 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13062 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13063 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13064 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13065 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13066 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13067 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13068 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013069 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013070 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013071 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013072 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013073 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013074 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013075 {"maketrans", (PyCFunction) unicode_maketrans,
13076 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013077 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013078#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013079 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013080#endif
13081
13082#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013083 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013084 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013085#endif
13086
Benjamin Peterson14339b62009-01-31 16:36:08 +000013087 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088 {NULL, NULL}
13089};
13090
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013091static PyObject *
13092unicode_mod(PyObject *v, PyObject *w)
13093{
Brian Curtindfc80e32011-08-10 20:28:54 -050013094 if (!PyUnicode_Check(v))
13095 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013096 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013097}
13098
13099static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013100 0, /*nb_add*/
13101 0, /*nb_subtract*/
13102 0, /*nb_multiply*/
13103 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013104};
13105
Guido van Rossumd57fd912000-03-10 22:53:23 +000013106static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013107 (lenfunc) unicode_length, /* sq_length */
13108 PyUnicode_Concat, /* sq_concat */
13109 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13110 (ssizeargfunc) unicode_getitem, /* sq_item */
13111 0, /* sq_slice */
13112 0, /* sq_ass_item */
13113 0, /* sq_ass_slice */
13114 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013115};
13116
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013117static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013118unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013119{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 if (PyUnicode_READY(self) == -1)
13121 return NULL;
13122
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013123 if (PyIndex_Check(item)) {
13124 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013125 if (i == -1 && PyErr_Occurred())
13126 return NULL;
13127 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013128 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013129 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013130 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013131 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013132 PyObject *result;
13133 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013134 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013135 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013136
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013137 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013138 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013139 return NULL;
13140 }
13141
13142 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013143 return PyUnicode_New(0, 0);
13144 } else if (start == 0 && step == 1 &&
13145 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013146 PyUnicode_CheckExact(self)) {
13147 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013148 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013149 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013150 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013151 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013152 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013153 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013154 src_kind = PyUnicode_KIND(self);
13155 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013156 if (!PyUnicode_IS_ASCII(self)) {
13157 kind_limit = kind_maxchar_limit(src_kind);
13158 max_char = 0;
13159 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13160 ch = PyUnicode_READ(src_kind, src_data, cur);
13161 if (ch > max_char) {
13162 max_char = ch;
13163 if (max_char >= kind_limit)
13164 break;
13165 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013166 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013167 }
Victor Stinner55c99112011-10-13 01:17:06 +020013168 else
13169 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013170 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013171 if (result == NULL)
13172 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013173 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013174 dest_data = PyUnicode_DATA(result);
13175
13176 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013177 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13178 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013179 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013180 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013181 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013182 } else {
13183 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13184 return NULL;
13185 }
13186}
13187
13188static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013189 (lenfunc)unicode_length, /* mp_length */
13190 (binaryfunc)unicode_subscript, /* mp_subscript */
13191 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013192};
13193
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195/* Helpers for PyUnicode_Format() */
13196
13197static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013198getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013200 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013202 (*p_argidx)++;
13203 if (arglen < 0)
13204 return args;
13205 else
13206 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207 }
13208 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013209 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210 return NULL;
13211}
13212
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013213/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013214
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013215static PyObject *
13216formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013217{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013218 char *p;
13219 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013221
Guido van Rossumd57fd912000-03-10 22:53:23 +000013222 x = PyFloat_AsDouble(v);
13223 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013224 return NULL;
13225
Guido van Rossumd57fd912000-03-10 22:53:23 +000013226 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013227 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013228
Eric Smith0923d1d2009-04-16 20:16:10 +000013229 p = PyOS_double_to_string(x, type, prec,
13230 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013231 if (p == NULL)
13232 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013233 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013234 PyMem_Free(p);
13235 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013236}
13237
Tim Peters38fd5b62000-09-21 05:43:11 +000013238static PyObject*
13239formatlong(PyObject *val, int flags, int prec, int type)
13240{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013241 char *buf;
13242 int len;
13243 PyObject *str; /* temporary string object. */
13244 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013245
Benjamin Peterson14339b62009-01-31 16:36:08 +000013246 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13247 if (!str)
13248 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013249 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013250 Py_DECREF(str);
13251 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013252}
13253
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013254static Py_UCS4
13255formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013256{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013257 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013258 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013259 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013260 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013261 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013262 goto onError;
13263 }
13264 else {
13265 /* Integer input truncated to a character */
13266 long x;
13267 x = PyLong_AsLong(v);
13268 if (x == -1 && PyErr_Occurred())
13269 goto onError;
13270
13271 if (x < 0 || x > 0x10ffff) {
13272 PyErr_SetString(PyExc_OverflowError,
13273 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013274 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 }
13276
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013277 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013278 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013279
Benjamin Peterson29060642009-01-31 22:14:21 +000013280 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013281 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013283 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013284}
13285
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013286static int
13287repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13288{
13289 int r;
13290 assert(count > 0);
13291 assert(PyUnicode_Check(obj));
13292 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013293 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013294 if (repeated == NULL)
13295 return -1;
13296 r = _PyAccu_Accumulate(acc, repeated);
13297 Py_DECREF(repeated);
13298 return r;
13299 }
13300 else {
13301 do {
13302 if (_PyAccu_Accumulate(acc, obj))
13303 return -1;
13304 } while (--count);
13305 return 0;
13306 }
13307}
13308
Alexander Belopolsky40018472011-02-26 01:02:56 +000013309PyObject *
13310PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013311{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013312 void *fmt;
13313 int fmtkind;
13314 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013316 int r;
13317 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013318 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013319 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013320 PyObject *temp = NULL;
13321 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013322 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013323 _PyAccu acc;
13324 static PyObject *plus, *minus, *blank, *zero, *percent;
13325
13326 if (!plus && !(plus = get_latin1_char('+')))
13327 return NULL;
13328 if (!minus && !(minus = get_latin1_char('-')))
13329 return NULL;
13330 if (!blank && !(blank = get_latin1_char(' ')))
13331 return NULL;
13332 if (!zero && !(zero = get_latin1_char('0')))
13333 return NULL;
13334 if (!percent && !(percent = get_latin1_char('%')))
13335 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013336
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013338 PyErr_BadInternalCall();
13339 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013340 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013341 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013342 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013343 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013344 if (_PyAccu_Init(&acc))
13345 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013346 fmt = PyUnicode_DATA(uformat);
13347 fmtkind = PyUnicode_KIND(uformat);
13348 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13349 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013350
Guido van Rossumd57fd912000-03-10 22:53:23 +000013351 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013352 arglen = PyTuple_Size(args);
13353 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013354 }
13355 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013356 arglen = -1;
13357 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013358 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013359 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013360 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013361 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013362
13363 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013364 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013365 PyObject *nonfmt;
13366 Py_ssize_t nonfmtpos;
13367 nonfmtpos = fmtpos++;
13368 while (fmtcnt >= 0 &&
13369 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13370 fmtpos++;
13371 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013372 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013373 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
13374 if (nonfmt == NULL)
13375 goto onError;
13376 r = _PyAccu_Accumulate(&acc, nonfmt);
13377 Py_DECREF(nonfmt);
13378 if (r)
13379 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013380 }
13381 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 /* Got a format specifier */
13383 int flags = 0;
13384 Py_ssize_t width = -1;
13385 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013386 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013387 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013388 int isnumok;
13389 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013390 void *pbuf = NULL;
13391 Py_ssize_t pindex, len;
13392 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013393
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013394 fmtpos++;
13395 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13396 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013397 Py_ssize_t keylen;
13398 PyObject *key;
13399 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013400
Benjamin Peterson29060642009-01-31 22:14:21 +000013401 if (dict == NULL) {
13402 PyErr_SetString(PyExc_TypeError,
13403 "format requires a mapping");
13404 goto onError;
13405 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013406 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013408 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013409 /* Skip over balanced parentheses */
13410 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013411 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013412 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013413 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013414 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013415 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013416 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013417 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 if (fmtcnt < 0 || pcount > 0) {
13419 PyErr_SetString(PyExc_ValueError,
13420 "incomplete format key");
13421 goto onError;
13422 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020013423 key = PyUnicode_Substring((PyObject*)uformat,
13424 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 if (key == NULL)
13426 goto onError;
13427 if (args_owned) {
13428 Py_DECREF(args);
13429 args_owned = 0;
13430 }
13431 args = PyObject_GetItem(dict, key);
13432 Py_DECREF(key);
13433 if (args == NULL) {
13434 goto onError;
13435 }
13436 args_owned = 1;
13437 arglen = -1;
13438 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013439 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013440 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013441 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 case '-': flags |= F_LJUST; continue;
13443 case '+': flags |= F_SIGN; continue;
13444 case ' ': flags |= F_BLANK; continue;
13445 case '#': flags |= F_ALT; continue;
13446 case '0': flags |= F_ZERO; continue;
13447 }
13448 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013449 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013450 if (c == '*') {
13451 v = getnextarg(args, arglen, &argidx);
13452 if (v == NULL)
13453 goto onError;
13454 if (!PyLong_Check(v)) {
13455 PyErr_SetString(PyExc_TypeError,
13456 "* wants int");
13457 goto onError;
13458 }
13459 width = PyLong_AsLong(v);
13460 if (width == -1 && PyErr_Occurred())
13461 goto onError;
13462 if (width < 0) {
13463 flags |= F_LJUST;
13464 width = -width;
13465 }
13466 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013467 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013468 }
13469 else if (c >= '0' && c <= '9') {
13470 width = c - '0';
13471 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013472 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013473 if (c < '0' || c > '9')
13474 break;
13475 if ((width*10) / 10 != width) {
13476 PyErr_SetString(PyExc_ValueError,
13477 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013478 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013479 }
13480 width = width*10 + (c - '0');
13481 }
13482 }
13483 if (c == '.') {
13484 prec = 0;
13485 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013486 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 if (c == '*') {
13488 v = getnextarg(args, arglen, &argidx);
13489 if (v == NULL)
13490 goto onError;
13491 if (!PyLong_Check(v)) {
13492 PyErr_SetString(PyExc_TypeError,
13493 "* wants int");
13494 goto onError;
13495 }
13496 prec = PyLong_AsLong(v);
13497 if (prec == -1 && PyErr_Occurred())
13498 goto onError;
13499 if (prec < 0)
13500 prec = 0;
13501 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013502 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 }
13504 else if (c >= '0' && c <= '9') {
13505 prec = c - '0';
13506 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013507 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 if (c < '0' || c > '9')
13509 break;
13510 if ((prec*10) / 10 != prec) {
13511 PyErr_SetString(PyExc_ValueError,
13512 "prec too big");
13513 goto onError;
13514 }
13515 prec = prec*10 + (c - '0');
13516 }
13517 }
13518 } /* prec */
13519 if (fmtcnt >= 0) {
13520 if (c == 'h' || c == 'l' || c == 'L') {
13521 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013522 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 }
13524 }
13525 if (fmtcnt < 0) {
13526 PyErr_SetString(PyExc_ValueError,
13527 "incomplete format");
13528 goto onError;
13529 }
13530 if (c != '%') {
13531 v = getnextarg(args, arglen, &argidx);
13532 if (v == NULL)
13533 goto onError;
13534 }
13535 sign = 0;
13536 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013537 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013538 switch (c) {
13539
13540 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013541 _PyAccu_Accumulate(&acc, percent);
13542 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013543
13544 case 's':
13545 case 'r':
13546 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013547 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 temp = v;
13549 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013550 }
13551 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013552 if (c == 's')
13553 temp = PyObject_Str(v);
13554 else if (c == 'r')
13555 temp = PyObject_Repr(v);
13556 else
13557 temp = PyObject_ASCII(v);
13558 if (temp == NULL)
13559 goto onError;
13560 if (PyUnicode_Check(temp))
13561 /* nothing to do */;
13562 else {
13563 Py_DECREF(temp);
13564 PyErr_SetString(PyExc_TypeError,
13565 "%s argument has non-string str()");
13566 goto onError;
13567 }
13568 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013569 if (PyUnicode_READY(temp) == -1) {
13570 Py_CLEAR(temp);
13571 goto onError;
13572 }
13573 pbuf = PyUnicode_DATA(temp);
13574 kind = PyUnicode_KIND(temp);
13575 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013576 if (prec >= 0 && len > prec)
13577 len = prec;
13578 break;
13579
13580 case 'i':
13581 case 'd':
13582 case 'u':
13583 case 'o':
13584 case 'x':
13585 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013586 isnumok = 0;
13587 if (PyNumber_Check(v)) {
13588 PyObject *iobj=NULL;
13589
13590 if (PyLong_Check(v)) {
13591 iobj = v;
13592 Py_INCREF(iobj);
13593 }
13594 else {
13595 iobj = PyNumber_Long(v);
13596 }
13597 if (iobj!=NULL) {
13598 if (PyLong_Check(iobj)) {
13599 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013600 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013601 Py_DECREF(iobj);
13602 if (!temp)
13603 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013604 if (PyUnicode_READY(temp) == -1) {
13605 Py_CLEAR(temp);
13606 goto onError;
13607 }
13608 pbuf = PyUnicode_DATA(temp);
13609 kind = PyUnicode_KIND(temp);
13610 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013611 sign = 1;
13612 }
13613 else {
13614 Py_DECREF(iobj);
13615 }
13616 }
13617 }
13618 if (!isnumok) {
13619 PyErr_Format(PyExc_TypeError,
13620 "%%%c format: a number is required, "
13621 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13622 goto onError;
13623 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013624 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013626 fillobj = zero;
13627 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013628 break;
13629
13630 case 'e':
13631 case 'E':
13632 case 'f':
13633 case 'F':
13634 case 'g':
13635 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013636 temp = formatfloat(v, flags, prec, c);
13637 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013638 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013639 if (PyUnicode_READY(temp) == -1) {
13640 Py_CLEAR(temp);
13641 goto onError;
13642 }
13643 pbuf = PyUnicode_DATA(temp);
13644 kind = PyUnicode_KIND(temp);
13645 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013646 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013647 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013648 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013649 fillobj = zero;
13650 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013651 break;
13652
13653 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013654 {
13655 Py_UCS4 ch = formatchar(v);
13656 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013658 temp = _PyUnicode_FromUCS4(&ch, 1);
13659 if (temp == NULL)
13660 goto onError;
13661 pbuf = PyUnicode_DATA(temp);
13662 kind = PyUnicode_KIND(temp);
13663 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013665 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013666
13667 default:
13668 PyErr_Format(PyExc_ValueError,
13669 "unsupported format character '%c' (0x%x) "
13670 "at index %zd",
13671 (31<=c && c<=126) ? (char)c : '?',
13672 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013673 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 goto onError;
13675 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013676 /* pbuf is initialized here. */
13677 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013678 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013679 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13680 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013681 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013682 pindex++;
13683 }
13684 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13685 signobj = plus;
13686 len--;
13687 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013688 }
13689 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013690 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013691 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013692 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 else
13694 sign = 0;
13695 }
13696 if (width < len)
13697 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013698 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013699 if (fill != ' ') {
13700 assert(signobj != NULL);
13701 if (_PyAccu_Accumulate(&acc, signobj))
13702 goto onError;
13703 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013704 if (width > len)
13705 width--;
13706 }
13707 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013708 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013709 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013710 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013711 second = get_latin1_char(
13712 PyUnicode_READ(kind, pbuf, pindex + 1));
13713 pindex += 2;
13714 if (second == NULL ||
13715 _PyAccu_Accumulate(&acc, zero) ||
13716 _PyAccu_Accumulate(&acc, second))
13717 goto onError;
13718 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013719 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013720 width -= 2;
13721 if (width < 0)
13722 width = 0;
13723 len -= 2;
13724 }
13725 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013726 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013727 if (repeat_accumulate(&acc, fillobj, width - len))
13728 goto onError;
13729 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013730 }
13731 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013732 if (sign) {
13733 assert(signobj != NULL);
13734 if (_PyAccu_Accumulate(&acc, signobj))
13735 goto onError;
13736 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013737 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013738 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13739 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013740 second = get_latin1_char(
13741 PyUnicode_READ(kind, pbuf, pindex + 1));
13742 pindex += 2;
13743 if (second == NULL ||
13744 _PyAccu_Accumulate(&acc, zero) ||
13745 _PyAccu_Accumulate(&acc, second))
13746 goto onError;
13747 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013748 }
13749 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013750 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013751 if (temp != NULL) {
13752 assert(pbuf == PyUnicode_DATA(temp));
13753 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013754 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013755 else {
13756 const char *p = (const char *) pbuf;
13757 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013758 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013759 v = PyUnicode_FromKindAndData(kind, p, len);
13760 }
13761 if (v == NULL)
13762 goto onError;
13763 r = _PyAccu_Accumulate(&acc, v);
13764 Py_DECREF(v);
13765 if (r)
13766 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013767 if (width > len && repeat_accumulate(&acc, blank, width - len))
13768 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 if (dict && (argidx < arglen) && c != '%') {
13770 PyErr_SetString(PyExc_TypeError,
13771 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013772 goto onError;
13773 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013774 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013776 } /* until end */
13777 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 PyErr_SetString(PyExc_TypeError,
13779 "not all arguments converted during string formatting");
13780 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013781 }
13782
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013783 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013784 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013785 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013786 }
13787 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013788 Py_XDECREF(temp);
13789 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013790 return (PyObject *)result;
13791
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013793 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013794 Py_XDECREF(temp);
13795 Py_XDECREF(second);
13796 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013797 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013798 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013799 }
13800 return NULL;
13801}
13802
Jeremy Hylton938ace62002-07-17 16:30:39 +000013803static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013804unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13805
Tim Peters6d6c1a32001-08-02 04:15:00 +000013806static PyObject *
13807unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13808{
Benjamin Peterson29060642009-01-31 22:14:21 +000013809 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013810 static char *kwlist[] = {"object", "encoding", "errors", 0};
13811 char *encoding = NULL;
13812 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013813
Benjamin Peterson14339b62009-01-31 16:36:08 +000013814 if (type != &PyUnicode_Type)
13815 return unicode_subtype_new(type, args, kwds);
13816 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013817 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013818 return NULL;
13819 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013820 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013821 if (encoding == NULL && errors == NULL)
13822 return PyObject_Str(x);
13823 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013824 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013825}
13826
Guido van Rossume023fe02001-08-30 03:12:59 +000013827static PyObject *
13828unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13829{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013830 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013831 Py_ssize_t length, char_size;
13832 int share_wstr, share_utf8;
13833 unsigned int kind;
13834 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013835
Benjamin Peterson14339b62009-01-31 16:36:08 +000013836 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013837
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013838 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013839 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013840 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013841 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013842 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013843 return NULL;
13844
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013845 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013846 if (self == NULL) {
13847 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013848 return NULL;
13849 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013850 kind = PyUnicode_KIND(unicode);
13851 length = PyUnicode_GET_LENGTH(unicode);
13852
13853 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013854#ifdef Py_DEBUG
13855 _PyUnicode_HASH(self) = -1;
13856#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013857 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013858#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013859 _PyUnicode_STATE(self).interned = 0;
13860 _PyUnicode_STATE(self).kind = kind;
13861 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013862 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013863 _PyUnicode_STATE(self).ready = 1;
13864 _PyUnicode_WSTR(self) = NULL;
13865 _PyUnicode_UTF8_LENGTH(self) = 0;
13866 _PyUnicode_UTF8(self) = NULL;
13867 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013868 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013869
13870 share_utf8 = 0;
13871 share_wstr = 0;
13872 if (kind == PyUnicode_1BYTE_KIND) {
13873 char_size = 1;
13874 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13875 share_utf8 = 1;
13876 }
13877 else if (kind == PyUnicode_2BYTE_KIND) {
13878 char_size = 2;
13879 if (sizeof(wchar_t) == 2)
13880 share_wstr = 1;
13881 }
13882 else {
13883 assert(kind == PyUnicode_4BYTE_KIND);
13884 char_size = 4;
13885 if (sizeof(wchar_t) == 4)
13886 share_wstr = 1;
13887 }
13888
13889 /* Ensure we won't overflow the length. */
13890 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13891 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013892 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013893 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013894 data = PyObject_MALLOC((length + 1) * char_size);
13895 if (data == NULL) {
13896 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013897 goto onError;
13898 }
13899
Victor Stinnerc3c74152011-10-02 20:39:55 +020013900 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013901 if (share_utf8) {
13902 _PyUnicode_UTF8_LENGTH(self) = length;
13903 _PyUnicode_UTF8(self) = data;
13904 }
13905 if (share_wstr) {
13906 _PyUnicode_WSTR_LENGTH(self) = length;
13907 _PyUnicode_WSTR(self) = (wchar_t *)data;
13908 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013909
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013910 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013911 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013912 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013913#ifdef Py_DEBUG
13914 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13915#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013916 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013917 return (PyObject *)self;
13918
13919onError:
13920 Py_DECREF(unicode);
13921 Py_DECREF(self);
13922 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013923}
13924
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013925PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013926 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013927\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013928Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013929encoding defaults to the current default string encoding.\n\
13930errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013931
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013932static PyObject *unicode_iter(PyObject *seq);
13933
Guido van Rossumd57fd912000-03-10 22:53:23 +000013934PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013935 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013936 "str", /* tp_name */
13937 sizeof(PyUnicodeObject), /* tp_size */
13938 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013939 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013940 (destructor)unicode_dealloc, /* tp_dealloc */
13941 0, /* tp_print */
13942 0, /* tp_getattr */
13943 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013944 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013945 unicode_repr, /* tp_repr */
13946 &unicode_as_number, /* tp_as_number */
13947 &unicode_as_sequence, /* tp_as_sequence */
13948 &unicode_as_mapping, /* tp_as_mapping */
13949 (hashfunc) unicode_hash, /* tp_hash*/
13950 0, /* tp_call*/
13951 (reprfunc) unicode_str, /* tp_str */
13952 PyObject_GenericGetAttr, /* tp_getattro */
13953 0, /* tp_setattro */
13954 0, /* tp_as_buffer */
13955 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013956 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 unicode_doc, /* tp_doc */
13958 0, /* tp_traverse */
13959 0, /* tp_clear */
13960 PyUnicode_RichCompare, /* tp_richcompare */
13961 0, /* tp_weaklistoffset */
13962 unicode_iter, /* tp_iter */
13963 0, /* tp_iternext */
13964 unicode_methods, /* tp_methods */
13965 0, /* tp_members */
13966 0, /* tp_getset */
13967 &PyBaseObject_Type, /* tp_base */
13968 0, /* tp_dict */
13969 0, /* tp_descr_get */
13970 0, /* tp_descr_set */
13971 0, /* tp_dictoffset */
13972 0, /* tp_init */
13973 0, /* tp_alloc */
13974 unicode_new, /* tp_new */
13975 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013976};
13977
13978/* Initialize the Unicode implementation */
13979
Victor Stinner3a50e702011-10-18 21:21:00 +020013980int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013981{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013982 int i;
13983
Thomas Wouters477c8d52006-05-27 19:21:47 +000013984 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013985 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013986 0x000A, /* LINE FEED */
13987 0x000D, /* CARRIAGE RETURN */
13988 0x001C, /* FILE SEPARATOR */
13989 0x001D, /* GROUP SEPARATOR */
13990 0x001E, /* RECORD SEPARATOR */
13991 0x0085, /* NEXT LINE */
13992 0x2028, /* LINE SEPARATOR */
13993 0x2029, /* PARAGRAPH SEPARATOR */
13994 };
13995
Fred Drakee4315f52000-05-09 19:53:39 +000013996 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013997 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013998 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013999 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014000 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014001
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014002 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000014003 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000014004 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000014005 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000014006
14007 /* initialize the linebreak bloom filter */
14008 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014009 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020014010 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000014011
14012 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020014013
14014#ifdef HAVE_MBCS
14015 winver.dwOSVersionInfoSize = sizeof(winver);
14016 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14017 PyErr_SetFromWindowsErr(0);
14018 return -1;
14019 }
14020#endif
14021 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014022}
14023
14024/* Finalize the Unicode implementation */
14025
Christian Heimesa156e092008-02-16 07:38:31 +000014026int
14027PyUnicode_ClearFreeList(void)
14028{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014029 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014030}
14031
Guido van Rossumd57fd912000-03-10 22:53:23 +000014032void
Thomas Wouters78890102000-07-22 19:25:51 +000014033_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014034{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014035 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014036
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014037 Py_XDECREF(unicode_empty);
14038 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014039
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014040 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014041 if (unicode_latin1[i]) {
14042 Py_DECREF(unicode_latin1[i]);
14043 unicode_latin1[i] = NULL;
14044 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014045 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014046 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014047 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014048}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014049
Walter Dörwald16807132007-05-25 13:52:07 +000014050void
14051PyUnicode_InternInPlace(PyObject **p)
14052{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014053 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014054 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014055#ifdef Py_DEBUG
14056 assert(s != NULL);
14057 assert(_PyUnicode_CHECK(s));
14058#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014059 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014060 return;
14061#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014062 /* If it's a subclass, we don't really know what putting
14063 it in the interned dict might do. */
14064 if (!PyUnicode_CheckExact(s))
14065 return;
14066 if (PyUnicode_CHECK_INTERNED(s))
14067 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020014068 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014069 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014070 return;
14071 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014072 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014073 if (interned == NULL) {
14074 interned = PyDict_New();
14075 if (interned == NULL) {
14076 PyErr_Clear(); /* Don't leave an exception */
14077 return;
14078 }
14079 }
14080 /* It might be that the GetItem call fails even
14081 though the key is present in the dictionary,
14082 namely when this happens during a stack overflow. */
14083 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000014084 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014085 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014086
Benjamin Peterson29060642009-01-31 22:14:21 +000014087 if (t) {
14088 Py_INCREF(t);
14089 Py_DECREF(*p);
14090 *p = t;
14091 return;
14092 }
Walter Dörwald16807132007-05-25 13:52:07 +000014093
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 PyThreadState_GET()->recursion_critical = 1;
14095 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
14096 PyErr_Clear();
14097 PyThreadState_GET()->recursion_critical = 0;
14098 return;
14099 }
14100 PyThreadState_GET()->recursion_critical = 0;
14101 /* The two references in interned are not counted by refcnt.
14102 The deallocator will take care of this */
14103 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014104 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014105}
14106
14107void
14108PyUnicode_InternImmortal(PyObject **p)
14109{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014110 PyUnicode_InternInPlace(p);
14111 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014112 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014113 Py_INCREF(*p);
14114 }
Walter Dörwald16807132007-05-25 13:52:07 +000014115}
14116
14117PyObject *
14118PyUnicode_InternFromString(const char *cp)
14119{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014120 PyObject *s = PyUnicode_FromString(cp);
14121 if (s == NULL)
14122 return NULL;
14123 PyUnicode_InternInPlace(&s);
14124 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014125}
14126
Alexander Belopolsky40018472011-02-26 01:02:56 +000014127void
14128_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014129{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014130 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014131 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 Py_ssize_t i, n;
14133 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014134
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 if (interned == NULL || !PyDict_Check(interned))
14136 return;
14137 keys = PyDict_Keys(interned);
14138 if (keys == NULL || !PyList_Check(keys)) {
14139 PyErr_Clear();
14140 return;
14141 }
Walter Dörwald16807132007-05-25 13:52:07 +000014142
Benjamin Peterson14339b62009-01-31 16:36:08 +000014143 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14144 detector, interned unicode strings are not forcibly deallocated;
14145 rather, we give them their stolen references back, and then clear
14146 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014147
Benjamin Peterson14339b62009-01-31 16:36:08 +000014148 n = PyList_GET_SIZE(keys);
14149 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014150 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014151 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014152 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014153 if (PyUnicode_READY(s) == -1) {
14154 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014155 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014157 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014158 case SSTATE_NOT_INTERNED:
14159 /* XXX Shouldn't happen */
14160 break;
14161 case SSTATE_INTERNED_IMMORTAL:
14162 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014163 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014164 break;
14165 case SSTATE_INTERNED_MORTAL:
14166 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014167 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014168 break;
14169 default:
14170 Py_FatalError("Inconsistent interned string state.");
14171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014172 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014173 }
14174 fprintf(stderr, "total size of all interned strings: "
14175 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14176 "mortal/immortal\n", mortal_size, immortal_size);
14177 Py_DECREF(keys);
14178 PyDict_Clear(interned);
14179 Py_DECREF(interned);
14180 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014181}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014182
14183
14184/********************* Unicode Iterator **************************/
14185
14186typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014187 PyObject_HEAD
14188 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014189 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014190} unicodeiterobject;
14191
14192static void
14193unicodeiter_dealloc(unicodeiterobject *it)
14194{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014195 _PyObject_GC_UNTRACK(it);
14196 Py_XDECREF(it->it_seq);
14197 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014198}
14199
14200static int
14201unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14202{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014203 Py_VISIT(it->it_seq);
14204 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014205}
14206
14207static PyObject *
14208unicodeiter_next(unicodeiterobject *it)
14209{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014210 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014211
Benjamin Peterson14339b62009-01-31 16:36:08 +000014212 assert(it != NULL);
14213 seq = it->it_seq;
14214 if (seq == NULL)
14215 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014216 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014217
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014218 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14219 int kind = PyUnicode_KIND(seq);
14220 void *data = PyUnicode_DATA(seq);
14221 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14222 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014223 if (item != NULL)
14224 ++it->it_index;
14225 return item;
14226 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014227
Benjamin Peterson14339b62009-01-31 16:36:08 +000014228 Py_DECREF(seq);
14229 it->it_seq = NULL;
14230 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014231}
14232
14233static PyObject *
14234unicodeiter_len(unicodeiterobject *it)
14235{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014236 Py_ssize_t len = 0;
14237 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014238 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014239 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014240}
14241
14242PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14243
14244static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014245 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014246 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014247 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014248};
14249
14250PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014251 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14252 "str_iterator", /* tp_name */
14253 sizeof(unicodeiterobject), /* tp_basicsize */
14254 0, /* tp_itemsize */
14255 /* methods */
14256 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14257 0, /* tp_print */
14258 0, /* tp_getattr */
14259 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014260 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014261 0, /* tp_repr */
14262 0, /* tp_as_number */
14263 0, /* tp_as_sequence */
14264 0, /* tp_as_mapping */
14265 0, /* tp_hash */
14266 0, /* tp_call */
14267 0, /* tp_str */
14268 PyObject_GenericGetAttr, /* tp_getattro */
14269 0, /* tp_setattro */
14270 0, /* tp_as_buffer */
14271 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14272 0, /* tp_doc */
14273 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14274 0, /* tp_clear */
14275 0, /* tp_richcompare */
14276 0, /* tp_weaklistoffset */
14277 PyObject_SelfIter, /* tp_iter */
14278 (iternextfunc)unicodeiter_next, /* tp_iternext */
14279 unicodeiter_methods, /* tp_methods */
14280 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014281};
14282
14283static PyObject *
14284unicode_iter(PyObject *seq)
14285{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014286 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014287
Benjamin Peterson14339b62009-01-31 16:36:08 +000014288 if (!PyUnicode_Check(seq)) {
14289 PyErr_BadInternalCall();
14290 return NULL;
14291 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014292 if (PyUnicode_READY(seq) == -1)
14293 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014294 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14295 if (it == NULL)
14296 return NULL;
14297 it->it_index = 0;
14298 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014299 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014300 _PyObject_GC_TRACK(it);
14301 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014302}
14303
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014304
14305size_t
14306Py_UNICODE_strlen(const Py_UNICODE *u)
14307{
14308 int res = 0;
14309 while(*u++)
14310 res++;
14311 return res;
14312}
14313
14314Py_UNICODE*
14315Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14316{
14317 Py_UNICODE *u = s1;
14318 while ((*u++ = *s2++));
14319 return s1;
14320}
14321
14322Py_UNICODE*
14323Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14324{
14325 Py_UNICODE *u = s1;
14326 while ((*u++ = *s2++))
14327 if (n-- == 0)
14328 break;
14329 return s1;
14330}
14331
14332Py_UNICODE*
14333Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14334{
14335 Py_UNICODE *u1 = s1;
14336 u1 += Py_UNICODE_strlen(u1);
14337 Py_UNICODE_strcpy(u1, s2);
14338 return s1;
14339}
14340
14341int
14342Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14343{
14344 while (*s1 && *s2 && *s1 == *s2)
14345 s1++, s2++;
14346 if (*s1 && *s2)
14347 return (*s1 < *s2) ? -1 : +1;
14348 if (*s1)
14349 return 1;
14350 if (*s2)
14351 return -1;
14352 return 0;
14353}
14354
14355int
14356Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14357{
14358 register Py_UNICODE u1, u2;
14359 for (; n != 0; n--) {
14360 u1 = *s1;
14361 u2 = *s2;
14362 if (u1 != u2)
14363 return (u1 < u2) ? -1 : +1;
14364 if (u1 == '\0')
14365 return 0;
14366 s1++;
14367 s2++;
14368 }
14369 return 0;
14370}
14371
14372Py_UNICODE*
14373Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14374{
14375 const Py_UNICODE *p;
14376 for (p = s; *p; p++)
14377 if (*p == c)
14378 return (Py_UNICODE*)p;
14379 return NULL;
14380}
14381
14382Py_UNICODE*
14383Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14384{
14385 const Py_UNICODE *p;
14386 p = s + Py_UNICODE_strlen(s);
14387 while (p != s) {
14388 p--;
14389 if (*p == c)
14390 return (Py_UNICODE*)p;
14391 }
14392 return NULL;
14393}
Victor Stinner331ea922010-08-10 16:37:20 +000014394
Victor Stinner71133ff2010-09-01 23:43:53 +000014395Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014396PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014397{
Victor Stinner577db2c2011-10-11 22:12:48 +020014398 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014399 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014401 if (!PyUnicode_Check(unicode)) {
14402 PyErr_BadArgument();
14403 return NULL;
14404 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014405 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014406 if (u == NULL)
14407 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014408 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014409 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014410 PyErr_NoMemory();
14411 return NULL;
14412 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014413 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014414 size *= sizeof(Py_UNICODE);
14415 copy = PyMem_Malloc(size);
14416 if (copy == NULL) {
14417 PyErr_NoMemory();
14418 return NULL;
14419 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014420 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014421 return copy;
14422}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014423
Georg Brandl66c221e2010-10-14 07:04:07 +000014424/* A _string module, to export formatter_parser and formatter_field_name_split
14425 to the string.Formatter class implemented in Python. */
14426
14427static PyMethodDef _string_methods[] = {
14428 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14429 METH_O, PyDoc_STR("split the argument as a field name")},
14430 {"formatter_parser", (PyCFunction) formatter_parser,
14431 METH_O, PyDoc_STR("parse the argument as a format string")},
14432 {NULL, NULL}
14433};
14434
14435static struct PyModuleDef _string_module = {
14436 PyModuleDef_HEAD_INIT,
14437 "_string",
14438 PyDoc_STR("string helper module"),
14439 0,
14440 _string_methods,
14441 NULL,
14442 NULL,
14443 NULL,
14444 NULL
14445};
14446
14447PyMODINIT_FUNC
14448PyInit__string(void)
14449{
14450 return PyModule_Create(&_string_module);
14451}
14452
14453
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014454#ifdef __cplusplus
14455}
14456#endif