blob: 0ecbd1d4ae6b05558fe31ef3df5ab482f41d99d3 [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,
7408 const Py_UNICODE *in, const int insize,
7409 const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007410{
Victor Stinner3a50e702011-10-18 21:21:00 +02007411 const DWORD flags = encode_code_page_flags(code_page, errors);
7412 const Py_UNICODE *startin = in;
7413 const Py_UNICODE *endin = in + insize;
7414 /* Ideally, we should get reason from FormatMessage. This is the Windows
7415 2000 English version of the message. */
7416 const char *reason = "invalid character";
7417 /* 4=maximum length of a UTF-8 sequence */
7418 char buffer[4];
7419 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7420 Py_ssize_t outsize;
7421 char *out;
7422 int charsize;
7423 PyObject *errorHandler = NULL;
7424 PyObject *exc = NULL;
7425 PyObject *encoding_obj = NULL;
7426 char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007427 Py_ssize_t startpos, newpos, newoutsize;
7428 PyObject *rep;
7429 int ret = -1;
7430
7431 assert(insize > 0);
7432
7433 encoding = code_page_name(code_page, &encoding_obj);
7434 if (encoding == NULL)
7435 return -1;
7436
7437 if (errors == NULL || strcmp(errors, "strict") == 0) {
7438 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7439 then we raise a UnicodeEncodeError. */
7440 make_encode_exception(&exc, encoding, in, insize, 0, 0, reason);
7441 if (exc != NULL) {
7442 PyCodec_StrictErrors(exc);
7443 Py_DECREF(exc);
7444 }
7445 Py_XDECREF(encoding_obj);
7446 return -1;
7447 }
7448
7449 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7450 pusedDefaultChar = &usedDefaultChar;
7451 else
7452 pusedDefaultChar = NULL;
7453
7454 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7455 PyErr_NoMemory();
7456 goto error;
7457 }
7458 outsize = insize * Py_ARRAY_LENGTH(buffer);
7459
7460 if (*outbytes == NULL) {
7461 /* Create string object */
7462 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7463 if (*outbytes == NULL)
7464 goto error;
7465 out = PyBytes_AS_STRING(*outbytes);
7466 }
7467 else {
7468 /* Extend string object */
7469 Py_ssize_t n = PyBytes_Size(*outbytes);
7470 if (n > PY_SSIZE_T_MAX - outsize) {
7471 PyErr_NoMemory();
7472 goto error;
7473 }
7474 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7475 goto error;
7476 out = PyBytes_AS_STRING(*outbytes) + n;
7477 }
7478
7479 /* Encode the string character per character */
7480 while (in < endin)
7481 {
7482 if ((in + 2) <= endin
7483 && 0xD800 <= in[0] && in[0] <= 0xDBFF
7484 && 0xDC00 <= in[1] && in[1] <= 0xDFFF)
7485 charsize = 2;
7486 else
7487 charsize = 1;
7488
7489 outsize = WideCharToMultiByte(code_page, flags,
7490 in, charsize,
7491 buffer, Py_ARRAY_LENGTH(buffer),
7492 NULL, pusedDefaultChar);
7493 if (outsize > 0) {
7494 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7495 {
7496 in += charsize;
7497 memcpy(out, buffer, outsize);
7498 out += outsize;
7499 continue;
7500 }
7501 }
7502 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7503 PyErr_SetFromWindowsErr(0);
7504 goto error;
7505 }
7506
7507 charsize = Py_MAX(charsize - 1, 1);
7508 startpos = in - startin;
7509 rep = unicode_encode_call_errorhandler(
7510 errors, &errorHandler, encoding, reason,
7511 startin, insize, &exc,
7512 startpos, startpos + charsize, &newpos);
7513 if (rep == NULL)
7514 goto error;
7515 in = startin + newpos;
7516
7517 if (PyBytes_Check(rep)) {
7518 outsize = PyBytes_GET_SIZE(rep);
7519 if (outsize != 1) {
7520 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7521 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7522 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7523 Py_DECREF(rep);
7524 goto error;
7525 }
7526 out = PyBytes_AS_STRING(*outbytes) + offset;
7527 }
7528 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7529 out += outsize;
7530 }
7531 else {
7532 Py_ssize_t i;
7533 enum PyUnicode_Kind kind;
7534 void *data;
7535
7536 if (PyUnicode_READY(rep) < 0) {
7537 Py_DECREF(rep);
7538 goto error;
7539 }
7540
7541 outsize = PyUnicode_GET_LENGTH(rep);
7542 if (outsize != 1) {
7543 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7544 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7545 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7546 Py_DECREF(rep);
7547 goto error;
7548 }
7549 out = PyBytes_AS_STRING(*outbytes) + offset;
7550 }
7551 kind = PyUnicode_KIND(rep);
7552 data = PyUnicode_DATA(rep);
7553 for (i=0; i < outsize; i++) {
7554 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7555 if (ch > 127) {
7556 raise_encode_exception(&exc,
7557 encoding,
7558 startin, insize,
7559 startpos, startpos + charsize,
7560 "unable to encode error handler result to ASCII");
7561 Py_DECREF(rep);
7562 goto error;
7563 }
7564 *out = (unsigned char)ch;
7565 out++;
7566 }
7567 }
7568 Py_DECREF(rep);
7569 }
7570 /* write a NUL byte */
7571 *out = 0;
7572 outsize = out - PyBytes_AS_STRING(*outbytes);
7573 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7574 if (_PyBytes_Resize(outbytes, outsize) < 0)
7575 goto error;
7576 ret = 0;
7577
7578error:
7579 Py_XDECREF(encoding_obj);
7580 Py_XDECREF(errorHandler);
7581 Py_XDECREF(exc);
7582 return ret;
7583}
7584
7585/*
7586 * Encode a Unicode string to a Windows code page into a byte string.
7587 *
7588 * Returns consumed characters if succeed, or raise a WindowsError and returns
7589 * -1 on other error.
7590 */
7591static int
7592encode_code_page_chunk(UINT code_page, PyObject **outbytes,
7593 const Py_UNICODE *p, int size,
7594 const char* errors)
7595{
7596 int done;
7597
7598 if (size == 0) {
7599 if (*outbytes == NULL) {
7600 *outbytes = PyBytes_FromStringAndSize(NULL, 0);
7601 if (*outbytes == NULL)
7602 return -1;
7603 }
7604 return 0;
7605 }
7606
7607 done = encode_code_page_strict(code_page, outbytes, p, size, errors);
7608 if (done == -2)
7609 done = encode_code_page_errors(code_page, outbytes, p, size, errors);
7610 return done;
7611}
7612
7613static PyObject *
7614encode_code_page(int code_page,
7615 const Py_UNICODE *p, Py_ssize_t size,
7616 const char *errors)
7617{
7618 PyObject *outbytes = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007619 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007620
Victor Stinner3a50e702011-10-18 21:21:00 +02007621 if (code_page < 0) {
7622 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7623 return NULL;
7624 }
7625
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007626#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007627 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007628 if (size > INT_MAX)
Victor Stinner3a50e702011-10-18 21:21:00 +02007629 ret = encode_code_page_chunk(code_page, &outbytes, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007630 else
7631#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007632 ret = encode_code_page_chunk(code_page, &outbytes, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007633
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007634 if (ret < 0) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007635 Py_XDECREF(outbytes);
Benjamin Peterson29060642009-01-31 22:14:21 +00007636 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007637 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007638
7639#ifdef NEED_RETRY
7640 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007641 p += INT_MAX;
7642 size -= INT_MAX;
7643 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007644 }
7645#endif
7646
Victor Stinner3a50e702011-10-18 21:21:00 +02007647 return outbytes;
7648}
7649
7650PyObject *
7651PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7652 Py_ssize_t size,
7653 const char *errors)
7654{
7655 return encode_code_page(CP_ACP, p, size, errors);
7656}
7657
7658PyObject *
7659PyUnicode_EncodeCodePage(int code_page,
7660 PyObject *unicode,
7661 const char *errors)
7662{
7663 const Py_UNICODE *p;
7664 Py_ssize_t size;
7665 p = PyUnicode_AsUnicodeAndSize(unicode, &size);
7666 if (p == NULL)
7667 return NULL;
7668 return encode_code_page(code_page, p, size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007669}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007670
Alexander Belopolsky40018472011-02-26 01:02:56 +00007671PyObject *
7672PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007673{
7674 if (!PyUnicode_Check(unicode)) {
7675 PyErr_BadArgument();
7676 return NULL;
7677 }
7678 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007679 PyUnicode_GET_SIZE(unicode),
7680 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007681}
7682
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007683#undef NEED_RETRY
7684
Victor Stinner99b95382011-07-04 14:23:54 +02007685#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007686
Guido van Rossumd57fd912000-03-10 22:53:23 +00007687/* --- Character Mapping Codec -------------------------------------------- */
7688
Alexander Belopolsky40018472011-02-26 01:02:56 +00007689PyObject *
7690PyUnicode_DecodeCharmap(const char *s,
7691 Py_ssize_t size,
7692 PyObject *mapping,
7693 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007694{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007695 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007696 Py_ssize_t startinpos;
7697 Py_ssize_t endinpos;
7698 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007699 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007700 PyUnicodeObject *v;
7701 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007702 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007703 PyObject *errorHandler = NULL;
7704 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007705 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007706 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007707
Guido van Rossumd57fd912000-03-10 22:53:23 +00007708 /* Default to Latin-1 */
7709 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007710 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007711
7712 v = _PyUnicode_New(size);
7713 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007715 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007716 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007718 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007719 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 mapstring = PyUnicode_AS_UNICODE(mapping);
7721 maplen = PyUnicode_GET_SIZE(mapping);
7722 while (s < e) {
7723 unsigned char ch = *s;
7724 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007725
Benjamin Peterson29060642009-01-31 22:14:21 +00007726 if (ch < maplen)
7727 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007728
Benjamin Peterson29060642009-01-31 22:14:21 +00007729 if (x == 0xfffe) {
7730 /* undefined mapping */
7731 outpos = p-PyUnicode_AS_UNICODE(v);
7732 startinpos = s-starts;
7733 endinpos = startinpos+1;
7734 if (unicode_decode_call_errorhandler(
7735 errors, &errorHandler,
7736 "charmap", "character maps to <undefined>",
7737 &starts, &e, &startinpos, &endinpos, &exc, &s,
7738 &v, &outpos, &p)) {
7739 goto onError;
7740 }
7741 continue;
7742 }
7743 *p++ = x;
7744 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007745 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007746 }
7747 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007748 while (s < e) {
7749 unsigned char ch = *s;
7750 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007751
Benjamin Peterson29060642009-01-31 22:14:21 +00007752 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7753 w = PyLong_FromLong((long)ch);
7754 if (w == NULL)
7755 goto onError;
7756 x = PyObject_GetItem(mapping, w);
7757 Py_DECREF(w);
7758 if (x == NULL) {
7759 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7760 /* No mapping found means: mapping is undefined. */
7761 PyErr_Clear();
7762 x = Py_None;
7763 Py_INCREF(x);
7764 } else
7765 goto onError;
7766 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007767
Benjamin Peterson29060642009-01-31 22:14:21 +00007768 /* Apply mapping */
7769 if (PyLong_Check(x)) {
7770 long value = PyLong_AS_LONG(x);
7771 if (value < 0 || value > 65535) {
7772 PyErr_SetString(PyExc_TypeError,
7773 "character mapping must be in range(65536)");
7774 Py_DECREF(x);
7775 goto onError;
7776 }
7777 *p++ = (Py_UNICODE)value;
7778 }
7779 else if (x == Py_None) {
7780 /* undefined mapping */
7781 outpos = p-PyUnicode_AS_UNICODE(v);
7782 startinpos = s-starts;
7783 endinpos = startinpos+1;
7784 if (unicode_decode_call_errorhandler(
7785 errors, &errorHandler,
7786 "charmap", "character maps to <undefined>",
7787 &starts, &e, &startinpos, &endinpos, &exc, &s,
7788 &v, &outpos, &p)) {
7789 Py_DECREF(x);
7790 goto onError;
7791 }
7792 Py_DECREF(x);
7793 continue;
7794 }
7795 else if (PyUnicode_Check(x)) {
7796 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007797
Benjamin Peterson29060642009-01-31 22:14:21 +00007798 if (targetsize == 1)
7799 /* 1-1 mapping */
7800 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007801
Benjamin Peterson29060642009-01-31 22:14:21 +00007802 else if (targetsize > 1) {
7803 /* 1-n mapping */
7804 if (targetsize > extrachars) {
7805 /* resize first */
7806 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7807 Py_ssize_t needed = (targetsize - extrachars) + \
7808 (targetsize << 2);
7809 extrachars += needed;
7810 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007811 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007812 PyUnicode_GET_SIZE(v) + needed) < 0) {
7813 Py_DECREF(x);
7814 goto onError;
7815 }
7816 p = PyUnicode_AS_UNICODE(v) + oldpos;
7817 }
7818 Py_UNICODE_COPY(p,
7819 PyUnicode_AS_UNICODE(x),
7820 targetsize);
7821 p += targetsize;
7822 extrachars -= targetsize;
7823 }
7824 /* 1-0 mapping: skip the character */
7825 }
7826 else {
7827 /* wrong return value */
7828 PyErr_SetString(PyExc_TypeError,
7829 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007830 Py_DECREF(x);
7831 goto onError;
7832 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007833 Py_DECREF(x);
7834 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007835 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007836 }
7837 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007838 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007839 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007840 Py_XDECREF(errorHandler);
7841 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007842#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007843 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007844 Py_DECREF(v);
7845 return NULL;
7846 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007847#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007848 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007849 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007850
Benjamin Peterson29060642009-01-31 22:14:21 +00007851 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007852 Py_XDECREF(errorHandler);
7853 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007854 Py_XDECREF(v);
7855 return NULL;
7856}
7857
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858/* Charmap encoding: the lookup table */
7859
Alexander Belopolsky40018472011-02-26 01:02:56 +00007860struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007861 PyObject_HEAD
7862 unsigned char level1[32];
7863 int count2, count3;
7864 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007865};
7866
7867static PyObject*
7868encoding_map_size(PyObject *obj, PyObject* args)
7869{
7870 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007871 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007872 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873}
7874
7875static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007876 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007877 PyDoc_STR("Return the size (in bytes) of this object") },
7878 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007879};
7880
7881static void
7882encoding_map_dealloc(PyObject* o)
7883{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007884 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007885}
7886
7887static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007888 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007889 "EncodingMap", /*tp_name*/
7890 sizeof(struct encoding_map), /*tp_basicsize*/
7891 0, /*tp_itemsize*/
7892 /* methods */
7893 encoding_map_dealloc, /*tp_dealloc*/
7894 0, /*tp_print*/
7895 0, /*tp_getattr*/
7896 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007897 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007898 0, /*tp_repr*/
7899 0, /*tp_as_number*/
7900 0, /*tp_as_sequence*/
7901 0, /*tp_as_mapping*/
7902 0, /*tp_hash*/
7903 0, /*tp_call*/
7904 0, /*tp_str*/
7905 0, /*tp_getattro*/
7906 0, /*tp_setattro*/
7907 0, /*tp_as_buffer*/
7908 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7909 0, /*tp_doc*/
7910 0, /*tp_traverse*/
7911 0, /*tp_clear*/
7912 0, /*tp_richcompare*/
7913 0, /*tp_weaklistoffset*/
7914 0, /*tp_iter*/
7915 0, /*tp_iternext*/
7916 encoding_map_methods, /*tp_methods*/
7917 0, /*tp_members*/
7918 0, /*tp_getset*/
7919 0, /*tp_base*/
7920 0, /*tp_dict*/
7921 0, /*tp_descr_get*/
7922 0, /*tp_descr_set*/
7923 0, /*tp_dictoffset*/
7924 0, /*tp_init*/
7925 0, /*tp_alloc*/
7926 0, /*tp_new*/
7927 0, /*tp_free*/
7928 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007929};
7930
7931PyObject*
7932PyUnicode_BuildEncodingMap(PyObject* string)
7933{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007934 PyObject *result;
7935 struct encoding_map *mresult;
7936 int i;
7937 int need_dict = 0;
7938 unsigned char level1[32];
7939 unsigned char level2[512];
7940 unsigned char *mlevel1, *mlevel2, *mlevel3;
7941 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007942 int kind;
7943 void *data;
7944 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007946 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007947 PyErr_BadArgument();
7948 return NULL;
7949 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007950 kind = PyUnicode_KIND(string);
7951 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 memset(level1, 0xFF, sizeof level1);
7953 memset(level2, 0xFF, sizeof level2);
7954
7955 /* If there isn't a one-to-one mapping of NULL to \0,
7956 or if there are non-BMP characters, we need to use
7957 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007958 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007959 need_dict = 1;
7960 for (i = 1; i < 256; i++) {
7961 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007962 ch = PyUnicode_READ(kind, data, i);
7963 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007964 need_dict = 1;
7965 break;
7966 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007967 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007968 /* unmapped character */
7969 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007970 l1 = ch >> 11;
7971 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007972 if (level1[l1] == 0xFF)
7973 level1[l1] = count2++;
7974 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007975 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007976 }
7977
7978 if (count2 >= 0xFF || count3 >= 0xFF)
7979 need_dict = 1;
7980
7981 if (need_dict) {
7982 PyObject *result = PyDict_New();
7983 PyObject *key, *value;
7984 if (!result)
7985 return NULL;
7986 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007987 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007988 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007989 if (!key || !value)
7990 goto failed1;
7991 if (PyDict_SetItem(result, key, value) == -1)
7992 goto failed1;
7993 Py_DECREF(key);
7994 Py_DECREF(value);
7995 }
7996 return result;
7997 failed1:
7998 Py_XDECREF(key);
7999 Py_XDECREF(value);
8000 Py_DECREF(result);
8001 return NULL;
8002 }
8003
8004 /* Create a three-level trie */
8005 result = PyObject_MALLOC(sizeof(struct encoding_map) +
8006 16*count2 + 128*count3 - 1);
8007 if (!result)
8008 return PyErr_NoMemory();
8009 PyObject_Init(result, &EncodingMapType);
8010 mresult = (struct encoding_map*)result;
8011 mresult->count2 = count2;
8012 mresult->count3 = count3;
8013 mlevel1 = mresult->level1;
8014 mlevel2 = mresult->level23;
8015 mlevel3 = mresult->level23 + 16*count2;
8016 memcpy(mlevel1, level1, 32);
8017 memset(mlevel2, 0xFF, 16*count2);
8018 memset(mlevel3, 0, 128*count3);
8019 count3 = 0;
8020 for (i = 1; i < 256; i++) {
8021 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008022 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008023 /* unmapped character */
8024 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008025 o1 = PyUnicode_READ(kind, data, i)>>11;
8026 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008027 i2 = 16*mlevel1[o1] + o2;
8028 if (mlevel2[i2] == 0xFF)
8029 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008030 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008031 i3 = 128*mlevel2[i2] + o3;
8032 mlevel3[i3] = i;
8033 }
8034 return result;
8035}
8036
8037static int
8038encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
8039{
8040 struct encoding_map *map = (struct encoding_map*)mapping;
8041 int l1 = c>>11;
8042 int l2 = (c>>7) & 0xF;
8043 int l3 = c & 0x7F;
8044 int i;
8045
8046#ifdef Py_UNICODE_WIDE
8047 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008048 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008049 }
8050#endif
8051 if (c == 0)
8052 return 0;
8053 /* level 1*/
8054 i = map->level1[l1];
8055 if (i == 0xFF) {
8056 return -1;
8057 }
8058 /* level 2*/
8059 i = map->level23[16*i+l2];
8060 if (i == 0xFF) {
8061 return -1;
8062 }
8063 /* level 3 */
8064 i = map->level23[16*map->count2 + 128*i + l3];
8065 if (i == 0) {
8066 return -1;
8067 }
8068 return i;
8069}
8070
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008071/* Lookup the character ch in the mapping. If the character
8072 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008073 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008074static PyObject *
8075charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008076{
Christian Heimes217cfd12007-12-02 14:31:20 +00008077 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008078 PyObject *x;
8079
8080 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008081 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008082 x = PyObject_GetItem(mapping, w);
8083 Py_DECREF(w);
8084 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008085 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8086 /* No mapping found means: mapping is undefined. */
8087 PyErr_Clear();
8088 x = Py_None;
8089 Py_INCREF(x);
8090 return x;
8091 } else
8092 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008093 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008094 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008096 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008097 long value = PyLong_AS_LONG(x);
8098 if (value < 0 || value > 255) {
8099 PyErr_SetString(PyExc_TypeError,
8100 "character mapping must be in range(256)");
8101 Py_DECREF(x);
8102 return NULL;
8103 }
8104 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008105 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008106 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008108 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008109 /* wrong return value */
8110 PyErr_Format(PyExc_TypeError,
8111 "character mapping must return integer, bytes or None, not %.400s",
8112 x->ob_type->tp_name);
8113 Py_DECREF(x);
8114 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008115 }
8116}
8117
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008118static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008119charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008120{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8122 /* exponentially overallocate to minimize reallocations */
8123 if (requiredsize < 2*outsize)
8124 requiredsize = 2*outsize;
8125 if (_PyBytes_Resize(outobj, requiredsize))
8126 return -1;
8127 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008128}
8129
Benjamin Peterson14339b62009-01-31 16:36:08 +00008130typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008132} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008133/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008134 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135 space is available. Return a new reference to the object that
8136 was put in the output buffer, or Py_None, if the mapping was undefined
8137 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008138 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008139static charmapencode_result
8140charmapencode_output(Py_UNICODE c, PyObject *mapping,
8141 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008142{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 PyObject *rep;
8144 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008145 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146
Christian Heimes90aa7642007-12-19 02:45:37 +00008147 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008148 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008150 if (res == -1)
8151 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 if (outsize<requiredsize)
8153 if (charmapencode_resize(outobj, outpos, requiredsize))
8154 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008155 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008156 outstart[(*outpos)++] = (char)res;
8157 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008158 }
8159
8160 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008161 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008162 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008163 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008164 Py_DECREF(rep);
8165 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008166 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008167 if (PyLong_Check(rep)) {
8168 Py_ssize_t requiredsize = *outpos+1;
8169 if (outsize<requiredsize)
8170 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8171 Py_DECREF(rep);
8172 return enc_EXCEPTION;
8173 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008174 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008175 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008176 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008177 else {
8178 const char *repchars = PyBytes_AS_STRING(rep);
8179 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8180 Py_ssize_t requiredsize = *outpos+repsize;
8181 if (outsize<requiredsize)
8182 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8183 Py_DECREF(rep);
8184 return enc_EXCEPTION;
8185 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008186 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008187 memcpy(outstart + *outpos, repchars, repsize);
8188 *outpos += repsize;
8189 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008190 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008191 Py_DECREF(rep);
8192 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008193}
8194
8195/* handle an error in PyUnicode_EncodeCharmap
8196 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008197static int
8198charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008199 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008200 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008201 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008202 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008203{
8204 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008205 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008206 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008207 Py_UNICODE *uni2;
8208 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008209 Py_ssize_t collstartpos = *inpos;
8210 Py_ssize_t collendpos = *inpos+1;
8211 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008212 char *encoding = "charmap";
8213 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008214 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008215 Py_UCS4 ch;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008216
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008217 if (PyUnicode_READY(unicode) < 0)
8218 return -1;
8219 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008220 /* find all unencodable characters */
8221 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008222 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008223 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008224 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8225 int res = encoding_map_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 if (res != -1)
8227 break;
8228 ++collendpos;
8229 continue;
8230 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008231
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008232 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8233 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008234 if (rep==NULL)
8235 return -1;
8236 else if (rep!=Py_None) {
8237 Py_DECREF(rep);
8238 break;
8239 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008240 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 }
8243 /* cache callback name lookup
8244 * (if not done yet, i.e. it's the first error) */
8245 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008246 if ((errors==NULL) || (!strcmp(errors, "strict")))
8247 *known_errorHandler = 1;
8248 else if (!strcmp(errors, "replace"))
8249 *known_errorHandler = 2;
8250 else if (!strcmp(errors, "ignore"))
8251 *known_errorHandler = 3;
8252 else if (!strcmp(errors, "xmlcharrefreplace"))
8253 *known_errorHandler = 4;
8254 else
8255 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256 }
8257 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008258 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008259 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008260 return -1;
8261 case 2: /* replace */
8262 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 x = charmapencode_output('?', mapping, res, respos);
8264 if (x==enc_EXCEPTION) {
8265 return -1;
8266 }
8267 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008268 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008269 return -1;
8270 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008271 }
8272 /* fall through */
8273 case 3: /* ignore */
8274 *inpos = collendpos;
8275 break;
8276 case 4: /* xmlcharrefreplace */
8277 /* generate replacement (temporarily (mis)uses p) */
8278 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008279 char buffer[2+29+1+1];
8280 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008281 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 for (cp = buffer; *cp; ++cp) {
8283 x = charmapencode_output(*cp, mapping, res, respos);
8284 if (x==enc_EXCEPTION)
8285 return -1;
8286 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008287 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008288 return -1;
8289 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008290 }
8291 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008292 *inpos = collendpos;
8293 break;
8294 default:
8295 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008296 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008297 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008298 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008299 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008300 if (PyBytes_Check(repunicode)) {
8301 /* Directly copy bytes result to output. */
8302 Py_ssize_t outsize = PyBytes_Size(*res);
8303 Py_ssize_t requiredsize;
8304 repsize = PyBytes_Size(repunicode);
8305 requiredsize = *respos + repsize;
8306 if (requiredsize > outsize)
8307 /* Make room for all additional bytes. */
8308 if (charmapencode_resize(res, respos, requiredsize)) {
8309 Py_DECREF(repunicode);
8310 return -1;
8311 }
8312 memcpy(PyBytes_AsString(*res) + *respos,
8313 PyBytes_AsString(repunicode), repsize);
8314 *respos += repsize;
8315 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008316 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008317 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008318 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008319 /* generate replacement */
8320 repsize = PyUnicode_GET_SIZE(repunicode);
8321 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008322 x = charmapencode_output(*uni2, mapping, res, respos);
8323 if (x==enc_EXCEPTION) {
8324 return -1;
8325 }
8326 else if (x==enc_FAILED) {
8327 Py_DECREF(repunicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008328 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 return -1;
8330 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008331 }
8332 *inpos = newpos;
8333 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334 }
8335 return 0;
8336}
8337
Alexander Belopolsky40018472011-02-26 01:02:56 +00008338PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008339_PyUnicode_EncodeCharmap(PyObject *unicode,
8340 PyObject *mapping,
8341 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008342{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 /* output object */
8344 PyObject *res = NULL;
8345 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008346 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008347 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008349 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350 PyObject *errorHandler = NULL;
8351 PyObject *exc = NULL;
8352 /* the following variable is used for caching string comparisons
8353 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8354 * 3=ignore, 4=xmlcharrefreplace */
8355 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008356
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008357 if (PyUnicode_READY(unicode) < 0)
8358 return NULL;
8359 size = PyUnicode_GET_LENGTH(unicode);
8360
Guido van Rossumd57fd912000-03-10 22:53:23 +00008361 /* Default to Latin-1 */
8362 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008363 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008364
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365 /* allocate enough for a simple encoding without
8366 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008367 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 if (res == NULL)
8369 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008370 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008372
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008376 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 if (x==enc_EXCEPTION) /* error */
8378 goto onError;
8379 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008380 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 &exc,
8382 &known_errorHandler, &errorHandler, errors,
8383 &res, &respos)) {
8384 goto onError;
8385 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008386 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008387 else
8388 /* done with this character => adjust input position */
8389 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008392 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008393 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008394 if (_PyBytes_Resize(&res, respos) < 0)
8395 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008396
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008397 Py_XDECREF(exc);
8398 Py_XDECREF(errorHandler);
8399 return res;
8400
Benjamin Peterson29060642009-01-31 22:14:21 +00008401 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402 Py_XDECREF(res);
8403 Py_XDECREF(exc);
8404 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008405 return NULL;
8406}
8407
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008408/* Deprecated */
8409PyObject *
8410PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8411 Py_ssize_t size,
8412 PyObject *mapping,
8413 const char *errors)
8414{
8415 PyObject *result;
8416 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8417 if (unicode == NULL)
8418 return NULL;
8419 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8420 Py_DECREF(unicode);
8421 return NULL;
8422}
8423
Alexander Belopolsky40018472011-02-26 01:02:56 +00008424PyObject *
8425PyUnicode_AsCharmapString(PyObject *unicode,
8426 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427{
8428 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008429 PyErr_BadArgument();
8430 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008431 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008432 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008433}
8434
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008435/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008436static void
8437make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008438 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008439 Py_ssize_t startpos, Py_ssize_t endpos,
8440 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008441{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008442 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008443 *exceptionObject = _PyUnicodeTranslateError_Create(
8444 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008445 }
8446 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008447 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8448 goto onError;
8449 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8450 goto onError;
8451 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8452 goto onError;
8453 return;
8454 onError:
8455 Py_DECREF(*exceptionObject);
8456 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008457 }
8458}
8459
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008461static void
8462raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008463 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008464 Py_ssize_t startpos, Py_ssize_t endpos,
8465 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466{
8467 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008468 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008469 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008471}
8472
8473/* error handling callback helper:
8474 build arguments, call the callback and check the arguments,
8475 put the result into newpos and return the replacement string, which
8476 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008477static PyObject *
8478unicode_translate_call_errorhandler(const char *errors,
8479 PyObject **errorHandler,
8480 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008481 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008482 Py_ssize_t startpos, Py_ssize_t endpos,
8483 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008485 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008487 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 PyObject *restuple;
8489 PyObject *resunicode;
8490
8491 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495 }
8496
8497 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008498 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008499 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501
8502 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008505 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008506 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008507 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008508 Py_DECREF(restuple);
8509 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008510 }
8511 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008512 &resunicode, &i_newpos)) {
8513 Py_DECREF(restuple);
8514 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008515 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008516 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008517 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008518 else
8519 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008520 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008521 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8522 Py_DECREF(restuple);
8523 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008524 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525 Py_INCREF(resunicode);
8526 Py_DECREF(restuple);
8527 return resunicode;
8528}
8529
8530/* Lookup the character ch in the mapping and put the result in result,
8531 which must be decrefed by the caller.
8532 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008533static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008534charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535{
Christian Heimes217cfd12007-12-02 14:31:20 +00008536 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 PyObject *x;
8538
8539 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008540 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541 x = PyObject_GetItem(mapping, w);
8542 Py_DECREF(w);
8543 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8545 /* No mapping found means: use 1:1 mapping. */
8546 PyErr_Clear();
8547 *result = NULL;
8548 return 0;
8549 } else
8550 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551 }
8552 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008553 *result = x;
8554 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008555 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008556 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008557 long value = PyLong_AS_LONG(x);
8558 long max = PyUnicode_GetMax();
8559 if (value < 0 || value > max) {
8560 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008561 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008562 Py_DECREF(x);
8563 return -1;
8564 }
8565 *result = x;
8566 return 0;
8567 }
8568 else if (PyUnicode_Check(x)) {
8569 *result = x;
8570 return 0;
8571 }
8572 else {
8573 /* wrong return value */
8574 PyErr_SetString(PyExc_TypeError,
8575 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008576 Py_DECREF(x);
8577 return -1;
8578 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008579}
8580/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008581 if not reallocate and adjust various state variables.
8582 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008583static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008586{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008587 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008588 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 /* exponentially overallocate to minimize reallocations */
8590 if (requiredsize < 2 * oldsize)
8591 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8593 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008594 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008596 }
8597 return 0;
8598}
8599/* lookup the character, put the result in the output string and adjust
8600 various state variables. Return a new reference to the object that
8601 was put in the output buffer in *result, or Py_None, if the mapping was
8602 undefined (in which case no character was written).
8603 The called must decref result.
8604 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008605static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008606charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8607 PyObject *mapping, Py_UCS4 **output,
8608 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008609 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008610{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8612 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008614 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 }
8618 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008620 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008621 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008623 }
8624 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 Py_ssize_t repsize;
8626 if (PyUnicode_READY(*res) == -1)
8627 return -1;
8628 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 if (repsize==1) {
8630 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 }
8633 else if (repsize!=0) {
8634 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 Py_ssize_t requiredsize = *opos +
8636 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008638 Py_ssize_t i;
8639 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 for(i = 0; i < repsize; i++)
8642 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008643 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 }
8645 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008646 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008647 return 0;
8648}
8649
Alexander Belopolsky40018472011-02-26 01:02:56 +00008650PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008651_PyUnicode_TranslateCharmap(PyObject *input,
8652 PyObject *mapping,
8653 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008654{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 /* input object */
8656 char *idata;
8657 Py_ssize_t size, i;
8658 int kind;
8659 /* output buffer */
8660 Py_UCS4 *output = NULL;
8661 Py_ssize_t osize;
8662 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008663 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 char *reason = "character maps to <undefined>";
8666 PyObject *errorHandler = NULL;
8667 PyObject *exc = NULL;
8668 /* the following variable is used for caching string comparisons
8669 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8670 * 3=ignore, 4=xmlcharrefreplace */
8671 int known_errorHandler = -1;
8672
Guido van Rossumd57fd912000-03-10 22:53:23 +00008673 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008674 PyErr_BadArgument();
8675 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008676 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 if (PyUnicode_READY(input) == -1)
8679 return NULL;
8680 idata = (char*)PyUnicode_DATA(input);
8681 kind = PyUnicode_KIND(input);
8682 size = PyUnicode_GET_LENGTH(input);
8683 i = 0;
8684
8685 if (size == 0) {
8686 Py_INCREF(input);
8687 return input;
8688 }
8689
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008690 /* allocate enough for a simple 1:1 translation without
8691 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008692 osize = size;
8693 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8694 opos = 0;
8695 if (output == NULL) {
8696 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008698 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008700 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008701 /* try to encode it */
8702 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 if (charmaptranslate_output(input, i, mapping,
8704 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 Py_XDECREF(x);
8706 goto onError;
8707 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008708 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008709 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008710 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008711 else { /* untranslatable character */
8712 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8713 Py_ssize_t repsize;
8714 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008715 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008716 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008717 Py_ssize_t collstart = i;
8718 Py_ssize_t collend = i+1;
8719 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008720
Benjamin Peterson29060642009-01-31 22:14:21 +00008721 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008722 while (collend < size) {
8723 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008724 goto onError;
8725 Py_XDECREF(x);
8726 if (x!=Py_None)
8727 break;
8728 ++collend;
8729 }
8730 /* cache callback name lookup
8731 * (if not done yet, i.e. it's the first error) */
8732 if (known_errorHandler==-1) {
8733 if ((errors==NULL) || (!strcmp(errors, "strict")))
8734 known_errorHandler = 1;
8735 else if (!strcmp(errors, "replace"))
8736 known_errorHandler = 2;
8737 else if (!strcmp(errors, "ignore"))
8738 known_errorHandler = 3;
8739 else if (!strcmp(errors, "xmlcharrefreplace"))
8740 known_errorHandler = 4;
8741 else
8742 known_errorHandler = 0;
8743 }
8744 switch (known_errorHandler) {
8745 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008746 raise_translate_exception(&exc, input, collstart,
8747 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008748 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008749 case 2: /* replace */
8750 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008751 for (coll = collstart; coll<collend; coll++)
8752 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008753 /* fall through */
8754 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008755 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008756 break;
8757 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008758 /* generate replacement (temporarily (mis)uses i) */
8759 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008760 char buffer[2+29+1+1];
8761 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008762 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8763 if (charmaptranslate_makespace(&output, &osize,
8764 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 goto onError;
8766 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008768 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008769 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 break;
8771 default:
8772 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008773 reason, input, &exc,
8774 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008775 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008776 goto onError;
8777 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 repsize = PyUnicode_GET_LENGTH(repunicode);
8779 if (charmaptranslate_makespace(&output, &osize,
8780 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 Py_DECREF(repunicode);
8782 goto onError;
8783 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008784 for (uni2 = 0; repsize-->0; ++uni2)
8785 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8786 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008787 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008788 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008789 }
8790 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008791 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8792 if (!res)
8793 goto onError;
8794 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008795 Py_XDECREF(exc);
8796 Py_XDECREF(errorHandler);
8797 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008798
Benjamin Peterson29060642009-01-31 22:14:21 +00008799 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008801 Py_XDECREF(exc);
8802 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008803 return NULL;
8804}
8805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008806/* Deprecated. Use PyUnicode_Translate instead. */
8807PyObject *
8808PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8809 Py_ssize_t size,
8810 PyObject *mapping,
8811 const char *errors)
8812{
8813 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8814 if (!unicode)
8815 return NULL;
8816 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8817}
8818
Alexander Belopolsky40018472011-02-26 01:02:56 +00008819PyObject *
8820PyUnicode_Translate(PyObject *str,
8821 PyObject *mapping,
8822 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008823{
8824 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008825
Guido van Rossumd57fd912000-03-10 22:53:23 +00008826 str = PyUnicode_FromObject(str);
8827 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008828 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008829 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008830 Py_DECREF(str);
8831 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008832
Benjamin Peterson29060642009-01-31 22:14:21 +00008833 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008834 Py_XDECREF(str);
8835 return NULL;
8836}
Tim Petersced69f82003-09-16 20:30:58 +00008837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008838static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008839fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008840{
8841 /* No need to call PyUnicode_READY(self) because this function is only
8842 called as a callback from fixup() which does it already. */
8843 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8844 const int kind = PyUnicode_KIND(self);
8845 void *data = PyUnicode_DATA(self);
8846 Py_UCS4 maxchar = 0, ch, fixed;
8847 Py_ssize_t i;
8848
8849 for (i = 0; i < len; ++i) {
8850 ch = PyUnicode_READ(kind, data, i);
8851 fixed = 0;
8852 if (ch > 127) {
8853 if (Py_UNICODE_ISSPACE(ch))
8854 fixed = ' ';
8855 else {
8856 const int decimal = Py_UNICODE_TODECIMAL(ch);
8857 if (decimal >= 0)
8858 fixed = '0' + decimal;
8859 }
8860 if (fixed != 0) {
8861 if (fixed > maxchar)
8862 maxchar = fixed;
8863 PyUnicode_WRITE(kind, data, i, fixed);
8864 }
8865 else if (ch > maxchar)
8866 maxchar = ch;
8867 }
8868 else if (ch > maxchar)
8869 maxchar = ch;
8870 }
8871
8872 return maxchar;
8873}
8874
8875PyObject *
8876_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8877{
8878 if (!PyUnicode_Check(unicode)) {
8879 PyErr_BadInternalCall();
8880 return NULL;
8881 }
8882 if (PyUnicode_READY(unicode) == -1)
8883 return NULL;
8884 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8885 /* If the string is already ASCII, just return the same string */
8886 Py_INCREF(unicode);
8887 return unicode;
8888 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008889 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008890}
8891
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008892PyObject *
8893PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8894 Py_ssize_t length)
8895{
8896 PyObject *result;
8897 Py_UNICODE *p; /* write pointer into result */
8898 Py_ssize_t i;
8899 /* Copy to a new string */
8900 result = (PyObject *)_PyUnicode_New(length);
8901 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8902 if (result == NULL)
8903 return result;
8904 p = PyUnicode_AS_UNICODE(result);
8905 /* Iterate over code points */
8906 for (i = 0; i < length; i++) {
8907 Py_UNICODE ch =s[i];
8908 if (ch > 127) {
8909 int decimal = Py_UNICODE_TODECIMAL(ch);
8910 if (decimal >= 0)
8911 p[i] = '0' + decimal;
8912 }
8913 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008914#ifndef DONT_MAKE_RESULT_READY
8915 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008916 Py_DECREF(result);
8917 return NULL;
8918 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008919#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008920 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008921 return result;
8922}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008923/* --- Decimal Encoder ---------------------------------------------------- */
8924
Alexander Belopolsky40018472011-02-26 01:02:56 +00008925int
8926PyUnicode_EncodeDecimal(Py_UNICODE *s,
8927 Py_ssize_t length,
8928 char *output,
8929 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008930{
8931 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008932 PyObject *errorHandler = NULL;
8933 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008934 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008935 const char *encoding = "decimal";
8936 const char *reason = "invalid decimal Unicode string";
8937 /* the following variable is used for caching string comparisons
8938 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8939 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008940
8941 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 PyErr_BadArgument();
8943 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008944 }
8945
8946 p = s;
8947 end = s + length;
8948 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008949 register Py_UNICODE ch = *p;
8950 int decimal;
8951 PyObject *repunicode;
8952 Py_ssize_t repsize;
8953 Py_ssize_t newpos;
8954 Py_UNICODE *uni2;
8955 Py_UNICODE *collstart;
8956 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008957
Benjamin Peterson29060642009-01-31 22:14:21 +00008958 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008959 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008960 ++p;
8961 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008962 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008963 decimal = Py_UNICODE_TODECIMAL(ch);
8964 if (decimal >= 0) {
8965 *output++ = '0' + decimal;
8966 ++p;
8967 continue;
8968 }
8969 if (0 < ch && ch < 256) {
8970 *output++ = (char)ch;
8971 ++p;
8972 continue;
8973 }
8974 /* All other characters are considered unencodable */
8975 collstart = p;
8976 collend = p+1;
8977 while (collend < end) {
8978 if ((0 < *collend && *collend < 256) ||
8979 !Py_UNICODE_ISSPACE(*collend) ||
8980 Py_UNICODE_TODECIMAL(*collend))
8981 break;
8982 }
8983 /* cache callback name lookup
8984 * (if not done yet, i.e. it's the first error) */
8985 if (known_errorHandler==-1) {
8986 if ((errors==NULL) || (!strcmp(errors, "strict")))
8987 known_errorHandler = 1;
8988 else if (!strcmp(errors, "replace"))
8989 known_errorHandler = 2;
8990 else if (!strcmp(errors, "ignore"))
8991 known_errorHandler = 3;
8992 else if (!strcmp(errors, "xmlcharrefreplace"))
8993 known_errorHandler = 4;
8994 else
8995 known_errorHandler = 0;
8996 }
8997 switch (known_errorHandler) {
8998 case 1: /* strict */
8999 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
9000 goto onError;
9001 case 2: /* replace */
9002 for (p = collstart; p < collend; ++p)
9003 *output++ = '?';
9004 /* fall through */
9005 case 3: /* ignore */
9006 p = collend;
9007 break;
9008 case 4: /* xmlcharrefreplace */
9009 /* generate replacement (temporarily (mis)uses p) */
9010 for (p = collstart; p < collend; ++p)
9011 output += sprintf(output, "&#%d;", (int)*p);
9012 p = collend;
9013 break;
9014 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009015 unicode = PyUnicode_FromUnicode(s, length);
9016 if (unicode == NULL)
9017 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009018 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009019 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009020 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009021 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00009022 if (repunicode == NULL)
9023 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009024 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00009025 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009026 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
9027 Py_DECREF(repunicode);
9028 goto onError;
9029 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009030 /* generate replacement */
9031 repsize = PyUnicode_GET_SIZE(repunicode);
9032 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
9033 Py_UNICODE ch = *uni2;
9034 if (Py_UNICODE_ISSPACE(ch))
9035 *output++ = ' ';
9036 else {
9037 decimal = Py_UNICODE_TODECIMAL(ch);
9038 if (decimal >= 0)
9039 *output++ = '0' + decimal;
9040 else if (0 < ch && ch < 256)
9041 *output++ = (char)ch;
9042 else {
9043 Py_DECREF(repunicode);
9044 raise_encode_exception(&exc, encoding,
9045 s, length, collstart-s, collend-s, reason);
9046 goto onError;
9047 }
9048 }
9049 }
9050 p = s + newpos;
9051 Py_DECREF(repunicode);
9052 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00009053 }
9054 /* 0-terminate the output string */
9055 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009056 Py_XDECREF(exc);
9057 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009058 return 0;
9059
Benjamin Peterson29060642009-01-31 22:14:21 +00009060 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009061 Py_XDECREF(exc);
9062 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009063 return -1;
9064}
9065
Guido van Rossumd57fd912000-03-10 22:53:23 +00009066/* --- Helpers ------------------------------------------------------------ */
9067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009069any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009070 Py_ssize_t start,
9071 Py_ssize_t end)
9072{
9073 int kind1, kind2, kind;
9074 void *buf1, *buf2;
9075 Py_ssize_t len1, len2, result;
9076
9077 kind1 = PyUnicode_KIND(s1);
9078 kind2 = PyUnicode_KIND(s2);
9079 kind = kind1 > kind2 ? kind1 : kind2;
9080 buf1 = PyUnicode_DATA(s1);
9081 buf2 = PyUnicode_DATA(s2);
9082 if (kind1 != kind)
9083 buf1 = _PyUnicode_AsKind(s1, kind);
9084 if (!buf1)
9085 return -2;
9086 if (kind2 != kind)
9087 buf2 = _PyUnicode_AsKind(s2, kind);
9088 if (!buf2) {
9089 if (kind1 != kind) PyMem_Free(buf1);
9090 return -2;
9091 }
9092 len1 = PyUnicode_GET_LENGTH(s1);
9093 len2 = PyUnicode_GET_LENGTH(s2);
9094
Victor Stinner794d5672011-10-10 03:21:36 +02009095 if (direction > 0) {
9096 switch(kind) {
9097 case PyUnicode_1BYTE_KIND:
9098 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9099 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9100 else
9101 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9102 break;
9103 case PyUnicode_2BYTE_KIND:
9104 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9105 break;
9106 case PyUnicode_4BYTE_KIND:
9107 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9108 break;
9109 default:
9110 assert(0); result = -2;
9111 }
9112 }
9113 else {
9114 switch(kind) {
9115 case PyUnicode_1BYTE_KIND:
9116 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9117 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9118 else
9119 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9120 break;
9121 case PyUnicode_2BYTE_KIND:
9122 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9123 break;
9124 case PyUnicode_4BYTE_KIND:
9125 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9126 break;
9127 default:
9128 assert(0); result = -2;
9129 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 }
9131
9132 if (kind1 != kind)
9133 PyMem_Free(buf1);
9134 if (kind2 != kind)
9135 PyMem_Free(buf2);
9136
9137 return result;
9138}
9139
9140Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009141_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009142 Py_ssize_t n_buffer,
9143 void *digits, Py_ssize_t n_digits,
9144 Py_ssize_t min_width,
9145 const char *grouping,
9146 const char *thousands_sep)
9147{
9148 switch(kind) {
9149 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009150 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9151 return _PyUnicode_ascii_InsertThousandsGrouping(
9152 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9153 min_width, grouping, thousands_sep);
9154 else
9155 return _PyUnicode_ucs1_InsertThousandsGrouping(
9156 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9157 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009158 case PyUnicode_2BYTE_KIND:
9159 return _PyUnicode_ucs2_InsertThousandsGrouping(
9160 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9161 min_width, grouping, thousands_sep);
9162 case PyUnicode_4BYTE_KIND:
9163 return _PyUnicode_ucs4_InsertThousandsGrouping(
9164 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9165 min_width, grouping, thousands_sep);
9166 }
9167 assert(0);
9168 return -1;
9169}
9170
9171
Thomas Wouters477c8d52006-05-27 19:21:47 +00009172/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009173#define ADJUST_INDICES(start, end, len) \
9174 if (end > len) \
9175 end = len; \
9176 else if (end < 0) { \
9177 end += len; \
9178 if (end < 0) \
9179 end = 0; \
9180 } \
9181 if (start < 0) { \
9182 start += len; \
9183 if (start < 0) \
9184 start = 0; \
9185 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009186
Alexander Belopolsky40018472011-02-26 01:02:56 +00009187Py_ssize_t
9188PyUnicode_Count(PyObject *str,
9189 PyObject *substr,
9190 Py_ssize_t start,
9191 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009192{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009193 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009194 PyObject* str_obj;
9195 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196 int kind1, kind2, kind;
9197 void *buf1 = NULL, *buf2 = NULL;
9198 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009199
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009200 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009201 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009202 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009203 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009204 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009205 Py_DECREF(str_obj);
9206 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 }
Tim Petersced69f82003-09-16 20:30:58 +00009208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 kind1 = PyUnicode_KIND(str_obj);
9210 kind2 = PyUnicode_KIND(sub_obj);
9211 kind = kind1 > kind2 ? kind1 : kind2;
9212 buf1 = PyUnicode_DATA(str_obj);
9213 if (kind1 != kind)
9214 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
9215 if (!buf1)
9216 goto onError;
9217 buf2 = PyUnicode_DATA(sub_obj);
9218 if (kind2 != kind)
9219 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
9220 if (!buf2)
9221 goto onError;
9222 len1 = PyUnicode_GET_LENGTH(str_obj);
9223 len2 = PyUnicode_GET_LENGTH(sub_obj);
9224
9225 ADJUST_INDICES(start, end, len1);
9226 switch(kind) {
9227 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009228 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9229 result = asciilib_count(
9230 ((Py_UCS1*)buf1) + start, end - start,
9231 buf2, len2, PY_SSIZE_T_MAX
9232 );
9233 else
9234 result = ucs1lib_count(
9235 ((Py_UCS1*)buf1) + start, end - start,
9236 buf2, len2, PY_SSIZE_T_MAX
9237 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009238 break;
9239 case PyUnicode_2BYTE_KIND:
9240 result = ucs2lib_count(
9241 ((Py_UCS2*)buf1) + start, end - start,
9242 buf2, len2, PY_SSIZE_T_MAX
9243 );
9244 break;
9245 case PyUnicode_4BYTE_KIND:
9246 result = ucs4lib_count(
9247 ((Py_UCS4*)buf1) + start, end - start,
9248 buf2, len2, PY_SSIZE_T_MAX
9249 );
9250 break;
9251 default:
9252 assert(0); result = 0;
9253 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009254
9255 Py_DECREF(sub_obj);
9256 Py_DECREF(str_obj);
9257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 if (kind1 != kind)
9259 PyMem_Free(buf1);
9260 if (kind2 != kind)
9261 PyMem_Free(buf2);
9262
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009264 onError:
9265 Py_DECREF(sub_obj);
9266 Py_DECREF(str_obj);
9267 if (kind1 != kind && buf1)
9268 PyMem_Free(buf1);
9269 if (kind2 != kind && buf2)
9270 PyMem_Free(buf2);
9271 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272}
9273
Alexander Belopolsky40018472011-02-26 01:02:56 +00009274Py_ssize_t
9275PyUnicode_Find(PyObject *str,
9276 PyObject *sub,
9277 Py_ssize_t start,
9278 Py_ssize_t end,
9279 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009280{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009281 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009282
Guido van Rossumd57fd912000-03-10 22:53:23 +00009283 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009284 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009285 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009286 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009287 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009288 Py_DECREF(str);
9289 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 }
Tim Petersced69f82003-09-16 20:30:58 +00009291
Victor Stinner794d5672011-10-10 03:21:36 +02009292 result = any_find_slice(direction,
9293 str, sub, start, end
9294 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009295
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009297 Py_DECREF(sub);
9298
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299 return result;
9300}
9301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302Py_ssize_t
9303PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9304 Py_ssize_t start, Py_ssize_t end,
9305 int direction)
9306{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009307 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009308 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009309 if (PyUnicode_READY(str) == -1)
9310 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009311 if (start < 0 || end < 0) {
9312 PyErr_SetString(PyExc_IndexError, "string index out of range");
9313 return -2;
9314 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315 if (end > PyUnicode_GET_LENGTH(str))
9316 end = PyUnicode_GET_LENGTH(str);
9317 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009318 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9319 kind, end-start, ch, direction);
9320 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009322 else
9323 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324}
9325
Alexander Belopolsky40018472011-02-26 01:02:56 +00009326static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009327tailmatch(PyObject *self,
9328 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009329 Py_ssize_t start,
9330 Py_ssize_t end,
9331 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009332{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009333 int kind_self;
9334 int kind_sub;
9335 void *data_self;
9336 void *data_sub;
9337 Py_ssize_t offset;
9338 Py_ssize_t i;
9339 Py_ssize_t end_sub;
9340
9341 if (PyUnicode_READY(self) == -1 ||
9342 PyUnicode_READY(substring) == -1)
9343 return 0;
9344
9345 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346 return 1;
9347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9349 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009350 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009351 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 kind_self = PyUnicode_KIND(self);
9354 data_self = PyUnicode_DATA(self);
9355 kind_sub = PyUnicode_KIND(substring);
9356 data_sub = PyUnicode_DATA(substring);
9357 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9358
9359 if (direction > 0)
9360 offset = end;
9361 else
9362 offset = start;
9363
9364 if (PyUnicode_READ(kind_self, data_self, offset) ==
9365 PyUnicode_READ(kind_sub, data_sub, 0) &&
9366 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9367 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9368 /* If both are of the same kind, memcmp is sufficient */
9369 if (kind_self == kind_sub) {
9370 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009371 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009372 data_sub,
9373 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009374 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 }
9376 /* otherwise we have to compare each character by first accesing it */
9377 else {
9378 /* We do not need to compare 0 and len(substring)-1 because
9379 the if statement above ensured already that they are equal
9380 when we end up here. */
9381 // TODO: honor direction and do a forward or backwards search
9382 for (i = 1; i < end_sub; ++i) {
9383 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9384 PyUnicode_READ(kind_sub, data_sub, i))
9385 return 0;
9386 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009387 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009389 }
9390
9391 return 0;
9392}
9393
Alexander Belopolsky40018472011-02-26 01:02:56 +00009394Py_ssize_t
9395PyUnicode_Tailmatch(PyObject *str,
9396 PyObject *substr,
9397 Py_ssize_t start,
9398 Py_ssize_t end,
9399 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009401 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009402
Guido van Rossumd57fd912000-03-10 22:53:23 +00009403 str = PyUnicode_FromObject(str);
9404 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009405 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406 substr = PyUnicode_FromObject(substr);
9407 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009408 Py_DECREF(str);
9409 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410 }
Tim Petersced69f82003-09-16 20:30:58 +00009411
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009412 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009413 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009414 Py_DECREF(str);
9415 Py_DECREF(substr);
9416 return result;
9417}
9418
Guido van Rossumd57fd912000-03-10 22:53:23 +00009419/* Apply fixfct filter to the Unicode object self and return a
9420 reference to the modified object */
9421
Alexander Belopolsky40018472011-02-26 01:02:56 +00009422static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009423fixup(PyObject *self,
9424 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009425{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 PyObject *u;
9427 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 if (PyUnicode_READY(self) == -1)
9430 return NULL;
9431 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9432 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9433 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009434 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009435 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009438 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009439
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009440 /* fix functions return the new maximum character in a string,
9441 if the kind of the resulting unicode object does not change,
9442 everything is fine. Otherwise we need to change the string kind
9443 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009444 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009445 if (maxchar_new == 0)
9446 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9447 else if (maxchar_new <= 127)
9448 maxchar_new = 127;
9449 else if (maxchar_new <= 255)
9450 maxchar_new = 255;
9451 else if (maxchar_new <= 65535)
9452 maxchar_new = 65535;
9453 else
9454 maxchar_new = 1114111; /* 0x10ffff */
9455
9456 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009457 /* fixfct should return TRUE if it modified the buffer. If
9458 FALSE, return a reference to the original buffer instead
9459 (to save space, not time) */
9460 Py_INCREF(self);
9461 Py_DECREF(u);
9462 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009464 else if (maxchar_new == maxchar_old) {
9465 return u;
9466 }
9467 else {
9468 /* In case the maximum character changed, we need to
9469 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009470 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009471 if (v == NULL) {
9472 Py_DECREF(u);
9473 return NULL;
9474 }
9475 if (maxchar_new > maxchar_old) {
9476 /* If the maxchar increased so that the kind changed, not all
9477 characters are representable anymore and we need to fix the
9478 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009479 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009480 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9482 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009483 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009484 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009485 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486
9487 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009488 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009489 return v;
9490 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009491}
9492
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009494fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009495{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496 /* No need to call PyUnicode_READY(self) because this function is only
9497 called as a callback from fixup() which does it already. */
9498 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9499 const int kind = PyUnicode_KIND(self);
9500 void *data = PyUnicode_DATA(self);
9501 int touched = 0;
9502 Py_UCS4 maxchar = 0;
9503 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009504
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505 for (i = 0; i < len; ++i) {
9506 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9507 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9508 if (up != ch) {
9509 if (up > maxchar)
9510 maxchar = up;
9511 PyUnicode_WRITE(kind, data, i, up);
9512 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009513 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009514 else if (ch > maxchar)
9515 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009516 }
9517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 if (touched)
9519 return maxchar;
9520 else
9521 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522}
9523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009524static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009525fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009526{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009527 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9528 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9529 const int kind = PyUnicode_KIND(self);
9530 void *data = PyUnicode_DATA(self);
9531 int touched = 0;
9532 Py_UCS4 maxchar = 0;
9533 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009534
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535 for(i = 0; i < len; ++i) {
9536 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9537 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9538 if (lo != ch) {
9539 if (lo > maxchar)
9540 maxchar = lo;
9541 PyUnicode_WRITE(kind, data, i, lo);
9542 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 else if (ch > maxchar)
9545 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546 }
9547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548 if (touched)
9549 return maxchar;
9550 else
9551 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009552}
9553
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009555fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009556{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009557 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9558 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9559 const int kind = PyUnicode_KIND(self);
9560 void *data = PyUnicode_DATA(self);
9561 int touched = 0;
9562 Py_UCS4 maxchar = 0;
9563 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 for(i = 0; i < len; ++i) {
9566 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9567 Py_UCS4 nu = 0;
9568
9569 if (Py_UNICODE_ISUPPER(ch))
9570 nu = Py_UNICODE_TOLOWER(ch);
9571 else if (Py_UNICODE_ISLOWER(ch))
9572 nu = Py_UNICODE_TOUPPER(ch);
9573
9574 if (nu != 0) {
9575 if (nu > maxchar)
9576 maxchar = nu;
9577 PyUnicode_WRITE(kind, data, i, nu);
9578 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009579 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009580 else if (ch > maxchar)
9581 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582 }
9583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584 if (touched)
9585 return maxchar;
9586 else
9587 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009588}
9589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009590static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009591fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009592{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9594 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9595 const int kind = PyUnicode_KIND(self);
9596 void *data = PyUnicode_DATA(self);
9597 int touched = 0;
9598 Py_UCS4 maxchar = 0;
9599 Py_ssize_t i = 0;
9600 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009601
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009602 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009603 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009604
9605 ch = PyUnicode_READ(kind, data, i);
9606 if (!Py_UNICODE_ISUPPER(ch)) {
9607 maxchar = Py_UNICODE_TOUPPER(ch);
9608 PyUnicode_WRITE(kind, data, i, maxchar);
9609 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009610 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009611 ++i;
9612 for(; i < len; ++i) {
9613 ch = PyUnicode_READ(kind, data, i);
9614 if (!Py_UNICODE_ISLOWER(ch)) {
9615 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9616 if (lo > maxchar)
9617 maxchar = lo;
9618 PyUnicode_WRITE(kind, data, i, lo);
9619 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009620 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009621 else if (ch > maxchar)
9622 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009623 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009624
9625 if (touched)
9626 return maxchar;
9627 else
9628 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009629}
9630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009631static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009632fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009633{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9635 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9636 const int kind = PyUnicode_KIND(self);
9637 void *data = PyUnicode_DATA(self);
9638 Py_UCS4 maxchar = 0;
9639 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009640 int previous_is_cased;
9641
9642 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009643 if (len == 1) {
9644 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9645 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9646 if (ti != ch) {
9647 PyUnicode_WRITE(kind, data, i, ti);
9648 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009649 }
9650 else
9651 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009652 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009654 for(; i < len; ++i) {
9655 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9656 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009657
Benjamin Peterson29060642009-01-31 22:14:21 +00009658 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009659 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009660 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009661 nu = Py_UNICODE_TOTITLE(ch);
9662
9663 if (nu > maxchar)
9664 maxchar = nu;
9665 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009666
Benjamin Peterson29060642009-01-31 22:14:21 +00009667 if (Py_UNICODE_ISLOWER(ch) ||
9668 Py_UNICODE_ISUPPER(ch) ||
9669 Py_UNICODE_ISTITLE(ch))
9670 previous_is_cased = 1;
9671 else
9672 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009674 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009675}
9676
Tim Peters8ce9f162004-08-27 01:49:32 +00009677PyObject *
9678PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009680 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009681 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009682 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009683 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009684 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9685 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009686 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009687 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009688 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009689 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009690 int use_memcpy;
9691 unsigned char *res_data = NULL, *sep_data = NULL;
9692 PyObject *last_obj;
9693 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009694
Tim Peters05eba1f2004-08-27 21:32:02 +00009695 fseq = PySequence_Fast(seq, "");
9696 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009697 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009698 }
9699
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009700 /* NOTE: the following code can't call back into Python code,
9701 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009702 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009703
Tim Peters05eba1f2004-08-27 21:32:02 +00009704 seqlen = PySequence_Fast_GET_SIZE(fseq);
9705 /* If empty sequence, return u"". */
9706 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009707 Py_DECREF(fseq);
9708 Py_INCREF(unicode_empty);
9709 res = unicode_empty;
9710 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009711 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009712
Tim Peters05eba1f2004-08-27 21:32:02 +00009713 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009714 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009715 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009716 if (seqlen == 1) {
9717 if (PyUnicode_CheckExact(items[0])) {
9718 res = items[0];
9719 Py_INCREF(res);
9720 Py_DECREF(fseq);
9721 return res;
9722 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009723 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009724 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009725 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009726 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009727 /* Set up sep and seplen */
9728 if (separator == NULL) {
9729 /* fall back to a blank space separator */
9730 sep = PyUnicode_FromOrdinal(' ');
9731 if (!sep)
9732 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009733 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009734 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009735 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009736 else {
9737 if (!PyUnicode_Check(separator)) {
9738 PyErr_Format(PyExc_TypeError,
9739 "separator: expected str instance,"
9740 " %.80s found",
9741 Py_TYPE(separator)->tp_name);
9742 goto onError;
9743 }
9744 if (PyUnicode_READY(separator))
9745 goto onError;
9746 sep = separator;
9747 seplen = PyUnicode_GET_LENGTH(separator);
9748 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9749 /* inc refcount to keep this code path symmetric with the
9750 above case of a blank separator */
9751 Py_INCREF(sep);
9752 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009753 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009754 }
9755
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009756 /* There are at least two things to join, or else we have a subclass
9757 * of str in the sequence.
9758 * Do a pre-pass to figure out the total amount of space we'll
9759 * need (sz), and see whether all argument are strings.
9760 */
9761 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009762#ifdef Py_DEBUG
9763 use_memcpy = 0;
9764#else
9765 use_memcpy = 1;
9766#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009767 for (i = 0; i < seqlen; i++) {
9768 const Py_ssize_t old_sz = sz;
9769 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009770 if (!PyUnicode_Check(item)) {
9771 PyErr_Format(PyExc_TypeError,
9772 "sequence item %zd: expected str instance,"
9773 " %.80s found",
9774 i, Py_TYPE(item)->tp_name);
9775 goto onError;
9776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 if (PyUnicode_READY(item) == -1)
9778 goto onError;
9779 sz += PyUnicode_GET_LENGTH(item);
9780 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009781 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009782 if (i != 0)
9783 sz += seplen;
9784 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9785 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009786 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009787 goto onError;
9788 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009789 if (use_memcpy && last_obj != NULL) {
9790 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9791 use_memcpy = 0;
9792 }
9793 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009794 }
Tim Petersced69f82003-09-16 20:30:58 +00009795
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009796 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009797 if (res == NULL)
9798 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009799
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009800 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009801#ifdef Py_DEBUG
9802 use_memcpy = 0;
9803#else
9804 if (use_memcpy) {
9805 res_data = PyUnicode_1BYTE_DATA(res);
9806 kind = PyUnicode_KIND(res);
9807 if (seplen != 0)
9808 sep_data = PyUnicode_1BYTE_DATA(sep);
9809 }
9810#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009811 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009812 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009813 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009814 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009815 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009816 if (use_memcpy) {
9817 Py_MEMCPY(res_data,
9818 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009819 kind * seplen);
9820 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009821 }
9822 else {
9823 copy_characters(res, res_offset, sep, 0, seplen);
9824 res_offset += seplen;
9825 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009826 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009827 itemlen = PyUnicode_GET_LENGTH(item);
9828 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009829 if (use_memcpy) {
9830 Py_MEMCPY(res_data,
9831 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009832 kind * itemlen);
9833 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009834 }
9835 else {
9836 copy_characters(res, res_offset, item, 0, itemlen);
9837 res_offset += itemlen;
9838 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009839 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009840 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009841 if (use_memcpy)
9842 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009843 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009844 else
9845 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009846
Tim Peters05eba1f2004-08-27 21:32:02 +00009847 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009849 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851
Benjamin Peterson29060642009-01-31 22:14:21 +00009852 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009853 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009855 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009856 return NULL;
9857}
9858
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859#define FILL(kind, data, value, start, length) \
9860 do { \
9861 Py_ssize_t i_ = 0; \
9862 assert(kind != PyUnicode_WCHAR_KIND); \
9863 switch ((kind)) { \
9864 case PyUnicode_1BYTE_KIND: { \
9865 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9866 memset(to_, (unsigned char)value, length); \
9867 break; \
9868 } \
9869 case PyUnicode_2BYTE_KIND: { \
9870 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9871 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9872 break; \
9873 } \
9874 default: { \
9875 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9876 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9877 break; \
9878 } \
9879 } \
9880 } while (0)
9881
Victor Stinner9310abb2011-10-05 00:59:23 +02009882static PyObject *
9883pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009884 Py_ssize_t left,
9885 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009886 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009887{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009888 PyObject *u;
9889 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009890 int kind;
9891 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009892
9893 if (left < 0)
9894 left = 0;
9895 if (right < 0)
9896 right = 0;
9897
Tim Peters7a29bd52001-09-12 03:03:31 +00009898 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009899 Py_INCREF(self);
9900 return self;
9901 }
9902
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9904 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009905 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9906 return NULL;
9907 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009908 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9909 if (fill > maxchar)
9910 maxchar = fill;
9911 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009912 if (!u)
9913 return NULL;
9914
9915 kind = PyUnicode_KIND(u);
9916 data = PyUnicode_DATA(u);
9917 if (left)
9918 FILL(kind, data, fill, 0, left);
9919 if (right)
9920 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009921 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009922 assert(_PyUnicode_CheckConsistency(u, 1));
9923 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009926
Alexander Belopolsky40018472011-02-26 01:02:56 +00009927PyObject *
9928PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009929{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009930 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009931
9932 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009933 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009934 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009936 switch(PyUnicode_KIND(string)) {
9937 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009938 if (PyUnicode_IS_ASCII(string))
9939 list = asciilib_splitlines(
9940 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9941 PyUnicode_GET_LENGTH(string), keepends);
9942 else
9943 list = ucs1lib_splitlines(
9944 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9945 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 break;
9947 case PyUnicode_2BYTE_KIND:
9948 list = ucs2lib_splitlines(
9949 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9950 PyUnicode_GET_LENGTH(string), keepends);
9951 break;
9952 case PyUnicode_4BYTE_KIND:
9953 list = ucs4lib_splitlines(
9954 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9955 PyUnicode_GET_LENGTH(string), keepends);
9956 break;
9957 default:
9958 assert(0);
9959 list = 0;
9960 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009961 Py_DECREF(string);
9962 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009963}
9964
Alexander Belopolsky40018472011-02-26 01:02:56 +00009965static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009966split(PyObject *self,
9967 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009968 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009969{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009970 int kind1, kind2, kind;
9971 void *buf1, *buf2;
9972 Py_ssize_t len1, len2;
9973 PyObject* out;
9974
Guido van Rossumd57fd912000-03-10 22:53:23 +00009975 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009976 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009978 if (PyUnicode_READY(self) == -1)
9979 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 if (substring == NULL)
9982 switch(PyUnicode_KIND(self)) {
9983 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009984 if (PyUnicode_IS_ASCII(self))
9985 return asciilib_split_whitespace(
9986 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9987 PyUnicode_GET_LENGTH(self), maxcount
9988 );
9989 else
9990 return ucs1lib_split_whitespace(
9991 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9992 PyUnicode_GET_LENGTH(self), maxcount
9993 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009994 case PyUnicode_2BYTE_KIND:
9995 return ucs2lib_split_whitespace(
9996 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9997 PyUnicode_GET_LENGTH(self), maxcount
9998 );
9999 case PyUnicode_4BYTE_KIND:
10000 return ucs4lib_split_whitespace(
10001 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10002 PyUnicode_GET_LENGTH(self), maxcount
10003 );
10004 default:
10005 assert(0);
10006 return NULL;
10007 }
10008
10009 if (PyUnicode_READY(substring) == -1)
10010 return NULL;
10011
10012 kind1 = PyUnicode_KIND(self);
10013 kind2 = PyUnicode_KIND(substring);
10014 kind = kind1 > kind2 ? kind1 : kind2;
10015 buf1 = PyUnicode_DATA(self);
10016 buf2 = PyUnicode_DATA(substring);
10017 if (kind1 != kind)
10018 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10019 if (!buf1)
10020 return NULL;
10021 if (kind2 != kind)
10022 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10023 if (!buf2) {
10024 if (kind1 != kind) PyMem_Free(buf1);
10025 return NULL;
10026 }
10027 len1 = PyUnicode_GET_LENGTH(self);
10028 len2 = PyUnicode_GET_LENGTH(substring);
10029
10030 switch(kind) {
10031 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010032 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10033 out = asciilib_split(
10034 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10035 else
10036 out = ucs1lib_split(
10037 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 break;
10039 case PyUnicode_2BYTE_KIND:
10040 out = ucs2lib_split(
10041 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10042 break;
10043 case PyUnicode_4BYTE_KIND:
10044 out = ucs4lib_split(
10045 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10046 break;
10047 default:
10048 out = NULL;
10049 }
10050 if (kind1 != kind)
10051 PyMem_Free(buf1);
10052 if (kind2 != kind)
10053 PyMem_Free(buf2);
10054 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010055}
10056
Alexander Belopolsky40018472011-02-26 01:02:56 +000010057static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010058rsplit(PyObject *self,
10059 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010060 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010061{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010062 int kind1, kind2, kind;
10063 void *buf1, *buf2;
10064 Py_ssize_t len1, len2;
10065 PyObject* out;
10066
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010067 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010068 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010069
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 if (PyUnicode_READY(self) == -1)
10071 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010072
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 if (substring == NULL)
10074 switch(PyUnicode_KIND(self)) {
10075 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010076 if (PyUnicode_IS_ASCII(self))
10077 return asciilib_rsplit_whitespace(
10078 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10079 PyUnicode_GET_LENGTH(self), maxcount
10080 );
10081 else
10082 return ucs1lib_rsplit_whitespace(
10083 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10084 PyUnicode_GET_LENGTH(self), maxcount
10085 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010086 case PyUnicode_2BYTE_KIND:
10087 return ucs2lib_rsplit_whitespace(
10088 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10089 PyUnicode_GET_LENGTH(self), maxcount
10090 );
10091 case PyUnicode_4BYTE_KIND:
10092 return ucs4lib_rsplit_whitespace(
10093 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10094 PyUnicode_GET_LENGTH(self), maxcount
10095 );
10096 default:
10097 assert(0);
10098 return NULL;
10099 }
10100
10101 if (PyUnicode_READY(substring) == -1)
10102 return NULL;
10103
10104 kind1 = PyUnicode_KIND(self);
10105 kind2 = PyUnicode_KIND(substring);
10106 kind = kind1 > kind2 ? kind1 : kind2;
10107 buf1 = PyUnicode_DATA(self);
10108 buf2 = PyUnicode_DATA(substring);
10109 if (kind1 != kind)
10110 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10111 if (!buf1)
10112 return NULL;
10113 if (kind2 != kind)
10114 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10115 if (!buf2) {
10116 if (kind1 != kind) PyMem_Free(buf1);
10117 return NULL;
10118 }
10119 len1 = PyUnicode_GET_LENGTH(self);
10120 len2 = PyUnicode_GET_LENGTH(substring);
10121
10122 switch(kind) {
10123 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10125 out = asciilib_rsplit(
10126 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10127 else
10128 out = ucs1lib_rsplit(
10129 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 break;
10131 case PyUnicode_2BYTE_KIND:
10132 out = ucs2lib_rsplit(
10133 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10134 break;
10135 case PyUnicode_4BYTE_KIND:
10136 out = ucs4lib_rsplit(
10137 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10138 break;
10139 default:
10140 out = NULL;
10141 }
10142 if (kind1 != kind)
10143 PyMem_Free(buf1);
10144 if (kind2 != kind)
10145 PyMem_Free(buf2);
10146 return out;
10147}
10148
10149static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10151 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152{
10153 switch(kind) {
10154 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010155 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10156 return asciilib_find(buf1, len1, buf2, len2, offset);
10157 else
10158 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 case PyUnicode_2BYTE_KIND:
10160 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10161 case PyUnicode_4BYTE_KIND:
10162 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10163 }
10164 assert(0);
10165 return -1;
10166}
10167
10168static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010169anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10170 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171{
10172 switch(kind) {
10173 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010174 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10175 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10176 else
10177 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 case PyUnicode_2BYTE_KIND:
10179 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10180 case PyUnicode_4BYTE_KIND:
10181 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10182 }
10183 assert(0);
10184 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010185}
10186
Alexander Belopolsky40018472011-02-26 01:02:56 +000010187static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188replace(PyObject *self, PyObject *str1,
10189 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010190{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010191 PyObject *u;
10192 char *sbuf = PyUnicode_DATA(self);
10193 char *buf1 = PyUnicode_DATA(str1);
10194 char *buf2 = PyUnicode_DATA(str2);
10195 int srelease = 0, release1 = 0, release2 = 0;
10196 int skind = PyUnicode_KIND(self);
10197 int kind1 = PyUnicode_KIND(str1);
10198 int kind2 = PyUnicode_KIND(str2);
10199 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10200 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10201 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010202 int mayshrink;
10203 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010204
10205 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010206 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010207 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010208 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010209
Victor Stinner59de0ee2011-10-07 10:01:28 +020010210 if (str1 == str2)
10211 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 if (skind < kind1)
10213 /* substring too wide to be present */
10214 goto nothing;
10215
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10217 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10218 /* Replacing str1 with str2 may cause a maxchar reduction in the
10219 result string. */
10220 mayshrink = (maxchar_str2 < maxchar);
10221 maxchar = Py_MAX(maxchar, maxchar_str2);
10222
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010224 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010225 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010227 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010228 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010230 Py_UCS4 u1, u2;
10231 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010233 if (findchar(sbuf, PyUnicode_KIND(self),
10234 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010235 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010236 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010238 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010240 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 rkind = PyUnicode_KIND(u);
10242 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10243 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010244 if (--maxcount < 0)
10245 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010246 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010247 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010248 }
10249 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 int rkind = skind;
10251 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010252
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 if (kind1 < rkind) {
10254 /* widen substring */
10255 buf1 = _PyUnicode_AsKind(str1, rkind);
10256 if (!buf1) goto error;
10257 release1 = 1;
10258 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010259 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010260 if (i < 0)
10261 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 if (rkind > kind2) {
10263 /* widen replacement */
10264 buf2 = _PyUnicode_AsKind(str2, rkind);
10265 if (!buf2) goto error;
10266 release2 = 1;
10267 }
10268 else if (rkind < kind2) {
10269 /* widen self and buf1 */
10270 rkind = kind2;
10271 if (release1) PyMem_Free(buf1);
10272 sbuf = _PyUnicode_AsKind(self, rkind);
10273 if (!sbuf) goto error;
10274 srelease = 1;
10275 buf1 = _PyUnicode_AsKind(str1, rkind);
10276 if (!buf1) goto error;
10277 release1 = 1;
10278 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010279 u = PyUnicode_New(slen, maxchar);
10280 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010281 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010282 assert(PyUnicode_KIND(u) == rkind);
10283 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010284
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010285 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010286 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010287 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010289 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010290 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010291
10292 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010293 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010294 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010295 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010296 if (i == -1)
10297 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010298 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010300 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010301 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010302 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010303 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010304 }
10305 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010306 Py_ssize_t n, i, j, ires;
10307 Py_ssize_t product, new_size;
10308 int rkind = skind;
10309 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010311 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010312 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 buf1 = _PyUnicode_AsKind(str1, rkind);
10314 if (!buf1) goto error;
10315 release1 = 1;
10316 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010317 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010318 if (n == 0)
10319 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010321 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 buf2 = _PyUnicode_AsKind(str2, rkind);
10323 if (!buf2) goto error;
10324 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010326 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010327 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010328 rkind = kind2;
10329 sbuf = _PyUnicode_AsKind(self, rkind);
10330 if (!sbuf) goto error;
10331 srelease = 1;
10332 if (release1) PyMem_Free(buf1);
10333 buf1 = _PyUnicode_AsKind(str1, rkind);
10334 if (!buf1) goto error;
10335 release1 = 1;
10336 }
10337 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10338 PyUnicode_GET_LENGTH(str1))); */
10339 product = n * (len2-len1);
10340 if ((product / (len2-len1)) != n) {
10341 PyErr_SetString(PyExc_OverflowError,
10342 "replace string is too long");
10343 goto error;
10344 }
10345 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010346 if (new_size == 0) {
10347 Py_INCREF(unicode_empty);
10348 u = unicode_empty;
10349 goto done;
10350 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010351 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10352 PyErr_SetString(PyExc_OverflowError,
10353 "replace string is too long");
10354 goto error;
10355 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010356 u = PyUnicode_New(new_size, maxchar);
10357 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010358 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010359 assert(PyUnicode_KIND(u) == rkind);
10360 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 ires = i = 0;
10362 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010363 while (n-- > 0) {
10364 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010365 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010366 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010367 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010368 if (j == -1)
10369 break;
10370 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010371 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010372 memcpy(res + rkind * ires,
10373 sbuf + rkind * i,
10374 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010375 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010376 }
10377 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010379 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010381 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010382 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010383 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010384 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010387 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010388 memcpy(res + rkind * ires,
10389 sbuf + rkind * i,
10390 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010391 }
10392 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010393 /* interleave */
10394 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010395 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010397 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010399 if (--n <= 0)
10400 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010401 memcpy(res + rkind * ires,
10402 sbuf + rkind * i,
10403 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010404 ires++;
10405 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010406 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010407 memcpy(res + rkind * ires,
10408 sbuf + rkind * i,
10409 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010410 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010411 }
10412
10413 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010414 unicode_adjust_maxchar(&u);
10415 if (u == NULL)
10416 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010417 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010418
10419 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010420 if (srelease)
10421 PyMem_FREE(sbuf);
10422 if (release1)
10423 PyMem_FREE(buf1);
10424 if (release2)
10425 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010426 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010428
Benjamin Peterson29060642009-01-31 22:14:21 +000010429 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010430 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010431 if (srelease)
10432 PyMem_FREE(sbuf);
10433 if (release1)
10434 PyMem_FREE(buf1);
10435 if (release2)
10436 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010437 if (PyUnicode_CheckExact(self)) {
10438 Py_INCREF(self);
10439 return (PyObject *) self;
10440 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010441 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 error:
10443 if (srelease && sbuf)
10444 PyMem_FREE(sbuf);
10445 if (release1 && buf1)
10446 PyMem_FREE(buf1);
10447 if (release2 && buf2)
10448 PyMem_FREE(buf2);
10449 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010450}
10451
10452/* --- Unicode Object Methods --------------------------------------------- */
10453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010454PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010455 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010456\n\
10457Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010458characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010459
10460static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010461unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010463 return fixup(self, fixtitle);
10464}
10465
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010466PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010467 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468\n\
10469Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010470have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010471
10472static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010473unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010474{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475 return fixup(self, fixcapitalize);
10476}
10477
10478#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010479PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010480 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481\n\
10482Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010483normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484
10485static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010486unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010487{
10488 PyObject *list;
10489 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010490 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010491
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492 /* Split into words */
10493 list = split(self, NULL, -1);
10494 if (!list)
10495 return NULL;
10496
10497 /* Capitalize each word */
10498 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010499 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010500 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010501 if (item == NULL)
10502 goto onError;
10503 Py_DECREF(PyList_GET_ITEM(list, i));
10504 PyList_SET_ITEM(list, i, item);
10505 }
10506
10507 /* Join the words to form a new string */
10508 item = PyUnicode_Join(NULL, list);
10509
Benjamin Peterson29060642009-01-31 22:14:21 +000010510 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010511 Py_DECREF(list);
10512 return (PyObject *)item;
10513}
10514#endif
10515
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010516/* Argument converter. Coerces to a single unicode character */
10517
10518static int
10519convert_uc(PyObject *obj, void *addr)
10520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010521 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010522 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010523
Benjamin Peterson14339b62009-01-31 16:36:08 +000010524 uniobj = PyUnicode_FromObject(obj);
10525 if (uniobj == NULL) {
10526 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010527 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010528 return 0;
10529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010531 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010532 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010533 Py_DECREF(uniobj);
10534 return 0;
10535 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010537 Py_DECREF(uniobj);
10538 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010539}
10540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010541PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010542 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010544Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010545done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010546
10547static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010548unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010549{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010550 Py_ssize_t marg, left;
10551 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010552 Py_UCS4 fillchar = ' ';
10553
Victor Stinnere9a29352011-10-01 02:14:59 +020010554 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010555 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010556
Victor Stinnere9a29352011-10-01 02:14:59 +020010557 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010558 return NULL;
10559
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010560 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010561 Py_INCREF(self);
10562 return (PyObject*) self;
10563 }
10564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010566 left = marg / 2 + (marg & width & 1);
10567
Victor Stinner9310abb2011-10-05 00:59:23 +020010568 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010569}
10570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010571/* This function assumes that str1 and str2 are readied by the caller. */
10572
Marc-André Lemburge5034372000-08-08 08:04:29 +000010573static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010574unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010575{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 int kind1, kind2;
10577 void *data1, *data2;
10578 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010579
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010580 kind1 = PyUnicode_KIND(str1);
10581 kind2 = PyUnicode_KIND(str2);
10582 data1 = PyUnicode_DATA(str1);
10583 data2 = PyUnicode_DATA(str2);
10584 len1 = PyUnicode_GET_LENGTH(str1);
10585 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010586
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010587 for (i = 0; i < len1 && i < len2; ++i) {
10588 Py_UCS4 c1, c2;
10589 c1 = PyUnicode_READ(kind1, data1, i);
10590 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010591
10592 if (c1 != c2)
10593 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010594 }
10595
10596 return (len1 < len2) ? -1 : (len1 != len2);
10597}
10598
Alexander Belopolsky40018472011-02-26 01:02:56 +000010599int
10600PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010601{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010602 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10603 if (PyUnicode_READY(left) == -1 ||
10604 PyUnicode_READY(right) == -1)
10605 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010606 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010608 PyErr_Format(PyExc_TypeError,
10609 "Can't compare %.100s and %.100s",
10610 left->ob_type->tp_name,
10611 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010612 return -1;
10613}
10614
Martin v. Löwis5b222132007-06-10 09:51:05 +000010615int
10616PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10617{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 Py_ssize_t i;
10619 int kind;
10620 void *data;
10621 Py_UCS4 chr;
10622
Victor Stinner910337b2011-10-03 03:20:16 +020010623 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 if (PyUnicode_READY(uni) == -1)
10625 return -1;
10626 kind = PyUnicode_KIND(uni);
10627 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010628 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10630 if (chr != str[i])
10631 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010632 /* This check keeps Python strings that end in '\0' from comparing equal
10633 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010634 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010635 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010636 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010637 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010638 return 0;
10639}
10640
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010641
Benjamin Peterson29060642009-01-31 22:14:21 +000010642#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010643 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010644
Alexander Belopolsky40018472011-02-26 01:02:56 +000010645PyObject *
10646PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010647{
10648 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010649
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010650 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10651 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 if (PyUnicode_READY(left) == -1 ||
10653 PyUnicode_READY(right) == -1)
10654 return NULL;
10655 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10656 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010657 if (op == Py_EQ) {
10658 Py_INCREF(Py_False);
10659 return Py_False;
10660 }
10661 if (op == Py_NE) {
10662 Py_INCREF(Py_True);
10663 return Py_True;
10664 }
10665 }
10666 if (left == right)
10667 result = 0;
10668 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010669 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010670
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010671 /* Convert the return value to a Boolean */
10672 switch (op) {
10673 case Py_EQ:
10674 v = TEST_COND(result == 0);
10675 break;
10676 case Py_NE:
10677 v = TEST_COND(result != 0);
10678 break;
10679 case Py_LE:
10680 v = TEST_COND(result <= 0);
10681 break;
10682 case Py_GE:
10683 v = TEST_COND(result >= 0);
10684 break;
10685 case Py_LT:
10686 v = TEST_COND(result == -1);
10687 break;
10688 case Py_GT:
10689 v = TEST_COND(result == 1);
10690 break;
10691 default:
10692 PyErr_BadArgument();
10693 return NULL;
10694 }
10695 Py_INCREF(v);
10696 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010697 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010698
Brian Curtindfc80e32011-08-10 20:28:54 -050010699 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010700}
10701
Alexander Belopolsky40018472011-02-26 01:02:56 +000010702int
10703PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010704{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010705 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010706 int kind1, kind2, kind;
10707 void *buf1, *buf2;
10708 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010709 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010710
10711 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010712 sub = PyUnicode_FromObject(element);
10713 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010714 PyErr_Format(PyExc_TypeError,
10715 "'in <string>' requires string as left operand, not %s",
10716 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010717 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010718 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 if (PyUnicode_READY(sub) == -1)
10720 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010721
Thomas Wouters477c8d52006-05-27 19:21:47 +000010722 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010723 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010724 Py_DECREF(sub);
10725 return -1;
10726 }
10727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010728 kind1 = PyUnicode_KIND(str);
10729 kind2 = PyUnicode_KIND(sub);
10730 kind = kind1 > kind2 ? kind1 : kind2;
10731 buf1 = PyUnicode_DATA(str);
10732 buf2 = PyUnicode_DATA(sub);
10733 if (kind1 != kind)
10734 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10735 if (!buf1) {
10736 Py_DECREF(sub);
10737 return -1;
10738 }
10739 if (kind2 != kind)
10740 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10741 if (!buf2) {
10742 Py_DECREF(sub);
10743 if (kind1 != kind) PyMem_Free(buf1);
10744 return -1;
10745 }
10746 len1 = PyUnicode_GET_LENGTH(str);
10747 len2 = PyUnicode_GET_LENGTH(sub);
10748
10749 switch(kind) {
10750 case PyUnicode_1BYTE_KIND:
10751 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10752 break;
10753 case PyUnicode_2BYTE_KIND:
10754 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10755 break;
10756 case PyUnicode_4BYTE_KIND:
10757 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10758 break;
10759 default:
10760 result = -1;
10761 assert(0);
10762 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010763
10764 Py_DECREF(str);
10765 Py_DECREF(sub);
10766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010767 if (kind1 != kind)
10768 PyMem_Free(buf1);
10769 if (kind2 != kind)
10770 PyMem_Free(buf2);
10771
Guido van Rossum403d68b2000-03-13 15:55:09 +000010772 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010773}
10774
Guido van Rossumd57fd912000-03-10 22:53:23 +000010775/* Concat to string or Unicode object giving a new Unicode object. */
10776
Alexander Belopolsky40018472011-02-26 01:02:56 +000010777PyObject *
10778PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010780 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010781 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782
10783 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010784 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010785 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010786 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010787 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010788 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010789 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010790
10791 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010792 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010793 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010795 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010796 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010797 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799 }
10800
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010801 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010802 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10803 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010804
Guido van Rossumd57fd912000-03-10 22:53:23 +000010805 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010806 w = PyUnicode_New(
10807 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10808 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010809 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010810 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010811 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10812 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813 Py_DECREF(u);
10814 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010815 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010816 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010817
Benjamin Peterson29060642009-01-31 22:14:21 +000010818 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010819 Py_XDECREF(u);
10820 Py_XDECREF(v);
10821 return NULL;
10822}
10823
Victor Stinnerb0923652011-10-04 01:17:31 +020010824static void
10825unicode_append_inplace(PyObject **p_left, PyObject *right)
10826{
10827 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010828
10829 assert(PyUnicode_IS_READY(*p_left));
10830 assert(PyUnicode_IS_READY(right));
10831
10832 left_len = PyUnicode_GET_LENGTH(*p_left);
10833 right_len = PyUnicode_GET_LENGTH(right);
10834 if (left_len > PY_SSIZE_T_MAX - right_len) {
10835 PyErr_SetString(PyExc_OverflowError,
10836 "strings are too large to concat");
10837 goto error;
10838 }
10839 new_len = left_len + right_len;
10840
10841 /* Now we own the last reference to 'left', so we can resize it
10842 * in-place.
10843 */
10844 if (unicode_resize(p_left, new_len) != 0) {
10845 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10846 * deallocated so it cannot be put back into
10847 * 'variable'. The MemoryError is raised when there
10848 * is no value in 'variable', which might (very
10849 * remotely) be a cause of incompatibilities.
10850 */
10851 goto error;
10852 }
10853 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010854 copy_characters(*p_left, left_len, right, 0, right_len);
10855 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010856 return;
10857
10858error:
10859 Py_DECREF(*p_left);
10860 *p_left = NULL;
10861}
10862
Walter Dörwald1ab83302007-05-18 17:15:44 +000010863void
Victor Stinner23e56682011-10-03 03:54:37 +020010864PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010865{
Victor Stinner23e56682011-10-03 03:54:37 +020010866 PyObject *left, *res;
10867
10868 if (p_left == NULL) {
10869 if (!PyErr_Occurred())
10870 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010871 return;
10872 }
Victor Stinner23e56682011-10-03 03:54:37 +020010873 left = *p_left;
10874 if (right == NULL || !PyUnicode_Check(left)) {
10875 if (!PyErr_Occurred())
10876 PyErr_BadInternalCall();
10877 goto error;
10878 }
10879
Victor Stinnere1335c72011-10-04 20:53:03 +020010880 if (PyUnicode_READY(left))
10881 goto error;
10882 if (PyUnicode_READY(right))
10883 goto error;
10884
Victor Stinner23e56682011-10-03 03:54:37 +020010885 if (PyUnicode_CheckExact(left) && left != unicode_empty
10886 && PyUnicode_CheckExact(right) && right != unicode_empty
10887 && unicode_resizable(left)
10888 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10889 || _PyUnicode_WSTR(left) != NULL))
10890 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010891 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10892 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010893 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010894 not so different than duplicating the string. */
10895 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010896 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010897 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010898 if (p_left != NULL)
10899 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010900 return;
10901 }
10902 }
10903
10904 res = PyUnicode_Concat(left, right);
10905 if (res == NULL)
10906 goto error;
10907 Py_DECREF(left);
10908 *p_left = res;
10909 return;
10910
10911error:
10912 Py_DECREF(*p_left);
10913 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010914}
10915
10916void
10917PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10918{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010919 PyUnicode_Append(pleft, right);
10920 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010921}
10922
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010923PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010924 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010925\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010926Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010927string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010928interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929
10930static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010931unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010932{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010933 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010934 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010935 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010936 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010937 int kind1, kind2, kind;
10938 void *buf1, *buf2;
10939 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940
Jesus Ceaac451502011-04-20 17:09:23 +020010941 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10942 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010943 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010945 kind1 = PyUnicode_KIND(self);
10946 kind2 = PyUnicode_KIND(substring);
10947 kind = kind1 > kind2 ? kind1 : kind2;
10948 buf1 = PyUnicode_DATA(self);
10949 buf2 = PyUnicode_DATA(substring);
10950 if (kind1 != kind)
10951 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10952 if (!buf1) {
10953 Py_DECREF(substring);
10954 return NULL;
10955 }
10956 if (kind2 != kind)
10957 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10958 if (!buf2) {
10959 Py_DECREF(substring);
10960 if (kind1 != kind) PyMem_Free(buf1);
10961 return NULL;
10962 }
10963 len1 = PyUnicode_GET_LENGTH(self);
10964 len2 = PyUnicode_GET_LENGTH(substring);
10965
10966 ADJUST_INDICES(start, end, len1);
10967 switch(kind) {
10968 case PyUnicode_1BYTE_KIND:
10969 iresult = ucs1lib_count(
10970 ((Py_UCS1*)buf1) + start, end - start,
10971 buf2, len2, PY_SSIZE_T_MAX
10972 );
10973 break;
10974 case PyUnicode_2BYTE_KIND:
10975 iresult = ucs2lib_count(
10976 ((Py_UCS2*)buf1) + start, end - start,
10977 buf2, len2, PY_SSIZE_T_MAX
10978 );
10979 break;
10980 case PyUnicode_4BYTE_KIND:
10981 iresult = ucs4lib_count(
10982 ((Py_UCS4*)buf1) + start, end - start,
10983 buf2, len2, PY_SSIZE_T_MAX
10984 );
10985 break;
10986 default:
10987 assert(0); iresult = 0;
10988 }
10989
10990 result = PyLong_FromSsize_t(iresult);
10991
10992 if (kind1 != kind)
10993 PyMem_Free(buf1);
10994 if (kind2 != kind)
10995 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996
10997 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010998
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999 return result;
11000}
11001
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011002PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011003 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011004\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011005Encode S using the codec registered for encoding. Default encoding\n\
11006is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011007handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011008a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11009'xmlcharrefreplace' as well as any other name registered with\n\
11010codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011
11012static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011013unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011015 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016 char *encoding = NULL;
11017 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011018
Benjamin Peterson308d6372009-09-18 21:42:35 +000011019 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11020 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011022 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011023}
11024
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011025PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011026 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027\n\
11028Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011029If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011030
11031static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011032unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011034 Py_ssize_t i, j, line_pos, src_len, incr;
11035 Py_UCS4 ch;
11036 PyObject *u;
11037 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011039 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011040 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041
11042 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011043 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
Antoine Pitrou22425222011-10-04 19:10:51 +020011045 if (PyUnicode_READY(self) == -1)
11046 return NULL;
11047
Thomas Wouters7e474022000-07-16 12:04:32 +000011048 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011049 src_len = PyUnicode_GET_LENGTH(self);
11050 i = j = line_pos = 0;
11051 kind = PyUnicode_KIND(self);
11052 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011053 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011054 for (; i < src_len; i++) {
11055 ch = PyUnicode_READ(kind, src_data, i);
11056 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011057 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011058 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011059 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011060 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011061 goto overflow;
11062 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011063 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011064 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011065 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011066 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011067 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011068 goto overflow;
11069 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011070 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011071 if (ch == '\n' || ch == '\r')
11072 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011074 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011075 if (!found && PyUnicode_CheckExact(self)) {
11076 Py_INCREF((PyObject *) self);
11077 return (PyObject *) self;
11078 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011079
Guido van Rossumd57fd912000-03-10 22:53:23 +000011080 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011081 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011082 if (!u)
11083 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011084 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011085
Antoine Pitroue71d5742011-10-04 15:55:09 +020011086 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087
Antoine Pitroue71d5742011-10-04 15:55:09 +020011088 for (; i < src_len; i++) {
11089 ch = PyUnicode_READ(kind, src_data, i);
11090 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011091 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011092 incr = tabsize - (line_pos % tabsize);
11093 line_pos += incr;
11094 while (incr--) {
11095 PyUnicode_WRITE(kind, dest_data, j, ' ');
11096 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011097 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011098 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011099 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011100 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011101 line_pos++;
11102 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011103 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011104 if (ch == '\n' || ch == '\r')
11105 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011107 }
11108 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011109#ifndef DONT_MAKE_RESULT_READY
11110 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 Py_DECREF(u);
11112 return NULL;
11113 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011114#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011115 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011117
Antoine Pitroue71d5742011-10-04 15:55:09 +020011118 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011119 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11120 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011121}
11122
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011123PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011124 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125\n\
11126Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011127such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128arguments start and end are interpreted as in slice notation.\n\
11129\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131
11132static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011133unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011135 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011136 Py_ssize_t start;
11137 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011138 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139
Jesus Ceaac451502011-04-20 17:09:23 +020011140 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11141 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011142 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011144 if (PyUnicode_READY(self) == -1)
11145 return NULL;
11146 if (PyUnicode_READY(substring) == -1)
11147 return NULL;
11148
Victor Stinner794d5672011-10-10 03:21:36 +020011149 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011151 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011152
11153 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011154
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 if (result == -2)
11156 return NULL;
11157
Christian Heimes217cfd12007-12-02 14:31:20 +000011158 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011159}
11160
11161static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011162unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011164 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11165 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011168}
11169
Guido van Rossumc2504932007-09-18 19:42:40 +000011170/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011171 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011172static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011173unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174{
Guido van Rossumc2504932007-09-18 19:42:40 +000011175 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011176 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011177
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 if (_PyUnicode_HASH(self) != -1)
11179 return _PyUnicode_HASH(self);
11180 if (PyUnicode_READY(self) == -1)
11181 return -1;
11182 len = PyUnicode_GET_LENGTH(self);
11183
11184 /* The hash function as a macro, gets expanded three times below. */
11185#define HASH(P) \
11186 x = (Py_uhash_t)*P << 7; \
11187 while (--len >= 0) \
11188 x = (1000003*x) ^ (Py_uhash_t)*P++;
11189
11190 switch (PyUnicode_KIND(self)) {
11191 case PyUnicode_1BYTE_KIND: {
11192 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11193 HASH(c);
11194 break;
11195 }
11196 case PyUnicode_2BYTE_KIND: {
11197 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11198 HASH(s);
11199 break;
11200 }
11201 default: {
11202 Py_UCS4 *l;
11203 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11204 "Impossible switch case in unicode_hash");
11205 l = PyUnicode_4BYTE_DATA(self);
11206 HASH(l);
11207 break;
11208 }
11209 }
11210 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11211
Guido van Rossumc2504932007-09-18 19:42:40 +000011212 if (x == -1)
11213 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011214 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011215 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011219PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011220 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011222Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223
11224static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011225unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011227 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011228 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011229 Py_ssize_t start;
11230 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231
Jesus Ceaac451502011-04-20 17:09:23 +020011232 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11233 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011236 if (PyUnicode_READY(self) == -1)
11237 return NULL;
11238 if (PyUnicode_READY(substring) == -1)
11239 return NULL;
11240
Victor Stinner794d5672011-10-10 03:21:36 +020011241 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011243 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011244
11245 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011247 if (result == -2)
11248 return NULL;
11249
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250 if (result < 0) {
11251 PyErr_SetString(PyExc_ValueError, "substring not found");
11252 return NULL;
11253 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011254
Christian Heimes217cfd12007-12-02 14:31:20 +000011255 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256}
11257
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011258PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011259 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011261Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011262at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263
11264static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011265unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011267 Py_ssize_t i, length;
11268 int kind;
11269 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 int cased;
11271
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011272 if (PyUnicode_READY(self) == -1)
11273 return NULL;
11274 length = PyUnicode_GET_LENGTH(self);
11275 kind = PyUnicode_KIND(self);
11276 data = PyUnicode_DATA(self);
11277
Guido van Rossumd57fd912000-03-10 22:53:23 +000011278 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 if (length == 1)
11280 return PyBool_FromLong(
11281 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011283 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011286
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288 for (i = 0; i < length; i++) {
11289 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011290
Benjamin Peterson29060642009-01-31 22:14:21 +000011291 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11292 return PyBool_FromLong(0);
11293 else if (!cased && Py_UNICODE_ISLOWER(ch))
11294 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011295 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011296 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297}
11298
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011299PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011302Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011303at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011304
11305static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011306unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011308 Py_ssize_t i, length;
11309 int kind;
11310 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311 int cased;
11312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 if (PyUnicode_READY(self) == -1)
11314 return NULL;
11315 length = PyUnicode_GET_LENGTH(self);
11316 kind = PyUnicode_KIND(self);
11317 data = PyUnicode_DATA(self);
11318
Guido van Rossumd57fd912000-03-10 22:53:23 +000011319 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (length == 1)
11321 return PyBool_FromLong(
11322 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011323
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011324 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011327
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 for (i = 0; i < length; i++) {
11330 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011331
Benjamin Peterson29060642009-01-31 22:14:21 +000011332 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11333 return PyBool_FromLong(0);
11334 else if (!cased && Py_UNICODE_ISUPPER(ch))
11335 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011336 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011337 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011338}
11339
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011340PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011341 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011342\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011343Return True if S is a titlecased string and there is at least one\n\
11344character in S, i.e. upper- and titlecase characters may only\n\
11345follow uncased characters and lowercase characters only cased ones.\n\
11346Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011347
11348static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011349unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011351 Py_ssize_t i, length;
11352 int kind;
11353 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011354 int cased, previous_is_cased;
11355
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 if (PyUnicode_READY(self) == -1)
11357 return NULL;
11358 length = PyUnicode_GET_LENGTH(self);
11359 kind = PyUnicode_KIND(self);
11360 data = PyUnicode_DATA(self);
11361
Guido van Rossumd57fd912000-03-10 22:53:23 +000011362 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011363 if (length == 1) {
11364 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11365 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11366 (Py_UNICODE_ISUPPER(ch) != 0));
11367 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011368
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011369 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011371 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011372
Guido van Rossumd57fd912000-03-10 22:53:23 +000011373 cased = 0;
11374 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 for (i = 0; i < length; i++) {
11376 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011377
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11379 if (previous_is_cased)
11380 return PyBool_FromLong(0);
11381 previous_is_cased = 1;
11382 cased = 1;
11383 }
11384 else if (Py_UNICODE_ISLOWER(ch)) {
11385 if (!previous_is_cased)
11386 return PyBool_FromLong(0);
11387 previous_is_cased = 1;
11388 cased = 1;
11389 }
11390 else
11391 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011393 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394}
11395
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011396PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011397 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011399Return True if all characters in S are whitespace\n\
11400and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401
11402static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011403unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011405 Py_ssize_t i, length;
11406 int kind;
11407 void *data;
11408
11409 if (PyUnicode_READY(self) == -1)
11410 return NULL;
11411 length = PyUnicode_GET_LENGTH(self);
11412 kind = PyUnicode_KIND(self);
11413 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011416 if (length == 1)
11417 return PyBool_FromLong(
11418 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011419
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011420 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011421 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011422 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011423
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011424 for (i = 0; i < length; i++) {
11425 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011426 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011427 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011428 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011429 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011430}
11431
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011432PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011433 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011434\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011435Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011436and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011437
11438static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011439unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011440{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 Py_ssize_t i, length;
11442 int kind;
11443 void *data;
11444
11445 if (PyUnicode_READY(self) == -1)
11446 return NULL;
11447 length = PyUnicode_GET_LENGTH(self);
11448 kind = PyUnicode_KIND(self);
11449 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011450
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011451 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011452 if (length == 1)
11453 return PyBool_FromLong(
11454 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011455
11456 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011459
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011460 for (i = 0; i < length; i++) {
11461 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011462 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011463 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011464 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011465}
11466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011467PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011468 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011469\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011470Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011471and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011472
11473static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011474unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011475{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011476 int kind;
11477 void *data;
11478 Py_ssize_t len, i;
11479
11480 if (PyUnicode_READY(self) == -1)
11481 return NULL;
11482
11483 kind = PyUnicode_KIND(self);
11484 data = PyUnicode_DATA(self);
11485 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011486
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011487 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011488 if (len == 1) {
11489 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11490 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11491 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011492
11493 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011494 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011495 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011497 for (i = 0; i < len; i++) {
11498 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011499 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011500 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011501 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011502 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011503}
11504
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011505PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011506 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011508Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011509False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011510
11511static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011512unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 Py_ssize_t i, length;
11515 int kind;
11516 void *data;
11517
11518 if (PyUnicode_READY(self) == -1)
11519 return NULL;
11520 length = PyUnicode_GET_LENGTH(self);
11521 kind = PyUnicode_KIND(self);
11522 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011523
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011525 if (length == 1)
11526 return PyBool_FromLong(
11527 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011529 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011530 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011532
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 for (i = 0; i < length; i++) {
11534 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011535 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011536 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011537 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538}
11539
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011540PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011541 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011542\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011543Return True if all characters in S are digits\n\
11544and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011545
11546static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011547unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 Py_ssize_t i, length;
11550 int kind;
11551 void *data;
11552
11553 if (PyUnicode_READY(self) == -1)
11554 return NULL;
11555 length = PyUnicode_GET_LENGTH(self);
11556 kind = PyUnicode_KIND(self);
11557 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 if (length == 1) {
11561 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11562 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011565 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011566 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011567 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011569 for (i = 0; i < length; i++) {
11570 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011571 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011573 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574}
11575
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011576PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011577 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011579Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011580False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581
11582static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011583unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 Py_ssize_t i, length;
11586 int kind;
11587 void *data;
11588
11589 if (PyUnicode_READY(self) == -1)
11590 return NULL;
11591 length = PyUnicode_GET_LENGTH(self);
11592 kind = PyUnicode_KIND(self);
11593 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011594
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011596 if (length == 1)
11597 return PyBool_FromLong(
11598 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011600 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011601 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011602 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011603
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 for (i = 0; i < length; i++) {
11605 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011606 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011608 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609}
11610
Martin v. Löwis47383402007-08-15 07:32:56 +000011611int
11612PyUnicode_IsIdentifier(PyObject *self)
11613{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011614 int kind;
11615 void *data;
11616 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011617 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011618
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011619 if (PyUnicode_READY(self) == -1) {
11620 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011621 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622 }
11623
11624 /* Special case for empty strings */
11625 if (PyUnicode_GET_LENGTH(self) == 0)
11626 return 0;
11627 kind = PyUnicode_KIND(self);
11628 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011629
11630 /* PEP 3131 says that the first character must be in
11631 XID_Start and subsequent characters in XID_Continue,
11632 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011633 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011634 letters, digits, underscore). However, given the current
11635 definition of XID_Start and XID_Continue, it is sufficient
11636 to check just for these, except that _ must be allowed
11637 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011638 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011639 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011640 return 0;
11641
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011642 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011645 return 1;
11646}
11647
11648PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011650\n\
11651Return True if S is a valid identifier according\n\
11652to the language definition.");
11653
11654static PyObject*
11655unicode_isidentifier(PyObject *self)
11656{
11657 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11658}
11659
Georg Brandl559e5d72008-06-11 18:37:52 +000011660PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011661 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011662\n\
11663Return True if all characters in S are considered\n\
11664printable in repr() or S is empty, False otherwise.");
11665
11666static PyObject*
11667unicode_isprintable(PyObject *self)
11668{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011669 Py_ssize_t i, length;
11670 int kind;
11671 void *data;
11672
11673 if (PyUnicode_READY(self) == -1)
11674 return NULL;
11675 length = PyUnicode_GET_LENGTH(self);
11676 kind = PyUnicode_KIND(self);
11677 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011678
11679 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (length == 1)
11681 return PyBool_FromLong(
11682 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011683
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011684 for (i = 0; i < length; i++) {
11685 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011686 Py_RETURN_FALSE;
11687 }
11688 }
11689 Py_RETURN_TRUE;
11690}
11691
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011692PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011693 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694\n\
11695Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011696iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697
11698static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011699unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011701 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011702}
11703
Martin v. Löwis18e16552006-02-15 17:27:45 +000011704static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011705unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011706{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011707 if (PyUnicode_READY(self) == -1)
11708 return -1;
11709 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710}
11711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011712PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011713 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011714\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011715Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011716done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011717
11718static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011719unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011720{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011721 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011722 Py_UCS4 fillchar = ' ';
11723
11724 if (PyUnicode_READY(self) == -1)
11725 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011726
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011727 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011728 return NULL;
11729
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011731 Py_INCREF(self);
11732 return (PyObject*) self;
11733 }
11734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736}
11737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011738PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011739 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011741Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011742
11743static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011744unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011745{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746 return fixup(self, fixlower);
11747}
11748
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011749#define LEFTSTRIP 0
11750#define RIGHTSTRIP 1
11751#define BOTHSTRIP 2
11752
11753/* Arrays indexed by above */
11754static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11755
11756#define STRIPNAME(i) (stripformat[i]+3)
11757
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011758/* externally visible for str.strip(unicode) */
11759PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011760_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011761{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011762 void *data;
11763 int kind;
11764 Py_ssize_t i, j, len;
11765 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011767 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11768 return NULL;
11769
11770 kind = PyUnicode_KIND(self);
11771 data = PyUnicode_DATA(self);
11772 len = PyUnicode_GET_LENGTH(self);
11773 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11774 PyUnicode_DATA(sepobj),
11775 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011776
Benjamin Peterson14339b62009-01-31 16:36:08 +000011777 i = 0;
11778 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 while (i < len &&
11780 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011781 i++;
11782 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011783 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011784
Benjamin Peterson14339b62009-01-31 16:36:08 +000011785 j = len;
11786 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011787 do {
11788 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011789 } while (j >= i &&
11790 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011791 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011792 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011793
Victor Stinner12bab6d2011-10-01 01:53:49 +020011794 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011795}
11796
11797PyObject*
11798PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11799{
11800 unsigned char *data;
11801 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011802 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011803
Victor Stinnerde636f32011-10-01 03:55:54 +020011804 if (PyUnicode_READY(self) == -1)
11805 return NULL;
11806
11807 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11808
Victor Stinner12bab6d2011-10-01 01:53:49 +020011809 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011810 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011811 if (PyUnicode_CheckExact(self)) {
11812 Py_INCREF(self);
11813 return self;
11814 }
11815 else
11816 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 }
11818
Victor Stinner12bab6d2011-10-01 01:53:49 +020011819 length = end - start;
11820 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011821 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011822
Victor Stinnerde636f32011-10-01 03:55:54 +020011823 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011824 PyErr_SetString(PyExc_IndexError, "string index out of range");
11825 return NULL;
11826 }
11827
Victor Stinnerb9275c12011-10-05 14:01:42 +020011828 if (PyUnicode_IS_ASCII(self)) {
11829 kind = PyUnicode_KIND(self);
11830 data = PyUnicode_1BYTE_DATA(self);
11831 return unicode_fromascii(data + start, length);
11832 }
11833 else {
11834 kind = PyUnicode_KIND(self);
11835 data = PyUnicode_1BYTE_DATA(self);
11836 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011837 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011838 length);
11839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011841
11842static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011843do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011844{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011845 int kind;
11846 void *data;
11847 Py_ssize_t len, i, j;
11848
11849 if (PyUnicode_READY(self) == -1)
11850 return NULL;
11851
11852 kind = PyUnicode_KIND(self);
11853 data = PyUnicode_DATA(self);
11854 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011855
Benjamin Peterson14339b62009-01-31 16:36:08 +000011856 i = 0;
11857 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011858 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011859 i++;
11860 }
11861 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011862
Benjamin Peterson14339b62009-01-31 16:36:08 +000011863 j = len;
11864 if (striptype != LEFTSTRIP) {
11865 do {
11866 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011868 j++;
11869 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011870
Victor Stinner12bab6d2011-10-01 01:53:49 +020011871 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872}
11873
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011874
11875static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011876do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011877{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011878 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011879
Benjamin Peterson14339b62009-01-31 16:36:08 +000011880 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11881 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011882
Benjamin Peterson14339b62009-01-31 16:36:08 +000011883 if (sep != NULL && sep != Py_None) {
11884 if (PyUnicode_Check(sep))
11885 return _PyUnicode_XStrip(self, striptype, sep);
11886 else {
11887 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011888 "%s arg must be None or str",
11889 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011890 return NULL;
11891 }
11892 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011893
Benjamin Peterson14339b62009-01-31 16:36:08 +000011894 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011895}
11896
11897
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011898PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011900\n\
11901Return a copy of the string S with leading and trailing\n\
11902whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011903If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011904
11905static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011906unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011907{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011908 if (PyTuple_GET_SIZE(args) == 0)
11909 return do_strip(self, BOTHSTRIP); /* Common case */
11910 else
11911 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011912}
11913
11914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011915PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011916 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011917\n\
11918Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011919If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011920
11921static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011922unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011923{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011924 if (PyTuple_GET_SIZE(args) == 0)
11925 return do_strip(self, LEFTSTRIP); /* Common case */
11926 else
11927 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011928}
11929
11930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011931PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011933\n\
11934Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011935If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011936
11937static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011938unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011939{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011940 if (PyTuple_GET_SIZE(args) == 0)
11941 return do_strip(self, RIGHTSTRIP); /* Common case */
11942 else
11943 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011944}
11945
11946
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011948unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011950 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011951 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952
Georg Brandl222de0f2009-04-12 12:01:50 +000011953 if (len < 1) {
11954 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011955 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011956 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011957
Tim Peters7a29bd52001-09-12 03:03:31 +000011958 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959 /* no repeat, return original string */
11960 Py_INCREF(str);
11961 return (PyObject*) str;
11962 }
Tim Peters8f422462000-09-09 06:13:41 +000011963
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011964 if (PyUnicode_READY(str) == -1)
11965 return NULL;
11966
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011967 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011968 PyErr_SetString(PyExc_OverflowError,
11969 "repeated string is too long");
11970 return NULL;
11971 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011973
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011974 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011975 if (!u)
11976 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011977 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 if (PyUnicode_GET_LENGTH(str) == 1) {
11980 const int kind = PyUnicode_KIND(str);
11981 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11982 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011983 if (kind == PyUnicode_1BYTE_KIND)
11984 memset(to, (unsigned char)fill_char, len);
11985 else {
11986 for (n = 0; n < len; ++n)
11987 PyUnicode_WRITE(kind, to, n, fill_char);
11988 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 }
11990 else {
11991 /* number of characters copied this far */
11992 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011993 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011994 char *to = (char *) PyUnicode_DATA(u);
11995 Py_MEMCPY(to, PyUnicode_DATA(str),
11996 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011997 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 n = (done <= nchars-done) ? done : nchars-done;
11999 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012000 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012001 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012002 }
12003
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012004 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012005 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012006}
12007
Alexander Belopolsky40018472011-02-26 01:02:56 +000012008PyObject *
12009PyUnicode_Replace(PyObject *obj,
12010 PyObject *subobj,
12011 PyObject *replobj,
12012 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012013{
12014 PyObject *self;
12015 PyObject *str1;
12016 PyObject *str2;
12017 PyObject *result;
12018
12019 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012020 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012023 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012024 Py_DECREF(self);
12025 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012026 }
12027 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012028 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012029 Py_DECREF(self);
12030 Py_DECREF(str1);
12031 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012033 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012034 Py_DECREF(self);
12035 Py_DECREF(str1);
12036 Py_DECREF(str2);
12037 return result;
12038}
12039
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012040PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012041 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012042\n\
12043Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012044old replaced by new. If the optional argument count is\n\
12045given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046
12047static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012049{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012050 PyObject *str1;
12051 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012052 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012053 PyObject *result;
12054
Martin v. Löwis18e16552006-02-15 17:27:45 +000012055 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012056 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012057 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012058 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 str1 = PyUnicode_FromObject(str1);
12060 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12061 return NULL;
12062 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012063 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012064 Py_DECREF(str1);
12065 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012066 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067
12068 result = replace(self, str1, str2, maxcount);
12069
12070 Py_DECREF(str1);
12071 Py_DECREF(str2);
12072 return result;
12073}
12074
Alexander Belopolsky40018472011-02-26 01:02:56 +000012075static PyObject *
12076unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012078 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012079 Py_ssize_t isize;
12080 Py_ssize_t osize, squote, dquote, i, o;
12081 Py_UCS4 max, quote;
12082 int ikind, okind;
12083 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012084
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012086 return NULL;
12087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012088 isize = PyUnicode_GET_LENGTH(unicode);
12089 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012091 /* Compute length of output, quote characters, and
12092 maximum character */
12093 osize = 2; /* quotes */
12094 max = 127;
12095 squote = dquote = 0;
12096 ikind = PyUnicode_KIND(unicode);
12097 for (i = 0; i < isize; i++) {
12098 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12099 switch (ch) {
12100 case '\'': squote++; osize++; break;
12101 case '"': dquote++; osize++; break;
12102 case '\\': case '\t': case '\r': case '\n':
12103 osize += 2; break;
12104 default:
12105 /* Fast-path ASCII */
12106 if (ch < ' ' || ch == 0x7f)
12107 osize += 4; /* \xHH */
12108 else if (ch < 0x7f)
12109 osize++;
12110 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12111 osize++;
12112 max = ch > max ? ch : max;
12113 }
12114 else if (ch < 0x100)
12115 osize += 4; /* \xHH */
12116 else if (ch < 0x10000)
12117 osize += 6; /* \uHHHH */
12118 else
12119 osize += 10; /* \uHHHHHHHH */
12120 }
12121 }
12122
12123 quote = '\'';
12124 if (squote) {
12125 if (dquote)
12126 /* Both squote and dquote present. Use squote,
12127 and escape them */
12128 osize += squote;
12129 else
12130 quote = '"';
12131 }
12132
12133 repr = PyUnicode_New(osize, max);
12134 if (repr == NULL)
12135 return NULL;
12136 okind = PyUnicode_KIND(repr);
12137 odata = PyUnicode_DATA(repr);
12138
12139 PyUnicode_WRITE(okind, odata, 0, quote);
12140 PyUnicode_WRITE(okind, odata, osize-1, quote);
12141
12142 for (i = 0, o = 1; i < isize; i++) {
12143 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012144
12145 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146 if ((ch == quote) || (ch == '\\')) {
12147 PyUnicode_WRITE(okind, odata, o++, '\\');
12148 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012149 continue;
12150 }
12151
Benjamin Peterson29060642009-01-31 22:14:21 +000012152 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012153 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012154 PyUnicode_WRITE(okind, odata, o++, '\\');
12155 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012156 }
12157 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158 PyUnicode_WRITE(okind, odata, o++, '\\');
12159 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012160 }
12161 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162 PyUnicode_WRITE(okind, odata, o++, '\\');
12163 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012164 }
12165
12166 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012167 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012168 PyUnicode_WRITE(okind, odata, o++, '\\');
12169 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012170 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12171 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012172 }
12173
Georg Brandl559e5d72008-06-11 18:37:52 +000012174 /* Copy ASCII characters as-is */
12175 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012177 }
12178
Benjamin Peterson29060642009-01-31 22:14:21 +000012179 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012180 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012181 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012182 (categories Z* and C* except ASCII space)
12183 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012184 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012185 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012186 if (ch <= 0xff) {
12187 PyUnicode_WRITE(okind, odata, o++, '\\');
12188 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012189 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12190 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012191 }
12192 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012193 else if (ch >= 0x10000) {
12194 PyUnicode_WRITE(okind, odata, o++, '\\');
12195 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012196 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12197 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12198 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12199 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12200 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12201 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12202 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12203 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012204 }
12205 /* Map 16-bit characters to '\uxxxx' */
12206 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 PyUnicode_WRITE(okind, odata, o++, '\\');
12208 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012209 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12210 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12211 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12212 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012213 }
12214 }
12215 /* Copy characters as-is */
12216 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012217 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012218 }
12219 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012222 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012223 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224}
12225
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012226PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012227 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228\n\
12229Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012230such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012231arguments start and end are interpreted as in slice notation.\n\
12232\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012233Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234
12235static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012236unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012238 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012239 Py_ssize_t start;
12240 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012241 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242
Jesus Ceaac451502011-04-20 17:09:23 +020012243 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12244 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012245 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 if (PyUnicode_READY(self) == -1)
12248 return NULL;
12249 if (PyUnicode_READY(substring) == -1)
12250 return NULL;
12251
Victor Stinner794d5672011-10-10 03:21:36 +020012252 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012253 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012254 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012255
12256 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258 if (result == -2)
12259 return NULL;
12260
Christian Heimes217cfd12007-12-02 14:31:20 +000012261 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012262}
12263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012264PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012265 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012266\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012267Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268
12269static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012270unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012271{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012272 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012273 Py_ssize_t start;
12274 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012275 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276
Jesus Ceaac451502011-04-20 17:09:23 +020012277 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12278 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012279 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012280
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012281 if (PyUnicode_READY(self) == -1)
12282 return NULL;
12283 if (PyUnicode_READY(substring) == -1)
12284 return NULL;
12285
Victor Stinner794d5672011-10-10 03:21:36 +020012286 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012287 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012288 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289
12290 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 if (result == -2)
12293 return NULL;
12294
Guido van Rossumd57fd912000-03-10 22:53:23 +000012295 if (result < 0) {
12296 PyErr_SetString(PyExc_ValueError, "substring not found");
12297 return NULL;
12298 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299
Christian Heimes217cfd12007-12-02 14:31:20 +000012300 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012301}
12302
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012303PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012304 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012306Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012307done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308
12309static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012310unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012311{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012312 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 Py_UCS4 fillchar = ' ';
12314
Victor Stinnere9a29352011-10-01 02:14:59 +020012315 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012317
Victor Stinnere9a29352011-10-01 02:14:59 +020012318 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012319 return NULL;
12320
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012322 Py_INCREF(self);
12323 return (PyObject*) self;
12324 }
12325
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012326 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012327}
12328
Alexander Belopolsky40018472011-02-26 01:02:56 +000012329PyObject *
12330PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012331{
12332 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012333
Guido van Rossumd57fd912000-03-10 22:53:23 +000012334 s = PyUnicode_FromObject(s);
12335 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012336 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012337 if (sep != NULL) {
12338 sep = PyUnicode_FromObject(sep);
12339 if (sep == NULL) {
12340 Py_DECREF(s);
12341 return NULL;
12342 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012343 }
12344
Victor Stinner9310abb2011-10-05 00:59:23 +020012345 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346
12347 Py_DECREF(s);
12348 Py_XDECREF(sep);
12349 return result;
12350}
12351
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012352PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012353 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012354\n\
12355Return a list of the words in S, using sep as the\n\
12356delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012357splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012358whitespace string is a separator and empty strings are\n\
12359removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360
12361static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012362unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012363{
12364 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012365 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012366
Martin v. Löwis18e16552006-02-15 17:27:45 +000012367 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012368 return NULL;
12369
12370 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012371 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012372 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012373 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012374 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012375 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012376}
12377
Thomas Wouters477c8d52006-05-27 19:21:47 +000012378PyObject *
12379PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12380{
12381 PyObject* str_obj;
12382 PyObject* sep_obj;
12383 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 int kind1, kind2, kind;
12385 void *buf1 = NULL, *buf2 = NULL;
12386 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012387
12388 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012389 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012390 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012391 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012392 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393 Py_DECREF(str_obj);
12394 return NULL;
12395 }
12396
Victor Stinner14f8f022011-10-05 20:58:25 +020012397 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012398 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012399 kind = Py_MAX(kind1, kind2);
12400 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012401 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012402 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012403 if (!buf1)
12404 goto onError;
12405 buf2 = PyUnicode_DATA(sep_obj);
12406 if (kind2 != kind)
12407 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12408 if (!buf2)
12409 goto onError;
12410 len1 = PyUnicode_GET_LENGTH(str_obj);
12411 len2 = PyUnicode_GET_LENGTH(sep_obj);
12412
Victor Stinner14f8f022011-10-05 20:58:25 +020012413 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012414 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012415 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12416 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12417 else
12418 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 break;
12420 case PyUnicode_2BYTE_KIND:
12421 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12422 break;
12423 case PyUnicode_4BYTE_KIND:
12424 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12425 break;
12426 default:
12427 assert(0);
12428 out = 0;
12429 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012430
12431 Py_DECREF(sep_obj);
12432 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012433 if (kind1 != kind)
12434 PyMem_Free(buf1);
12435 if (kind2 != kind)
12436 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012437
12438 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012439 onError:
12440 Py_DECREF(sep_obj);
12441 Py_DECREF(str_obj);
12442 if (kind1 != kind && buf1)
12443 PyMem_Free(buf1);
12444 if (kind2 != kind && buf2)
12445 PyMem_Free(buf2);
12446 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012447}
12448
12449
12450PyObject *
12451PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12452{
12453 PyObject* str_obj;
12454 PyObject* sep_obj;
12455 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012456 int kind1, kind2, kind;
12457 void *buf1 = NULL, *buf2 = NULL;
12458 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012459
12460 str_obj = PyUnicode_FromObject(str_in);
12461 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012462 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012463 sep_obj = PyUnicode_FromObject(sep_in);
12464 if (!sep_obj) {
12465 Py_DECREF(str_obj);
12466 return NULL;
12467 }
12468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012469 kind1 = PyUnicode_KIND(str_in);
12470 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012471 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012472 buf1 = PyUnicode_DATA(str_in);
12473 if (kind1 != kind)
12474 buf1 = _PyUnicode_AsKind(str_in, kind);
12475 if (!buf1)
12476 goto onError;
12477 buf2 = PyUnicode_DATA(sep_obj);
12478 if (kind2 != kind)
12479 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12480 if (!buf2)
12481 goto onError;
12482 len1 = PyUnicode_GET_LENGTH(str_obj);
12483 len2 = PyUnicode_GET_LENGTH(sep_obj);
12484
12485 switch(PyUnicode_KIND(str_in)) {
12486 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012487 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12488 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12489 else
12490 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 break;
12492 case PyUnicode_2BYTE_KIND:
12493 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12494 break;
12495 case PyUnicode_4BYTE_KIND:
12496 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12497 break;
12498 default:
12499 assert(0);
12500 out = 0;
12501 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012502
12503 Py_DECREF(sep_obj);
12504 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012505 if (kind1 != kind)
12506 PyMem_Free(buf1);
12507 if (kind2 != kind)
12508 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012509
12510 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012511 onError:
12512 Py_DECREF(sep_obj);
12513 Py_DECREF(str_obj);
12514 if (kind1 != kind && buf1)
12515 PyMem_Free(buf1);
12516 if (kind2 != kind && buf2)
12517 PyMem_Free(buf2);
12518 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012519}
12520
12521PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012522 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012523\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012524Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012525the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012526found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012527
12528static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012529unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012530{
Victor Stinner9310abb2011-10-05 00:59:23 +020012531 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012532}
12533
12534PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012535 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012536\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012537Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012538the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012539separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012540
12541static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012542unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012543{
Victor Stinner9310abb2011-10-05 00:59:23 +020012544 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012545}
12546
Alexander Belopolsky40018472011-02-26 01:02:56 +000012547PyObject *
12548PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012549{
12550 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012551
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012552 s = PyUnicode_FromObject(s);
12553 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012554 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012555 if (sep != NULL) {
12556 sep = PyUnicode_FromObject(sep);
12557 if (sep == NULL) {
12558 Py_DECREF(s);
12559 return NULL;
12560 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012561 }
12562
Victor Stinner9310abb2011-10-05 00:59:23 +020012563 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012564
12565 Py_DECREF(s);
12566 Py_XDECREF(sep);
12567 return result;
12568}
12569
12570PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012571 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012572\n\
12573Return a list of the words in S, using sep as the\n\
12574delimiter string, starting at the end of the string and\n\
12575working to the front. If maxsplit is given, at most maxsplit\n\
12576splits are done. If sep is not specified, any whitespace string\n\
12577is a separator.");
12578
12579static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012580unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012581{
12582 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012583 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012584
Martin v. Löwis18e16552006-02-15 17:27:45 +000012585 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012586 return NULL;
12587
12588 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012589 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012590 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012591 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012592 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012593 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012594}
12595
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012596PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012597 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012598\n\
12599Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012600Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012601is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012602
12603static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012604unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012605{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012606 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012607 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012608
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012609 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12610 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611 return NULL;
12612
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012613 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012614}
12615
12616static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012617PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618{
Walter Dörwald346737f2007-05-31 10:44:43 +000012619 if (PyUnicode_CheckExact(self)) {
12620 Py_INCREF(self);
12621 return self;
12622 } else
12623 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012624 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012625}
12626
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012627PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012628 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012629\n\
12630Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012631and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632
12633static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012634unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636 return fixup(self, fixswapcase);
12637}
12638
Georg Brandlceee0772007-11-27 23:48:05 +000012639PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012640 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012641\n\
12642Return a translation table usable for str.translate().\n\
12643If there is only one argument, it must be a dictionary mapping Unicode\n\
12644ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012645Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012646If there are two arguments, they must be strings of equal length, and\n\
12647in the resulting dictionary, each character in x will be mapped to the\n\
12648character at the same position in y. If there is a third argument, it\n\
12649must be a string, whose characters will be mapped to None in the result.");
12650
12651static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012652unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012653{
12654 PyObject *x, *y = NULL, *z = NULL;
12655 PyObject *new = NULL, *key, *value;
12656 Py_ssize_t i = 0;
12657 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012658
Georg Brandlceee0772007-11-27 23:48:05 +000012659 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12660 return NULL;
12661 new = PyDict_New();
12662 if (!new)
12663 return NULL;
12664 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012665 int x_kind, y_kind, z_kind;
12666 void *x_data, *y_data, *z_data;
12667
Georg Brandlceee0772007-11-27 23:48:05 +000012668 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012669 if (!PyUnicode_Check(x)) {
12670 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12671 "be a string if there is a second argument");
12672 goto err;
12673 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012675 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12676 "arguments must have equal length");
12677 goto err;
12678 }
12679 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 x_kind = PyUnicode_KIND(x);
12681 y_kind = PyUnicode_KIND(y);
12682 x_data = PyUnicode_DATA(x);
12683 y_data = PyUnicode_DATA(y);
12684 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12685 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12686 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012687 if (!key || !value)
12688 goto err;
12689 res = PyDict_SetItem(new, key, value);
12690 Py_DECREF(key);
12691 Py_DECREF(value);
12692 if (res < 0)
12693 goto err;
12694 }
12695 /* create entries for deleting chars in z */
12696 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012697 z_kind = PyUnicode_KIND(z);
12698 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012699 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012700 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012701 if (!key)
12702 goto err;
12703 res = PyDict_SetItem(new, key, Py_None);
12704 Py_DECREF(key);
12705 if (res < 0)
12706 goto err;
12707 }
12708 }
12709 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012710 int kind;
12711 void *data;
12712
Georg Brandlceee0772007-11-27 23:48:05 +000012713 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012714 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012715 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12716 "to maketrans it must be a dict");
12717 goto err;
12718 }
12719 /* copy entries into the new dict, converting string keys to int keys */
12720 while (PyDict_Next(x, &i, &key, &value)) {
12721 if (PyUnicode_Check(key)) {
12722 /* convert string keys to integer keys */
12723 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012724 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012725 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12726 "table must be of length 1");
12727 goto err;
12728 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012729 kind = PyUnicode_KIND(key);
12730 data = PyUnicode_DATA(key);
12731 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012732 if (!newkey)
12733 goto err;
12734 res = PyDict_SetItem(new, newkey, value);
12735 Py_DECREF(newkey);
12736 if (res < 0)
12737 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012738 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012739 /* just keep integer keys */
12740 if (PyDict_SetItem(new, key, value) < 0)
12741 goto err;
12742 } else {
12743 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12744 "be strings or integers");
12745 goto err;
12746 }
12747 }
12748 }
12749 return new;
12750 err:
12751 Py_DECREF(new);
12752 return NULL;
12753}
12754
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012755PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012756 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757\n\
12758Return a copy of the string S, where all characters have been mapped\n\
12759through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012760Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012761Unmapped characters are left untouched. Characters mapped to None\n\
12762are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763
12764static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012765unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012766{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012767 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012768}
12769
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012770PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012771 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012773Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774
12775static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012776unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012777{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778 return fixup(self, fixupper);
12779}
12780
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012781PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012784Pad a numeric string S with zeros on the left, to fill a field\n\
12785of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012786
12787static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012788unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012789{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012790 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012791 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012792 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012793 int kind;
12794 void *data;
12795 Py_UCS4 chr;
12796
12797 if (PyUnicode_READY(self) == -1)
12798 return NULL;
12799
Martin v. Löwis18e16552006-02-15 17:27:45 +000012800 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012801 return NULL;
12802
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012804 if (PyUnicode_CheckExact(self)) {
12805 Py_INCREF(self);
12806 return (PyObject*) self;
12807 }
12808 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012809 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810 }
12811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012812 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813
12814 u = pad(self, fill, 0, '0');
12815
Walter Dörwald068325e2002-04-15 13:36:47 +000012816 if (u == NULL)
12817 return NULL;
12818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012819 kind = PyUnicode_KIND(u);
12820 data = PyUnicode_DATA(u);
12821 chr = PyUnicode_READ(kind, data, fill);
12822
12823 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012824 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012825 PyUnicode_WRITE(kind, data, 0, chr);
12826 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012827 }
12828
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012829 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012830 return (PyObject*) u;
12831}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012832
12833#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012834static PyObject *
12835unicode__decimal2ascii(PyObject *self)
12836{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012837 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012838}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012839#endif
12840
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012841PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012842 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012843\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012844Return True if S starts with the specified prefix, False otherwise.\n\
12845With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012846With optional end, stop comparing S at that position.\n\
12847prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012848
12849static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012850unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012851 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012852{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012853 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012854 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012855 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012856 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012857 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012858
Jesus Ceaac451502011-04-20 17:09:23 +020012859 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012860 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012861 if (PyTuple_Check(subobj)) {
12862 Py_ssize_t i;
12863 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012864 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012865 if (substring == NULL)
12866 return NULL;
12867 result = tailmatch(self, substring, start, end, -1);
12868 Py_DECREF(substring);
12869 if (result) {
12870 Py_RETURN_TRUE;
12871 }
12872 }
12873 /* nothing matched */
12874 Py_RETURN_FALSE;
12875 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012876 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012877 if (substring == NULL) {
12878 if (PyErr_ExceptionMatches(PyExc_TypeError))
12879 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12880 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012881 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012882 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012883 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012885 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886}
12887
12888
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012889PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012890 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012892Return True if S ends with the specified suffix, False otherwise.\n\
12893With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012894With optional end, stop comparing S at that position.\n\
12895suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012896
12897static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012898unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012899 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012900{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012901 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012902 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012903 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012904 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012905 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012906
Jesus Ceaac451502011-04-20 17:09:23 +020012907 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012908 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012909 if (PyTuple_Check(subobj)) {
12910 Py_ssize_t i;
12911 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012912 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012913 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012914 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012916 result = tailmatch(self, substring, start, end, +1);
12917 Py_DECREF(substring);
12918 if (result) {
12919 Py_RETURN_TRUE;
12920 }
12921 }
12922 Py_RETURN_FALSE;
12923 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012924 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012925 if (substring == NULL) {
12926 if (PyErr_ExceptionMatches(PyExc_TypeError))
12927 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12928 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012929 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012930 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012931 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012933 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012934}
12935
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012936#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012937
12938PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012939 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012940\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012941Return a formatted version of S, using substitutions from args and kwargs.\n\
12942The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012943
Eric Smith27bbca62010-11-04 17:06:58 +000012944PyDoc_STRVAR(format_map__doc__,
12945 "S.format_map(mapping) -> str\n\
12946\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012947Return a formatted version of S, using substitutions from mapping.\n\
12948The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012949
Eric Smith4a7d76d2008-05-30 18:10:19 +000012950static PyObject *
12951unicode__format__(PyObject* self, PyObject* args)
12952{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012953 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012954
12955 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12956 return NULL;
12957
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012958 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012959 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012960 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012961}
12962
Eric Smith8c663262007-08-25 02:26:07 +000012963PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012964 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012965\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012966Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012967
12968static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012969unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012971 Py_ssize_t size;
12972
12973 /* If it's a compact object, account for base structure +
12974 character data. */
12975 if (PyUnicode_IS_COMPACT_ASCII(v))
12976 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12977 else if (PyUnicode_IS_COMPACT(v))
12978 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012979 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980 else {
12981 /* If it is a two-block object, account for base object, and
12982 for character block if present. */
12983 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012984 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012986 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012987 }
12988 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012989 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012990 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012992 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012993 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994
12995 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012996}
12997
12998PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012999 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013000
13001static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013002unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013003{
Victor Stinner034f6cf2011-09-30 02:26:44 +020013004 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013005 if (!copy)
13006 return NULL;
13007 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013008}
13009
Guido van Rossumd57fd912000-03-10 22:53:23 +000013010static PyMethodDef unicode_methods[] = {
13011
13012 /* Order is according to common usage: often used methods should
13013 appear first, since lookup is done sequentially. */
13014
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013015 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013016 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13017 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013018 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013019 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13020 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13021 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13022 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13023 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13024 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13025 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013026 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013027 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13028 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13029 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013030 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013031 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13032 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13033 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013034 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013035 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013036 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013037 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013038 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13039 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13040 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13041 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13042 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13043 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13044 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13045 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13046 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13047 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13048 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13049 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13050 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13051 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013052 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013053 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013054 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013055 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013056 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013057 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013058 {"maketrans", (PyCFunction) unicode_maketrans,
13059 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013060 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013061#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013062 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013063#endif
13064
13065#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013066 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013067 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068#endif
13069
Benjamin Peterson14339b62009-01-31 16:36:08 +000013070 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071 {NULL, NULL}
13072};
13073
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013074static PyObject *
13075unicode_mod(PyObject *v, PyObject *w)
13076{
Brian Curtindfc80e32011-08-10 20:28:54 -050013077 if (!PyUnicode_Check(v))
13078 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013079 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013080}
13081
13082static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013083 0, /*nb_add*/
13084 0, /*nb_subtract*/
13085 0, /*nb_multiply*/
13086 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013087};
13088
Guido van Rossumd57fd912000-03-10 22:53:23 +000013089static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013090 (lenfunc) unicode_length, /* sq_length */
13091 PyUnicode_Concat, /* sq_concat */
13092 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13093 (ssizeargfunc) unicode_getitem, /* sq_item */
13094 0, /* sq_slice */
13095 0, /* sq_ass_item */
13096 0, /* sq_ass_slice */
13097 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098};
13099
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013100static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013101unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013102{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013103 if (PyUnicode_READY(self) == -1)
13104 return NULL;
13105
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013106 if (PyIndex_Check(item)) {
13107 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013108 if (i == -1 && PyErr_Occurred())
13109 return NULL;
13110 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013111 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013112 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013113 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013114 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013115 PyObject *result;
13116 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013117 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013118 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013119
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013120 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013121 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013122 return NULL;
13123 }
13124
13125 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013126 return PyUnicode_New(0, 0);
13127 } else if (start == 0 && step == 1 &&
13128 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013129 PyUnicode_CheckExact(self)) {
13130 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013131 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013132 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013133 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013134 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013135 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013136 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013137 src_kind = PyUnicode_KIND(self);
13138 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013139 if (!PyUnicode_IS_ASCII(self)) {
13140 kind_limit = kind_maxchar_limit(src_kind);
13141 max_char = 0;
13142 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13143 ch = PyUnicode_READ(src_kind, src_data, cur);
13144 if (ch > max_char) {
13145 max_char = ch;
13146 if (max_char >= kind_limit)
13147 break;
13148 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013149 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013150 }
Victor Stinner55c99112011-10-13 01:17:06 +020013151 else
13152 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013153 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013154 if (result == NULL)
13155 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013156 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013157 dest_data = PyUnicode_DATA(result);
13158
13159 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013160 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13161 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013162 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013163 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013164 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013165 } else {
13166 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13167 return NULL;
13168 }
13169}
13170
13171static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013172 (lenfunc)unicode_length, /* mp_length */
13173 (binaryfunc)unicode_subscript, /* mp_subscript */
13174 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013175};
13176
Guido van Rossumd57fd912000-03-10 22:53:23 +000013177
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178/* Helpers for PyUnicode_Format() */
13179
13180static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013181getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013183 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 (*p_argidx)++;
13186 if (arglen < 0)
13187 return args;
13188 else
13189 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190 }
13191 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013192 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013193 return NULL;
13194}
13195
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013196/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013198static PyObject *
13199formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013200{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013201 char *p;
13202 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013203 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013204
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 x = PyFloat_AsDouble(v);
13206 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013207 return NULL;
13208
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013210 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013211
Eric Smith0923d1d2009-04-16 20:16:10 +000013212 p = PyOS_double_to_string(x, type, prec,
13213 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013214 if (p == NULL)
13215 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013216 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013217 PyMem_Free(p);
13218 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219}
13220
Tim Peters38fd5b62000-09-21 05:43:11 +000013221static PyObject*
13222formatlong(PyObject *val, int flags, int prec, int type)
13223{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013224 char *buf;
13225 int len;
13226 PyObject *str; /* temporary string object. */
13227 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013228
Benjamin Peterson14339b62009-01-31 16:36:08 +000013229 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13230 if (!str)
13231 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013232 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013233 Py_DECREF(str);
13234 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013235}
13236
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013237static Py_UCS4
13238formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013239{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013240 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013241 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013242 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013243 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 goto onError;
13246 }
13247 else {
13248 /* Integer input truncated to a character */
13249 long x;
13250 x = PyLong_AsLong(v);
13251 if (x == -1 && PyErr_Occurred())
13252 goto onError;
13253
13254 if (x < 0 || x > 0x10ffff) {
13255 PyErr_SetString(PyExc_OverflowError,
13256 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013257 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 }
13259
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013260 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013261 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013262
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013264 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013265 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013266 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013267}
13268
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013269static int
13270repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13271{
13272 int r;
13273 assert(count > 0);
13274 assert(PyUnicode_Check(obj));
13275 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013276 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013277 if (repeated == NULL)
13278 return -1;
13279 r = _PyAccu_Accumulate(acc, repeated);
13280 Py_DECREF(repeated);
13281 return r;
13282 }
13283 else {
13284 do {
13285 if (_PyAccu_Accumulate(acc, obj))
13286 return -1;
13287 } while (--count);
13288 return 0;
13289 }
13290}
13291
Alexander Belopolsky40018472011-02-26 01:02:56 +000013292PyObject *
13293PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013294{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013295 void *fmt;
13296 int fmtkind;
13297 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013298 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013299 int r;
13300 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013301 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013303 PyObject *temp = NULL;
13304 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013305 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013306 _PyAccu acc;
13307 static PyObject *plus, *minus, *blank, *zero, *percent;
13308
13309 if (!plus && !(plus = get_latin1_char('+')))
13310 return NULL;
13311 if (!minus && !(minus = get_latin1_char('-')))
13312 return NULL;
13313 if (!blank && !(blank = get_latin1_char(' ')))
13314 return NULL;
13315 if (!zero && !(zero = get_latin1_char('0')))
13316 return NULL;
13317 if (!percent && !(percent = get_latin1_char('%')))
13318 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013319
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013321 PyErr_BadInternalCall();
13322 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013323 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013324 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013325 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013326 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013327 if (_PyAccu_Init(&acc))
13328 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013329 fmt = PyUnicode_DATA(uformat);
13330 fmtkind = PyUnicode_KIND(uformat);
13331 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13332 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013333
Guido van Rossumd57fd912000-03-10 22:53:23 +000013334 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013335 arglen = PyTuple_Size(args);
13336 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013337 }
13338 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013339 arglen = -1;
13340 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013341 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013342 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013343 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013345
13346 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013347 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013348 PyObject *nonfmt;
13349 Py_ssize_t nonfmtpos;
13350 nonfmtpos = fmtpos++;
13351 while (fmtcnt >= 0 &&
13352 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13353 fmtpos++;
13354 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013355 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013356 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
13357 if (nonfmt == NULL)
13358 goto onError;
13359 r = _PyAccu_Accumulate(&acc, nonfmt);
13360 Py_DECREF(nonfmt);
13361 if (r)
13362 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013363 }
13364 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013365 /* Got a format specifier */
13366 int flags = 0;
13367 Py_ssize_t width = -1;
13368 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013369 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013370 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013371 int isnumok;
13372 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013373 void *pbuf = NULL;
13374 Py_ssize_t pindex, len;
13375 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 fmtpos++;
13378 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13379 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 Py_ssize_t keylen;
13381 PyObject *key;
13382 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013383
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 if (dict == NULL) {
13385 PyErr_SetString(PyExc_TypeError,
13386 "format requires a mapping");
13387 goto onError;
13388 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013389 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013390 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013391 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 /* Skip over balanced parentheses */
13393 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013394 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013396 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013397 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013398 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013400 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013401 if (fmtcnt < 0 || pcount > 0) {
13402 PyErr_SetString(PyExc_ValueError,
13403 "incomplete format key");
13404 goto onError;
13405 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020013406 key = PyUnicode_Substring((PyObject*)uformat,
13407 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 if (key == NULL)
13409 goto onError;
13410 if (args_owned) {
13411 Py_DECREF(args);
13412 args_owned = 0;
13413 }
13414 args = PyObject_GetItem(dict, key);
13415 Py_DECREF(key);
13416 if (args == NULL) {
13417 goto onError;
13418 }
13419 args_owned = 1;
13420 arglen = -1;
13421 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013422 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013424 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013425 case '-': flags |= F_LJUST; continue;
13426 case '+': flags |= F_SIGN; continue;
13427 case ' ': flags |= F_BLANK; continue;
13428 case '#': flags |= F_ALT; continue;
13429 case '0': flags |= F_ZERO; continue;
13430 }
13431 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013432 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 if (c == '*') {
13434 v = getnextarg(args, arglen, &argidx);
13435 if (v == NULL)
13436 goto onError;
13437 if (!PyLong_Check(v)) {
13438 PyErr_SetString(PyExc_TypeError,
13439 "* wants int");
13440 goto onError;
13441 }
13442 width = PyLong_AsLong(v);
13443 if (width == -1 && PyErr_Occurred())
13444 goto onError;
13445 if (width < 0) {
13446 flags |= F_LJUST;
13447 width = -width;
13448 }
13449 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013450 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013451 }
13452 else if (c >= '0' && c <= '9') {
13453 width = c - '0';
13454 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013455 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 if (c < '0' || c > '9')
13457 break;
13458 if ((width*10) / 10 != width) {
13459 PyErr_SetString(PyExc_ValueError,
13460 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013461 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013462 }
13463 width = width*10 + (c - '0');
13464 }
13465 }
13466 if (c == '.') {
13467 prec = 0;
13468 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013469 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 if (c == '*') {
13471 v = getnextarg(args, arglen, &argidx);
13472 if (v == NULL)
13473 goto onError;
13474 if (!PyLong_Check(v)) {
13475 PyErr_SetString(PyExc_TypeError,
13476 "* wants int");
13477 goto onError;
13478 }
13479 prec = PyLong_AsLong(v);
13480 if (prec == -1 && PyErr_Occurred())
13481 goto onError;
13482 if (prec < 0)
13483 prec = 0;
13484 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013485 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013486 }
13487 else if (c >= '0' && c <= '9') {
13488 prec = c - '0';
13489 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013490 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013491 if (c < '0' || c > '9')
13492 break;
13493 if ((prec*10) / 10 != prec) {
13494 PyErr_SetString(PyExc_ValueError,
13495 "prec too big");
13496 goto onError;
13497 }
13498 prec = prec*10 + (c - '0');
13499 }
13500 }
13501 } /* prec */
13502 if (fmtcnt >= 0) {
13503 if (c == 'h' || c == 'l' || c == 'L') {
13504 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013505 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013506 }
13507 }
13508 if (fmtcnt < 0) {
13509 PyErr_SetString(PyExc_ValueError,
13510 "incomplete format");
13511 goto onError;
13512 }
13513 if (c != '%') {
13514 v = getnextarg(args, arglen, &argidx);
13515 if (v == NULL)
13516 goto onError;
13517 }
13518 sign = 0;
13519 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013520 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 switch (c) {
13522
13523 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013524 _PyAccu_Accumulate(&acc, percent);
13525 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013526
13527 case 's':
13528 case 'r':
13529 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013530 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 temp = v;
13532 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013533 }
13534 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 if (c == 's')
13536 temp = PyObject_Str(v);
13537 else if (c == 'r')
13538 temp = PyObject_Repr(v);
13539 else
13540 temp = PyObject_ASCII(v);
13541 if (temp == NULL)
13542 goto onError;
13543 if (PyUnicode_Check(temp))
13544 /* nothing to do */;
13545 else {
13546 Py_DECREF(temp);
13547 PyErr_SetString(PyExc_TypeError,
13548 "%s argument has non-string str()");
13549 goto onError;
13550 }
13551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013552 if (PyUnicode_READY(temp) == -1) {
13553 Py_CLEAR(temp);
13554 goto onError;
13555 }
13556 pbuf = PyUnicode_DATA(temp);
13557 kind = PyUnicode_KIND(temp);
13558 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013559 if (prec >= 0 && len > prec)
13560 len = prec;
13561 break;
13562
13563 case 'i':
13564 case 'd':
13565 case 'u':
13566 case 'o':
13567 case 'x':
13568 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 isnumok = 0;
13570 if (PyNumber_Check(v)) {
13571 PyObject *iobj=NULL;
13572
13573 if (PyLong_Check(v)) {
13574 iobj = v;
13575 Py_INCREF(iobj);
13576 }
13577 else {
13578 iobj = PyNumber_Long(v);
13579 }
13580 if (iobj!=NULL) {
13581 if (PyLong_Check(iobj)) {
13582 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013583 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013584 Py_DECREF(iobj);
13585 if (!temp)
13586 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013587 if (PyUnicode_READY(temp) == -1) {
13588 Py_CLEAR(temp);
13589 goto onError;
13590 }
13591 pbuf = PyUnicode_DATA(temp);
13592 kind = PyUnicode_KIND(temp);
13593 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013594 sign = 1;
13595 }
13596 else {
13597 Py_DECREF(iobj);
13598 }
13599 }
13600 }
13601 if (!isnumok) {
13602 PyErr_Format(PyExc_TypeError,
13603 "%%%c format: a number is required, "
13604 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13605 goto onError;
13606 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013607 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013608 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013609 fillobj = zero;
13610 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013611 break;
13612
13613 case 'e':
13614 case 'E':
13615 case 'f':
13616 case 'F':
13617 case 'g':
13618 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013619 temp = formatfloat(v, flags, prec, c);
13620 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013621 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013622 if (PyUnicode_READY(temp) == -1) {
13623 Py_CLEAR(temp);
13624 goto onError;
13625 }
13626 pbuf = PyUnicode_DATA(temp);
13627 kind = PyUnicode_KIND(temp);
13628 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013629 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013630 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013631 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013632 fillobj = zero;
13633 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 break;
13635
13636 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013637 {
13638 Py_UCS4 ch = formatchar(v);
13639 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013640 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013641 temp = _PyUnicode_FromUCS4(&ch, 1);
13642 if (temp == NULL)
13643 goto onError;
13644 pbuf = PyUnicode_DATA(temp);
13645 kind = PyUnicode_KIND(temp);
13646 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013647 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013648 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013649
13650 default:
13651 PyErr_Format(PyExc_ValueError,
13652 "unsupported format character '%c' (0x%x) "
13653 "at index %zd",
13654 (31<=c && c<=126) ? (char)c : '?',
13655 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013656 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 goto onError;
13658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013659 /* pbuf is initialized here. */
13660 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013661 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013662 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13663 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013665 pindex++;
13666 }
13667 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13668 signobj = plus;
13669 len--;
13670 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 }
13672 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013673 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013675 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013676 else
13677 sign = 0;
13678 }
13679 if (width < len)
13680 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013681 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013682 if (fill != ' ') {
13683 assert(signobj != NULL);
13684 if (_PyAccu_Accumulate(&acc, signobj))
13685 goto onError;
13686 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013687 if (width > len)
13688 width--;
13689 }
13690 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013691 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013692 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013693 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013694 second = get_latin1_char(
13695 PyUnicode_READ(kind, pbuf, pindex + 1));
13696 pindex += 2;
13697 if (second == NULL ||
13698 _PyAccu_Accumulate(&acc, zero) ||
13699 _PyAccu_Accumulate(&acc, second))
13700 goto onError;
13701 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013702 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013703 width -= 2;
13704 if (width < 0)
13705 width = 0;
13706 len -= 2;
13707 }
13708 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013709 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013710 if (repeat_accumulate(&acc, fillobj, width - len))
13711 goto onError;
13712 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013713 }
13714 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013715 if (sign) {
13716 assert(signobj != NULL);
13717 if (_PyAccu_Accumulate(&acc, signobj))
13718 goto onError;
13719 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013720 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013721 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13722 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013723 second = get_latin1_char(
13724 PyUnicode_READ(kind, pbuf, pindex + 1));
13725 pindex += 2;
13726 if (second == NULL ||
13727 _PyAccu_Accumulate(&acc, zero) ||
13728 _PyAccu_Accumulate(&acc, second))
13729 goto onError;
13730 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013731 }
13732 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013733 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013734 if (temp != NULL) {
13735 assert(pbuf == PyUnicode_DATA(temp));
13736 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013737 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013738 else {
13739 const char *p = (const char *) pbuf;
13740 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013741 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013742 v = PyUnicode_FromKindAndData(kind, p, len);
13743 }
13744 if (v == NULL)
13745 goto onError;
13746 r = _PyAccu_Accumulate(&acc, v);
13747 Py_DECREF(v);
13748 if (r)
13749 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013750 if (width > len && repeat_accumulate(&acc, blank, width - len))
13751 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013752 if (dict && (argidx < arglen) && c != '%') {
13753 PyErr_SetString(PyExc_TypeError,
13754 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013755 goto onError;
13756 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013757 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013759 } /* until end */
13760 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013761 PyErr_SetString(PyExc_TypeError,
13762 "not all arguments converted during string formatting");
13763 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013764 }
13765
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013766 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013767 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013768 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013769 }
13770 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013771 Py_XDECREF(temp);
13772 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013773 return (PyObject *)result;
13774
Benjamin Peterson29060642009-01-31 22:14:21 +000013775 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013776 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013777 Py_XDECREF(temp);
13778 Py_XDECREF(second);
13779 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013780 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013781 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013782 }
13783 return NULL;
13784}
13785
Jeremy Hylton938ace62002-07-17 16:30:39 +000013786static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013787unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13788
Tim Peters6d6c1a32001-08-02 04:15:00 +000013789static PyObject *
13790unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13791{
Benjamin Peterson29060642009-01-31 22:14:21 +000013792 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013793 static char *kwlist[] = {"object", "encoding", "errors", 0};
13794 char *encoding = NULL;
13795 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013796
Benjamin Peterson14339b62009-01-31 16:36:08 +000013797 if (type != &PyUnicode_Type)
13798 return unicode_subtype_new(type, args, kwds);
13799 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013800 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013801 return NULL;
13802 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013803 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013804 if (encoding == NULL && errors == NULL)
13805 return PyObject_Str(x);
13806 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013807 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013808}
13809
Guido van Rossume023fe02001-08-30 03:12:59 +000013810static PyObject *
13811unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13812{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013813 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013814 Py_ssize_t length, char_size;
13815 int share_wstr, share_utf8;
13816 unsigned int kind;
13817 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013818
Benjamin Peterson14339b62009-01-31 16:36:08 +000013819 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013820
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013821 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013822 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013823 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013824 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013825 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013826 return NULL;
13827
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013828 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013829 if (self == NULL) {
13830 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013831 return NULL;
13832 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013833 kind = PyUnicode_KIND(unicode);
13834 length = PyUnicode_GET_LENGTH(unicode);
13835
13836 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013837#ifdef Py_DEBUG
13838 _PyUnicode_HASH(self) = -1;
13839#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013840 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013841#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013842 _PyUnicode_STATE(self).interned = 0;
13843 _PyUnicode_STATE(self).kind = kind;
13844 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013845 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013846 _PyUnicode_STATE(self).ready = 1;
13847 _PyUnicode_WSTR(self) = NULL;
13848 _PyUnicode_UTF8_LENGTH(self) = 0;
13849 _PyUnicode_UTF8(self) = NULL;
13850 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013851 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013852
13853 share_utf8 = 0;
13854 share_wstr = 0;
13855 if (kind == PyUnicode_1BYTE_KIND) {
13856 char_size = 1;
13857 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13858 share_utf8 = 1;
13859 }
13860 else if (kind == PyUnicode_2BYTE_KIND) {
13861 char_size = 2;
13862 if (sizeof(wchar_t) == 2)
13863 share_wstr = 1;
13864 }
13865 else {
13866 assert(kind == PyUnicode_4BYTE_KIND);
13867 char_size = 4;
13868 if (sizeof(wchar_t) == 4)
13869 share_wstr = 1;
13870 }
13871
13872 /* Ensure we won't overflow the length. */
13873 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13874 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013875 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013876 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013877 data = PyObject_MALLOC((length + 1) * char_size);
13878 if (data == NULL) {
13879 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013880 goto onError;
13881 }
13882
Victor Stinnerc3c74152011-10-02 20:39:55 +020013883 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013884 if (share_utf8) {
13885 _PyUnicode_UTF8_LENGTH(self) = length;
13886 _PyUnicode_UTF8(self) = data;
13887 }
13888 if (share_wstr) {
13889 _PyUnicode_WSTR_LENGTH(self) = length;
13890 _PyUnicode_WSTR(self) = (wchar_t *)data;
13891 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013892
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013893 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013894 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013895 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013896#ifdef Py_DEBUG
13897 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13898#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013899 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013900 return (PyObject *)self;
13901
13902onError:
13903 Py_DECREF(unicode);
13904 Py_DECREF(self);
13905 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013906}
13907
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013908PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013909 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013910\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013911Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013912encoding defaults to the current default string encoding.\n\
13913errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013914
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013915static PyObject *unicode_iter(PyObject *seq);
13916
Guido van Rossumd57fd912000-03-10 22:53:23 +000013917PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013918 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013919 "str", /* tp_name */
13920 sizeof(PyUnicodeObject), /* tp_size */
13921 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013922 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013923 (destructor)unicode_dealloc, /* tp_dealloc */
13924 0, /* tp_print */
13925 0, /* tp_getattr */
13926 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013927 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013928 unicode_repr, /* tp_repr */
13929 &unicode_as_number, /* tp_as_number */
13930 &unicode_as_sequence, /* tp_as_sequence */
13931 &unicode_as_mapping, /* tp_as_mapping */
13932 (hashfunc) unicode_hash, /* tp_hash*/
13933 0, /* tp_call*/
13934 (reprfunc) unicode_str, /* tp_str */
13935 PyObject_GenericGetAttr, /* tp_getattro */
13936 0, /* tp_setattro */
13937 0, /* tp_as_buffer */
13938 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013939 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013940 unicode_doc, /* tp_doc */
13941 0, /* tp_traverse */
13942 0, /* tp_clear */
13943 PyUnicode_RichCompare, /* tp_richcompare */
13944 0, /* tp_weaklistoffset */
13945 unicode_iter, /* tp_iter */
13946 0, /* tp_iternext */
13947 unicode_methods, /* tp_methods */
13948 0, /* tp_members */
13949 0, /* tp_getset */
13950 &PyBaseObject_Type, /* tp_base */
13951 0, /* tp_dict */
13952 0, /* tp_descr_get */
13953 0, /* tp_descr_set */
13954 0, /* tp_dictoffset */
13955 0, /* tp_init */
13956 0, /* tp_alloc */
13957 unicode_new, /* tp_new */
13958 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013959};
13960
13961/* Initialize the Unicode implementation */
13962
Victor Stinner3a50e702011-10-18 21:21:00 +020013963int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013964{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013965 int i;
13966
Thomas Wouters477c8d52006-05-27 19:21:47 +000013967 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013968 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013969 0x000A, /* LINE FEED */
13970 0x000D, /* CARRIAGE RETURN */
13971 0x001C, /* FILE SEPARATOR */
13972 0x001D, /* GROUP SEPARATOR */
13973 0x001E, /* RECORD SEPARATOR */
13974 0x0085, /* NEXT LINE */
13975 0x2028, /* LINE SEPARATOR */
13976 0x2029, /* PARAGRAPH SEPARATOR */
13977 };
13978
Fred Drakee4315f52000-05-09 19:53:39 +000013979 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013980 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013981 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013982 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013983 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013984
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013985 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013986 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013987 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013988 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013989
13990 /* initialize the linebreak bloom filter */
13991 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013992 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013993 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013994
13995 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013996
13997#ifdef HAVE_MBCS
13998 winver.dwOSVersionInfoSize = sizeof(winver);
13999 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14000 PyErr_SetFromWindowsErr(0);
14001 return -1;
14002 }
14003#endif
14004 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005}
14006
14007/* Finalize the Unicode implementation */
14008
Christian Heimesa156e092008-02-16 07:38:31 +000014009int
14010PyUnicode_ClearFreeList(void)
14011{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014012 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014013}
14014
Guido van Rossumd57fd912000-03-10 22:53:23 +000014015void
Thomas Wouters78890102000-07-22 19:25:51 +000014016_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014018 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014019
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014020 Py_XDECREF(unicode_empty);
14021 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014022
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014023 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014024 if (unicode_latin1[i]) {
14025 Py_DECREF(unicode_latin1[i]);
14026 unicode_latin1[i] = NULL;
14027 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014028 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014029 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014030 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014031}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014032
Walter Dörwald16807132007-05-25 13:52:07 +000014033void
14034PyUnicode_InternInPlace(PyObject **p)
14035{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014036 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014037 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014038#ifdef Py_DEBUG
14039 assert(s != NULL);
14040 assert(_PyUnicode_CHECK(s));
14041#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014043 return;
14044#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014045 /* If it's a subclass, we don't really know what putting
14046 it in the interned dict might do. */
14047 if (!PyUnicode_CheckExact(s))
14048 return;
14049 if (PyUnicode_CHECK_INTERNED(s))
14050 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020014051 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014052 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014053 return;
14054 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014055 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014056 if (interned == NULL) {
14057 interned = PyDict_New();
14058 if (interned == NULL) {
14059 PyErr_Clear(); /* Don't leave an exception */
14060 return;
14061 }
14062 }
14063 /* It might be that the GetItem call fails even
14064 though the key is present in the dictionary,
14065 namely when this happens during a stack overflow. */
14066 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000014067 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014068 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014069
Benjamin Peterson29060642009-01-31 22:14:21 +000014070 if (t) {
14071 Py_INCREF(t);
14072 Py_DECREF(*p);
14073 *p = t;
14074 return;
14075 }
Walter Dörwald16807132007-05-25 13:52:07 +000014076
Benjamin Peterson14339b62009-01-31 16:36:08 +000014077 PyThreadState_GET()->recursion_critical = 1;
14078 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
14079 PyErr_Clear();
14080 PyThreadState_GET()->recursion_critical = 0;
14081 return;
14082 }
14083 PyThreadState_GET()->recursion_critical = 0;
14084 /* The two references in interned are not counted by refcnt.
14085 The deallocator will take care of this */
14086 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014087 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014088}
14089
14090void
14091PyUnicode_InternImmortal(PyObject **p)
14092{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 PyUnicode_InternInPlace(p);
14094 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014095 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014096 Py_INCREF(*p);
14097 }
Walter Dörwald16807132007-05-25 13:52:07 +000014098}
14099
14100PyObject *
14101PyUnicode_InternFromString(const char *cp)
14102{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014103 PyObject *s = PyUnicode_FromString(cp);
14104 if (s == NULL)
14105 return NULL;
14106 PyUnicode_InternInPlace(&s);
14107 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014108}
14109
Alexander Belopolsky40018472011-02-26 01:02:56 +000014110void
14111_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014112{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014113 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014114 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014115 Py_ssize_t i, n;
14116 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014117
Benjamin Peterson14339b62009-01-31 16:36:08 +000014118 if (interned == NULL || !PyDict_Check(interned))
14119 return;
14120 keys = PyDict_Keys(interned);
14121 if (keys == NULL || !PyList_Check(keys)) {
14122 PyErr_Clear();
14123 return;
14124 }
Walter Dörwald16807132007-05-25 13:52:07 +000014125
Benjamin Peterson14339b62009-01-31 16:36:08 +000014126 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14127 detector, interned unicode strings are not forcibly deallocated;
14128 rather, we give them their stolen references back, and then clear
14129 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014130
Benjamin Peterson14339b62009-01-31 16:36:08 +000014131 n = PyList_GET_SIZE(keys);
14132 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014133 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014134 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014135 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014136 if (PyUnicode_READY(s) == -1) {
14137 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014138 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014139 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014140 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014141 case SSTATE_NOT_INTERNED:
14142 /* XXX Shouldn't happen */
14143 break;
14144 case SSTATE_INTERNED_IMMORTAL:
14145 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014146 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 break;
14148 case SSTATE_INTERNED_MORTAL:
14149 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014150 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014151 break;
14152 default:
14153 Py_FatalError("Inconsistent interned string state.");
14154 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014155 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014156 }
14157 fprintf(stderr, "total size of all interned strings: "
14158 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14159 "mortal/immortal\n", mortal_size, immortal_size);
14160 Py_DECREF(keys);
14161 PyDict_Clear(interned);
14162 Py_DECREF(interned);
14163 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014164}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014165
14166
14167/********************* Unicode Iterator **************************/
14168
14169typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014170 PyObject_HEAD
14171 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014172 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014173} unicodeiterobject;
14174
14175static void
14176unicodeiter_dealloc(unicodeiterobject *it)
14177{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014178 _PyObject_GC_UNTRACK(it);
14179 Py_XDECREF(it->it_seq);
14180 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014181}
14182
14183static int
14184unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14185{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 Py_VISIT(it->it_seq);
14187 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014188}
14189
14190static PyObject *
14191unicodeiter_next(unicodeiterobject *it)
14192{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014193 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014194
Benjamin Peterson14339b62009-01-31 16:36:08 +000014195 assert(it != NULL);
14196 seq = it->it_seq;
14197 if (seq == NULL)
14198 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014199 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014200
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014201 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14202 int kind = PyUnicode_KIND(seq);
14203 void *data = PyUnicode_DATA(seq);
14204 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14205 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014206 if (item != NULL)
14207 ++it->it_index;
14208 return item;
14209 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014210
Benjamin Peterson14339b62009-01-31 16:36:08 +000014211 Py_DECREF(seq);
14212 it->it_seq = NULL;
14213 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014214}
14215
14216static PyObject *
14217unicodeiter_len(unicodeiterobject *it)
14218{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014219 Py_ssize_t len = 0;
14220 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014221 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014222 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014223}
14224
14225PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14226
14227static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014228 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014229 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014230 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014231};
14232
14233PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014234 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14235 "str_iterator", /* tp_name */
14236 sizeof(unicodeiterobject), /* tp_basicsize */
14237 0, /* tp_itemsize */
14238 /* methods */
14239 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14240 0, /* tp_print */
14241 0, /* tp_getattr */
14242 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014243 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014244 0, /* tp_repr */
14245 0, /* tp_as_number */
14246 0, /* tp_as_sequence */
14247 0, /* tp_as_mapping */
14248 0, /* tp_hash */
14249 0, /* tp_call */
14250 0, /* tp_str */
14251 PyObject_GenericGetAttr, /* tp_getattro */
14252 0, /* tp_setattro */
14253 0, /* tp_as_buffer */
14254 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14255 0, /* tp_doc */
14256 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14257 0, /* tp_clear */
14258 0, /* tp_richcompare */
14259 0, /* tp_weaklistoffset */
14260 PyObject_SelfIter, /* tp_iter */
14261 (iternextfunc)unicodeiter_next, /* tp_iternext */
14262 unicodeiter_methods, /* tp_methods */
14263 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014264};
14265
14266static PyObject *
14267unicode_iter(PyObject *seq)
14268{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014269 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014270
Benjamin Peterson14339b62009-01-31 16:36:08 +000014271 if (!PyUnicode_Check(seq)) {
14272 PyErr_BadInternalCall();
14273 return NULL;
14274 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014275 if (PyUnicode_READY(seq) == -1)
14276 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014277 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14278 if (it == NULL)
14279 return NULL;
14280 it->it_index = 0;
14281 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014282 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014283 _PyObject_GC_TRACK(it);
14284 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014285}
14286
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014287
14288size_t
14289Py_UNICODE_strlen(const Py_UNICODE *u)
14290{
14291 int res = 0;
14292 while(*u++)
14293 res++;
14294 return res;
14295}
14296
14297Py_UNICODE*
14298Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14299{
14300 Py_UNICODE *u = s1;
14301 while ((*u++ = *s2++));
14302 return s1;
14303}
14304
14305Py_UNICODE*
14306Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14307{
14308 Py_UNICODE *u = s1;
14309 while ((*u++ = *s2++))
14310 if (n-- == 0)
14311 break;
14312 return s1;
14313}
14314
14315Py_UNICODE*
14316Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14317{
14318 Py_UNICODE *u1 = s1;
14319 u1 += Py_UNICODE_strlen(u1);
14320 Py_UNICODE_strcpy(u1, s2);
14321 return s1;
14322}
14323
14324int
14325Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14326{
14327 while (*s1 && *s2 && *s1 == *s2)
14328 s1++, s2++;
14329 if (*s1 && *s2)
14330 return (*s1 < *s2) ? -1 : +1;
14331 if (*s1)
14332 return 1;
14333 if (*s2)
14334 return -1;
14335 return 0;
14336}
14337
14338int
14339Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14340{
14341 register Py_UNICODE u1, u2;
14342 for (; n != 0; n--) {
14343 u1 = *s1;
14344 u2 = *s2;
14345 if (u1 != u2)
14346 return (u1 < u2) ? -1 : +1;
14347 if (u1 == '\0')
14348 return 0;
14349 s1++;
14350 s2++;
14351 }
14352 return 0;
14353}
14354
14355Py_UNICODE*
14356Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14357{
14358 const Py_UNICODE *p;
14359 for (p = s; *p; p++)
14360 if (*p == c)
14361 return (Py_UNICODE*)p;
14362 return NULL;
14363}
14364
14365Py_UNICODE*
14366Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14367{
14368 const Py_UNICODE *p;
14369 p = s + Py_UNICODE_strlen(s);
14370 while (p != s) {
14371 p--;
14372 if (*p == c)
14373 return (Py_UNICODE*)p;
14374 }
14375 return NULL;
14376}
Victor Stinner331ea922010-08-10 16:37:20 +000014377
Victor Stinner71133ff2010-09-01 23:43:53 +000014378Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014379PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014380{
Victor Stinner577db2c2011-10-11 22:12:48 +020014381 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014382 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014383
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014384 if (!PyUnicode_Check(unicode)) {
14385 PyErr_BadArgument();
14386 return NULL;
14387 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014388 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014389 if (u == NULL)
14390 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014391 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014392 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014393 PyErr_NoMemory();
14394 return NULL;
14395 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014396 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014397 size *= sizeof(Py_UNICODE);
14398 copy = PyMem_Malloc(size);
14399 if (copy == NULL) {
14400 PyErr_NoMemory();
14401 return NULL;
14402 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014403 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014404 return copy;
14405}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014406
Georg Brandl66c221e2010-10-14 07:04:07 +000014407/* A _string module, to export formatter_parser and formatter_field_name_split
14408 to the string.Formatter class implemented in Python. */
14409
14410static PyMethodDef _string_methods[] = {
14411 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14412 METH_O, PyDoc_STR("split the argument as a field name")},
14413 {"formatter_parser", (PyCFunction) formatter_parser,
14414 METH_O, PyDoc_STR("parse the argument as a format string")},
14415 {NULL, NULL}
14416};
14417
14418static struct PyModuleDef _string_module = {
14419 PyModuleDef_HEAD_INIT,
14420 "_string",
14421 PyDoc_STR("string helper module"),
14422 0,
14423 _string_methods,
14424 NULL,
14425 NULL,
14426 NULL,
14427 NULL
14428};
14429
14430PyMODINIT_FUNC
14431PyInit__string(void)
14432{
14433 return PyModule_Create(&_string_module);
14434}
14435
14436
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014437#ifdef __cplusplus
14438}
14439#endif