blob: 73f79268119b09bb4302834906fb4299500c4328 [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;
Brian Curtin2787ea42011-11-02 15:09:37 -05008216 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008217
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008218 if (PyUnicode_READY(unicode) < 0)
8219 return -1;
8220 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008221 /* find all unencodable characters */
8222 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008223 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008224 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008225 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008226 val = encoding_map_lookup(ch, mapping);
8227 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 break;
8229 ++collendpos;
8230 continue;
8231 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008232
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008233 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8234 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 if (rep==NULL)
8236 return -1;
8237 else if (rep!=Py_None) {
8238 Py_DECREF(rep);
8239 break;
8240 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008241 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008242 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008243 }
8244 /* cache callback name lookup
8245 * (if not done yet, i.e. it's the first error) */
8246 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008247 if ((errors==NULL) || (!strcmp(errors, "strict")))
8248 *known_errorHandler = 1;
8249 else if (!strcmp(errors, "replace"))
8250 *known_errorHandler = 2;
8251 else if (!strcmp(errors, "ignore"))
8252 *known_errorHandler = 3;
8253 else if (!strcmp(errors, "xmlcharrefreplace"))
8254 *known_errorHandler = 4;
8255 else
8256 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008257 }
8258 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008259 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008260 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008261 return -1;
8262 case 2: /* replace */
8263 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008264 x = charmapencode_output('?', mapping, res, respos);
8265 if (x==enc_EXCEPTION) {
8266 return -1;
8267 }
8268 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008269 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 return -1;
8271 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008272 }
8273 /* fall through */
8274 case 3: /* ignore */
8275 *inpos = collendpos;
8276 break;
8277 case 4: /* xmlcharrefreplace */
8278 /* generate replacement (temporarily (mis)uses p) */
8279 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008280 char buffer[2+29+1+1];
8281 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008282 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008283 for (cp = buffer; *cp; ++cp) {
8284 x = charmapencode_output(*cp, mapping, res, respos);
8285 if (x==enc_EXCEPTION)
8286 return -1;
8287 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008288 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008289 return -1;
8290 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008291 }
8292 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008293 *inpos = collendpos;
8294 break;
8295 default:
8296 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008297 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008298 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008299 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008301 if (PyBytes_Check(repunicode)) {
8302 /* Directly copy bytes result to output. */
8303 Py_ssize_t outsize = PyBytes_Size(*res);
8304 Py_ssize_t requiredsize;
8305 repsize = PyBytes_Size(repunicode);
8306 requiredsize = *respos + repsize;
8307 if (requiredsize > outsize)
8308 /* Make room for all additional bytes. */
8309 if (charmapencode_resize(res, respos, requiredsize)) {
8310 Py_DECREF(repunicode);
8311 return -1;
8312 }
8313 memcpy(PyBytes_AsString(*res) + *respos,
8314 PyBytes_AsString(repunicode), repsize);
8315 *respos += repsize;
8316 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008317 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008318 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008319 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008320 /* generate replacement */
8321 repsize = PyUnicode_GET_SIZE(repunicode);
8322 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 x = charmapencode_output(*uni2, mapping, res, respos);
8324 if (x==enc_EXCEPTION) {
8325 return -1;
8326 }
8327 else if (x==enc_FAILED) {
8328 Py_DECREF(repunicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008329 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008330 return -1;
8331 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008332 }
8333 *inpos = newpos;
8334 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335 }
8336 return 0;
8337}
8338
Alexander Belopolsky40018472011-02-26 01:02:56 +00008339PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008340_PyUnicode_EncodeCharmap(PyObject *unicode,
8341 PyObject *mapping,
8342 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 /* output object */
8345 PyObject *res = NULL;
8346 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008347 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008348 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008349 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008350 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008351 PyObject *errorHandler = NULL;
8352 PyObject *exc = NULL;
8353 /* the following variable is used for caching string comparisons
8354 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8355 * 3=ignore, 4=xmlcharrefreplace */
8356 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008357
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008358 if (PyUnicode_READY(unicode) < 0)
8359 return NULL;
8360 size = PyUnicode_GET_LENGTH(unicode);
8361
Guido van Rossumd57fd912000-03-10 22:53:23 +00008362 /* Default to Latin-1 */
8363 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008364 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008365
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008366 /* allocate enough for a simple encoding without
8367 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008368 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 if (res == NULL)
8370 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008371 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008373
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008375 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008377 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008378 if (x==enc_EXCEPTION) /* error */
8379 goto onError;
8380 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008381 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 &exc,
8383 &known_errorHandler, &errorHandler, errors,
8384 &res, &respos)) {
8385 goto onError;
8386 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008387 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008388 else
8389 /* done with this character => adjust input position */
8390 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008391 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008392
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008393 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008394 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008395 if (_PyBytes_Resize(&res, respos) < 0)
8396 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008397
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008398 Py_XDECREF(exc);
8399 Py_XDECREF(errorHandler);
8400 return res;
8401
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 Py_XDECREF(res);
8404 Py_XDECREF(exc);
8405 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008406 return NULL;
8407}
8408
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008409/* Deprecated */
8410PyObject *
8411PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8412 Py_ssize_t size,
8413 PyObject *mapping,
8414 const char *errors)
8415{
8416 PyObject *result;
8417 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8418 if (unicode == NULL)
8419 return NULL;
8420 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8421 Py_DECREF(unicode);
8422 return NULL;
8423}
8424
Alexander Belopolsky40018472011-02-26 01:02:56 +00008425PyObject *
8426PyUnicode_AsCharmapString(PyObject *unicode,
8427 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008428{
8429 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 PyErr_BadArgument();
8431 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008432 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008433 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008434}
8435
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008437static void
8438make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008440 Py_ssize_t startpos, Py_ssize_t endpos,
8441 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008442{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008443 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008444 *exceptionObject = _PyUnicodeTranslateError_Create(
8445 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008446 }
8447 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008448 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8449 goto onError;
8450 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8451 goto onError;
8452 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8453 goto onError;
8454 return;
8455 onError:
8456 Py_DECREF(*exceptionObject);
8457 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008458 }
8459}
8460
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008461/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008462static void
8463raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008465 Py_ssize_t startpos, Py_ssize_t endpos,
8466 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467{
8468 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008469 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008471 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472}
8473
8474/* error handling callback helper:
8475 build arguments, call the callback and check the arguments,
8476 put the result into newpos and return the replacement string, which
8477 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008478static PyObject *
8479unicode_translate_call_errorhandler(const char *errors,
8480 PyObject **errorHandler,
8481 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008482 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008483 Py_ssize_t startpos, Py_ssize_t endpos,
8484 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008485{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008486 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008488 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489 PyObject *restuple;
8490 PyObject *resunicode;
8491
8492 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 }
8497
8498 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008502
8503 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008505 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008507 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008508 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 Py_DECREF(restuple);
8510 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 }
8512 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008513 &resunicode, &i_newpos)) {
8514 Py_DECREF(restuple);
8515 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008516 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008517 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008518 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008519 else
8520 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008521 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008522 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8523 Py_DECREF(restuple);
8524 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008525 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526 Py_INCREF(resunicode);
8527 Py_DECREF(restuple);
8528 return resunicode;
8529}
8530
8531/* Lookup the character ch in the mapping and put the result in result,
8532 which must be decrefed by the caller.
8533 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008534static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008535charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008536{
Christian Heimes217cfd12007-12-02 14:31:20 +00008537 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 PyObject *x;
8539
8540 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008541 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008542 x = PyObject_GetItem(mapping, w);
8543 Py_DECREF(w);
8544 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008545 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8546 /* No mapping found means: use 1:1 mapping. */
8547 PyErr_Clear();
8548 *result = NULL;
8549 return 0;
8550 } else
8551 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008552 }
8553 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 *result = x;
8555 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008556 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008557 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 long value = PyLong_AS_LONG(x);
8559 long max = PyUnicode_GetMax();
8560 if (value < 0 || value > max) {
8561 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008562 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008563 Py_DECREF(x);
8564 return -1;
8565 }
8566 *result = x;
8567 return 0;
8568 }
8569 else if (PyUnicode_Check(x)) {
8570 *result = x;
8571 return 0;
8572 }
8573 else {
8574 /* wrong return value */
8575 PyErr_SetString(PyExc_TypeError,
8576 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008577 Py_DECREF(x);
8578 return -1;
8579 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580}
8581/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008582 if not reallocate and adjust various state variables.
8583 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008584static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008586 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008587{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008588 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008589 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 /* exponentially overallocate to minimize reallocations */
8591 if (requiredsize < 2 * oldsize)
8592 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8594 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008597 }
8598 return 0;
8599}
8600/* lookup the character, put the result in the output string and adjust
8601 various state variables. Return a new reference to the object that
8602 was put in the output buffer in *result, or Py_None, if the mapping was
8603 undefined (in which case no character was written).
8604 The called must decref result.
8605 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008606static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8608 PyObject *mapping, Py_UCS4 **output,
8609 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008610 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008612 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8613 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008615 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008617 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 }
8619 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008621 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 }
8625 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 Py_ssize_t repsize;
8627 if (PyUnicode_READY(*res) == -1)
8628 return -1;
8629 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 if (repsize==1) {
8631 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008633 }
8634 else if (repsize!=0) {
8635 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 Py_ssize_t requiredsize = *opos +
8637 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008638 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008639 Py_ssize_t i;
8640 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008641 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 for(i = 0; i < repsize; i++)
8643 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008645 }
8646 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008647 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008648 return 0;
8649}
8650
Alexander Belopolsky40018472011-02-26 01:02:56 +00008651PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652_PyUnicode_TranslateCharmap(PyObject *input,
8653 PyObject *mapping,
8654 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008655{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008656 /* input object */
8657 char *idata;
8658 Py_ssize_t size, i;
8659 int kind;
8660 /* output buffer */
8661 Py_UCS4 *output = NULL;
8662 Py_ssize_t osize;
8663 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008664 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008666 char *reason = "character maps to <undefined>";
8667 PyObject *errorHandler = NULL;
8668 PyObject *exc = NULL;
8669 /* the following variable is used for caching string comparisons
8670 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8671 * 3=ignore, 4=xmlcharrefreplace */
8672 int known_errorHandler = -1;
8673
Guido van Rossumd57fd912000-03-10 22:53:23 +00008674 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 PyErr_BadArgument();
8676 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008679 if (PyUnicode_READY(input) == -1)
8680 return NULL;
8681 idata = (char*)PyUnicode_DATA(input);
8682 kind = PyUnicode_KIND(input);
8683 size = PyUnicode_GET_LENGTH(input);
8684 i = 0;
8685
8686 if (size == 0) {
8687 Py_INCREF(input);
8688 return input;
8689 }
8690
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008691 /* allocate enough for a simple 1:1 translation without
8692 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 osize = size;
8694 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8695 opos = 0;
8696 if (output == NULL) {
8697 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008698 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008701 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 /* try to encode it */
8703 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 if (charmaptranslate_output(input, i, mapping,
8705 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008706 Py_XDECREF(x);
8707 goto onError;
8708 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008709 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008712 else { /* untranslatable character */
8713 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8714 Py_ssize_t repsize;
8715 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008717 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008718 Py_ssize_t collstart = i;
8719 Py_ssize_t collend = i+1;
8720 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008721
Benjamin Peterson29060642009-01-31 22:14:21 +00008722 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008723 while (collend < size) {
8724 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008725 goto onError;
8726 Py_XDECREF(x);
8727 if (x!=Py_None)
8728 break;
8729 ++collend;
8730 }
8731 /* cache callback name lookup
8732 * (if not done yet, i.e. it's the first error) */
8733 if (known_errorHandler==-1) {
8734 if ((errors==NULL) || (!strcmp(errors, "strict")))
8735 known_errorHandler = 1;
8736 else if (!strcmp(errors, "replace"))
8737 known_errorHandler = 2;
8738 else if (!strcmp(errors, "ignore"))
8739 known_errorHandler = 3;
8740 else if (!strcmp(errors, "xmlcharrefreplace"))
8741 known_errorHandler = 4;
8742 else
8743 known_errorHandler = 0;
8744 }
8745 switch (known_errorHandler) {
8746 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008747 raise_translate_exception(&exc, input, collstart,
8748 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008749 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 case 2: /* replace */
8751 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752 for (coll = collstart; coll<collend; coll++)
8753 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 /* fall through */
8755 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008757 break;
8758 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008759 /* generate replacement (temporarily (mis)uses i) */
8760 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008761 char buffer[2+29+1+1];
8762 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8764 if (charmaptranslate_makespace(&output, &osize,
8765 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008766 goto onError;
8767 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008768 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008769 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008770 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008771 break;
8772 default:
8773 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008774 reason, input, &exc,
8775 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008776 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008777 goto onError;
8778 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008779 repsize = PyUnicode_GET_LENGTH(repunicode);
8780 if (charmaptranslate_makespace(&output, &osize,
8781 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008782 Py_DECREF(repunicode);
8783 goto onError;
8784 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 for (uni2 = 0; repsize-->0; ++uni2)
8786 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8787 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008788 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008789 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008790 }
8791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008792 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8793 if (!res)
8794 goto onError;
8795 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008796 Py_XDECREF(exc);
8797 Py_XDECREF(errorHandler);
8798 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008799
Benjamin Peterson29060642009-01-31 22:14:21 +00008800 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008801 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008802 Py_XDECREF(exc);
8803 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008804 return NULL;
8805}
8806
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008807/* Deprecated. Use PyUnicode_Translate instead. */
8808PyObject *
8809PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8810 Py_ssize_t size,
8811 PyObject *mapping,
8812 const char *errors)
8813{
8814 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8815 if (!unicode)
8816 return NULL;
8817 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8818}
8819
Alexander Belopolsky40018472011-02-26 01:02:56 +00008820PyObject *
8821PyUnicode_Translate(PyObject *str,
8822 PyObject *mapping,
8823 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008824{
8825 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008826
Guido van Rossumd57fd912000-03-10 22:53:23 +00008827 str = PyUnicode_FromObject(str);
8828 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008829 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008830 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008831 Py_DECREF(str);
8832 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008833
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008835 Py_XDECREF(str);
8836 return NULL;
8837}
Tim Petersced69f82003-09-16 20:30:58 +00008838
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008839static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008840fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008841{
8842 /* No need to call PyUnicode_READY(self) because this function is only
8843 called as a callback from fixup() which does it already. */
8844 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8845 const int kind = PyUnicode_KIND(self);
8846 void *data = PyUnicode_DATA(self);
8847 Py_UCS4 maxchar = 0, ch, fixed;
8848 Py_ssize_t i;
8849
8850 for (i = 0; i < len; ++i) {
8851 ch = PyUnicode_READ(kind, data, i);
8852 fixed = 0;
8853 if (ch > 127) {
8854 if (Py_UNICODE_ISSPACE(ch))
8855 fixed = ' ';
8856 else {
8857 const int decimal = Py_UNICODE_TODECIMAL(ch);
8858 if (decimal >= 0)
8859 fixed = '0' + decimal;
8860 }
8861 if (fixed != 0) {
8862 if (fixed > maxchar)
8863 maxchar = fixed;
8864 PyUnicode_WRITE(kind, data, i, fixed);
8865 }
8866 else if (ch > maxchar)
8867 maxchar = ch;
8868 }
8869 else if (ch > maxchar)
8870 maxchar = ch;
8871 }
8872
8873 return maxchar;
8874}
8875
8876PyObject *
8877_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8878{
8879 if (!PyUnicode_Check(unicode)) {
8880 PyErr_BadInternalCall();
8881 return NULL;
8882 }
8883 if (PyUnicode_READY(unicode) == -1)
8884 return NULL;
8885 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8886 /* If the string is already ASCII, just return the same string */
8887 Py_INCREF(unicode);
8888 return unicode;
8889 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008890 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008891}
8892
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008893PyObject *
8894PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8895 Py_ssize_t length)
8896{
8897 PyObject *result;
8898 Py_UNICODE *p; /* write pointer into result */
8899 Py_ssize_t i;
8900 /* Copy to a new string */
8901 result = (PyObject *)_PyUnicode_New(length);
8902 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8903 if (result == NULL)
8904 return result;
8905 p = PyUnicode_AS_UNICODE(result);
8906 /* Iterate over code points */
8907 for (i = 0; i < length; i++) {
8908 Py_UNICODE ch =s[i];
8909 if (ch > 127) {
8910 int decimal = Py_UNICODE_TODECIMAL(ch);
8911 if (decimal >= 0)
8912 p[i] = '0' + decimal;
8913 }
8914 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008915#ifndef DONT_MAKE_RESULT_READY
8916 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008917 Py_DECREF(result);
8918 return NULL;
8919 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008920#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008921 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008922 return result;
8923}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008924/* --- Decimal Encoder ---------------------------------------------------- */
8925
Alexander Belopolsky40018472011-02-26 01:02:56 +00008926int
8927PyUnicode_EncodeDecimal(Py_UNICODE *s,
8928 Py_ssize_t length,
8929 char *output,
8930 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008931{
8932 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008933 PyObject *errorHandler = NULL;
8934 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008935 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008936 const char *encoding = "decimal";
8937 const char *reason = "invalid decimal Unicode string";
8938 /* the following variable is used for caching string comparisons
8939 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8940 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008941
8942 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008943 PyErr_BadArgument();
8944 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008945 }
8946
8947 p = s;
8948 end = s + length;
8949 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008950 register Py_UNICODE ch = *p;
8951 int decimal;
8952 PyObject *repunicode;
8953 Py_ssize_t repsize;
8954 Py_ssize_t newpos;
8955 Py_UNICODE *uni2;
8956 Py_UNICODE *collstart;
8957 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008958
Benjamin Peterson29060642009-01-31 22:14:21 +00008959 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008960 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008961 ++p;
8962 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008963 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008964 decimal = Py_UNICODE_TODECIMAL(ch);
8965 if (decimal >= 0) {
8966 *output++ = '0' + decimal;
8967 ++p;
8968 continue;
8969 }
8970 if (0 < ch && ch < 256) {
8971 *output++ = (char)ch;
8972 ++p;
8973 continue;
8974 }
8975 /* All other characters are considered unencodable */
8976 collstart = p;
8977 collend = p+1;
8978 while (collend < end) {
8979 if ((0 < *collend && *collend < 256) ||
8980 !Py_UNICODE_ISSPACE(*collend) ||
8981 Py_UNICODE_TODECIMAL(*collend))
8982 break;
8983 }
8984 /* cache callback name lookup
8985 * (if not done yet, i.e. it's the first error) */
8986 if (known_errorHandler==-1) {
8987 if ((errors==NULL) || (!strcmp(errors, "strict")))
8988 known_errorHandler = 1;
8989 else if (!strcmp(errors, "replace"))
8990 known_errorHandler = 2;
8991 else if (!strcmp(errors, "ignore"))
8992 known_errorHandler = 3;
8993 else if (!strcmp(errors, "xmlcharrefreplace"))
8994 known_errorHandler = 4;
8995 else
8996 known_errorHandler = 0;
8997 }
8998 switch (known_errorHandler) {
8999 case 1: /* strict */
9000 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
9001 goto onError;
9002 case 2: /* replace */
9003 for (p = collstart; p < collend; ++p)
9004 *output++ = '?';
9005 /* fall through */
9006 case 3: /* ignore */
9007 p = collend;
9008 break;
9009 case 4: /* xmlcharrefreplace */
9010 /* generate replacement (temporarily (mis)uses p) */
9011 for (p = collstart; p < collend; ++p)
9012 output += sprintf(output, "&#%d;", (int)*p);
9013 p = collend;
9014 break;
9015 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009016 unicode = PyUnicode_FromUnicode(s, length);
9017 if (unicode == NULL)
9018 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009019 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009020 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009021 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009022 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00009023 if (repunicode == NULL)
9024 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009025 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00009026 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009027 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
9028 Py_DECREF(repunicode);
9029 goto onError;
9030 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009031 /* generate replacement */
9032 repsize = PyUnicode_GET_SIZE(repunicode);
9033 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
9034 Py_UNICODE ch = *uni2;
9035 if (Py_UNICODE_ISSPACE(ch))
9036 *output++ = ' ';
9037 else {
9038 decimal = Py_UNICODE_TODECIMAL(ch);
9039 if (decimal >= 0)
9040 *output++ = '0' + decimal;
9041 else if (0 < ch && ch < 256)
9042 *output++ = (char)ch;
9043 else {
9044 Py_DECREF(repunicode);
9045 raise_encode_exception(&exc, encoding,
9046 s, length, collstart-s, collend-s, reason);
9047 goto onError;
9048 }
9049 }
9050 }
9051 p = s + newpos;
9052 Py_DECREF(repunicode);
9053 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00009054 }
9055 /* 0-terminate the output string */
9056 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009057 Py_XDECREF(exc);
9058 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009059 return 0;
9060
Benjamin Peterson29060642009-01-31 22:14:21 +00009061 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009062 Py_XDECREF(exc);
9063 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009064 return -1;
9065}
9066
Guido van Rossumd57fd912000-03-10 22:53:23 +00009067/* --- Helpers ------------------------------------------------------------ */
9068
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009070any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009071 Py_ssize_t start,
9072 Py_ssize_t end)
9073{
9074 int kind1, kind2, kind;
9075 void *buf1, *buf2;
9076 Py_ssize_t len1, len2, result;
9077
9078 kind1 = PyUnicode_KIND(s1);
9079 kind2 = PyUnicode_KIND(s2);
9080 kind = kind1 > kind2 ? kind1 : kind2;
9081 buf1 = PyUnicode_DATA(s1);
9082 buf2 = PyUnicode_DATA(s2);
9083 if (kind1 != kind)
9084 buf1 = _PyUnicode_AsKind(s1, kind);
9085 if (!buf1)
9086 return -2;
9087 if (kind2 != kind)
9088 buf2 = _PyUnicode_AsKind(s2, kind);
9089 if (!buf2) {
9090 if (kind1 != kind) PyMem_Free(buf1);
9091 return -2;
9092 }
9093 len1 = PyUnicode_GET_LENGTH(s1);
9094 len2 = PyUnicode_GET_LENGTH(s2);
9095
Victor Stinner794d5672011-10-10 03:21:36 +02009096 if (direction > 0) {
9097 switch(kind) {
9098 case PyUnicode_1BYTE_KIND:
9099 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9100 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9101 else
9102 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9103 break;
9104 case PyUnicode_2BYTE_KIND:
9105 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9106 break;
9107 case PyUnicode_4BYTE_KIND:
9108 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9109 break;
9110 default:
9111 assert(0); result = -2;
9112 }
9113 }
9114 else {
9115 switch(kind) {
9116 case PyUnicode_1BYTE_KIND:
9117 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9118 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9119 else
9120 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9121 break;
9122 case PyUnicode_2BYTE_KIND:
9123 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9124 break;
9125 case PyUnicode_4BYTE_KIND:
9126 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9127 break;
9128 default:
9129 assert(0); result = -2;
9130 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009131 }
9132
9133 if (kind1 != kind)
9134 PyMem_Free(buf1);
9135 if (kind2 != kind)
9136 PyMem_Free(buf2);
9137
9138 return result;
9139}
9140
9141Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009142_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009143 Py_ssize_t n_buffer,
9144 void *digits, Py_ssize_t n_digits,
9145 Py_ssize_t min_width,
9146 const char *grouping,
9147 const char *thousands_sep)
9148{
9149 switch(kind) {
9150 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009151 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9152 return _PyUnicode_ascii_InsertThousandsGrouping(
9153 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9154 min_width, grouping, thousands_sep);
9155 else
9156 return _PyUnicode_ucs1_InsertThousandsGrouping(
9157 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9158 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 case PyUnicode_2BYTE_KIND:
9160 return _PyUnicode_ucs2_InsertThousandsGrouping(
9161 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9162 min_width, grouping, thousands_sep);
9163 case PyUnicode_4BYTE_KIND:
9164 return _PyUnicode_ucs4_InsertThousandsGrouping(
9165 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9166 min_width, grouping, thousands_sep);
9167 }
9168 assert(0);
9169 return -1;
9170}
9171
9172
Thomas Wouters477c8d52006-05-27 19:21:47 +00009173/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009174#define ADJUST_INDICES(start, end, len) \
9175 if (end > len) \
9176 end = len; \
9177 else if (end < 0) { \
9178 end += len; \
9179 if (end < 0) \
9180 end = 0; \
9181 } \
9182 if (start < 0) { \
9183 start += len; \
9184 if (start < 0) \
9185 start = 0; \
9186 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009187
Alexander Belopolsky40018472011-02-26 01:02:56 +00009188Py_ssize_t
9189PyUnicode_Count(PyObject *str,
9190 PyObject *substr,
9191 Py_ssize_t start,
9192 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009193{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009194 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009195 PyObject* str_obj;
9196 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 int kind1, kind2, kind;
9198 void *buf1 = NULL, *buf2 = NULL;
9199 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009200
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009201 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009202 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009203 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009204 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009205 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009206 Py_DECREF(str_obj);
9207 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009208 }
Tim Petersced69f82003-09-16 20:30:58 +00009209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 kind1 = PyUnicode_KIND(str_obj);
9211 kind2 = PyUnicode_KIND(sub_obj);
9212 kind = kind1 > kind2 ? kind1 : kind2;
9213 buf1 = PyUnicode_DATA(str_obj);
9214 if (kind1 != kind)
9215 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
9216 if (!buf1)
9217 goto onError;
9218 buf2 = PyUnicode_DATA(sub_obj);
9219 if (kind2 != kind)
9220 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
9221 if (!buf2)
9222 goto onError;
9223 len1 = PyUnicode_GET_LENGTH(str_obj);
9224 len2 = PyUnicode_GET_LENGTH(sub_obj);
9225
9226 ADJUST_INDICES(start, end, len1);
9227 switch(kind) {
9228 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009229 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9230 result = asciilib_count(
9231 ((Py_UCS1*)buf1) + start, end - start,
9232 buf2, len2, PY_SSIZE_T_MAX
9233 );
9234 else
9235 result = ucs1lib_count(
9236 ((Py_UCS1*)buf1) + start, end - start,
9237 buf2, len2, PY_SSIZE_T_MAX
9238 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009239 break;
9240 case PyUnicode_2BYTE_KIND:
9241 result = ucs2lib_count(
9242 ((Py_UCS2*)buf1) + start, end - start,
9243 buf2, len2, PY_SSIZE_T_MAX
9244 );
9245 break;
9246 case PyUnicode_4BYTE_KIND:
9247 result = ucs4lib_count(
9248 ((Py_UCS4*)buf1) + start, end - start,
9249 buf2, len2, PY_SSIZE_T_MAX
9250 );
9251 break;
9252 default:
9253 assert(0); result = 0;
9254 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009255
9256 Py_DECREF(sub_obj);
9257 Py_DECREF(str_obj);
9258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009259 if (kind1 != kind)
9260 PyMem_Free(buf1);
9261 if (kind2 != kind)
9262 PyMem_Free(buf2);
9263
Guido van Rossumd57fd912000-03-10 22:53:23 +00009264 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009265 onError:
9266 Py_DECREF(sub_obj);
9267 Py_DECREF(str_obj);
9268 if (kind1 != kind && buf1)
9269 PyMem_Free(buf1);
9270 if (kind2 != kind && buf2)
9271 PyMem_Free(buf2);
9272 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009273}
9274
Alexander Belopolsky40018472011-02-26 01:02:56 +00009275Py_ssize_t
9276PyUnicode_Find(PyObject *str,
9277 PyObject *sub,
9278 Py_ssize_t start,
9279 Py_ssize_t end,
9280 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009281{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009282 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009283
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009286 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009287 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009288 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009289 Py_DECREF(str);
9290 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291 }
Tim Petersced69f82003-09-16 20:30:58 +00009292
Victor Stinner794d5672011-10-10 03:21:36 +02009293 result = any_find_slice(direction,
9294 str, sub, start, end
9295 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009296
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009298 Py_DECREF(sub);
9299
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300 return result;
9301}
9302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303Py_ssize_t
9304PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9305 Py_ssize_t start, Py_ssize_t end,
9306 int direction)
9307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009309 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009310 if (PyUnicode_READY(str) == -1)
9311 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009312 if (start < 0 || end < 0) {
9313 PyErr_SetString(PyExc_IndexError, "string index out of range");
9314 return -2;
9315 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009316 if (end > PyUnicode_GET_LENGTH(str))
9317 end = PyUnicode_GET_LENGTH(str);
9318 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009319 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9320 kind, end-start, ch, direction);
9321 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009322 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009323 else
9324 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009325}
9326
Alexander Belopolsky40018472011-02-26 01:02:56 +00009327static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009328tailmatch(PyObject *self,
9329 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009330 Py_ssize_t start,
9331 Py_ssize_t end,
9332 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009333{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009334 int kind_self;
9335 int kind_sub;
9336 void *data_self;
9337 void *data_sub;
9338 Py_ssize_t offset;
9339 Py_ssize_t i;
9340 Py_ssize_t end_sub;
9341
9342 if (PyUnicode_READY(self) == -1 ||
9343 PyUnicode_READY(substring) == -1)
9344 return 0;
9345
9346 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347 return 1;
9348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9350 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009351 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009352 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009354 kind_self = PyUnicode_KIND(self);
9355 data_self = PyUnicode_DATA(self);
9356 kind_sub = PyUnicode_KIND(substring);
9357 data_sub = PyUnicode_DATA(substring);
9358 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9359
9360 if (direction > 0)
9361 offset = end;
9362 else
9363 offset = start;
9364
9365 if (PyUnicode_READ(kind_self, data_self, offset) ==
9366 PyUnicode_READ(kind_sub, data_sub, 0) &&
9367 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9368 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9369 /* If both are of the same kind, memcmp is sufficient */
9370 if (kind_self == kind_sub) {
9371 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009372 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009373 data_sub,
9374 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009375 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009376 }
9377 /* otherwise we have to compare each character by first accesing it */
9378 else {
9379 /* We do not need to compare 0 and len(substring)-1 because
9380 the if statement above ensured already that they are equal
9381 when we end up here. */
9382 // TODO: honor direction and do a forward or backwards search
9383 for (i = 1; i < end_sub; ++i) {
9384 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9385 PyUnicode_READ(kind_sub, data_sub, i))
9386 return 0;
9387 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009388 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009389 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009390 }
9391
9392 return 0;
9393}
9394
Alexander Belopolsky40018472011-02-26 01:02:56 +00009395Py_ssize_t
9396PyUnicode_Tailmatch(PyObject *str,
9397 PyObject *substr,
9398 Py_ssize_t start,
9399 Py_ssize_t end,
9400 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009401{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009402 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009403
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404 str = PyUnicode_FromObject(str);
9405 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009406 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009407 substr = PyUnicode_FromObject(substr);
9408 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009409 Py_DECREF(str);
9410 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009411 }
Tim Petersced69f82003-09-16 20:30:58 +00009412
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009413 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009414 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009415 Py_DECREF(str);
9416 Py_DECREF(substr);
9417 return result;
9418}
9419
Guido van Rossumd57fd912000-03-10 22:53:23 +00009420/* Apply fixfct filter to the Unicode object self and return a
9421 reference to the modified object */
9422
Alexander Belopolsky40018472011-02-26 01:02:56 +00009423static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009424fixup(PyObject *self,
9425 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009426{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009427 PyObject *u;
9428 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009430 if (PyUnicode_READY(self) == -1)
9431 return NULL;
9432 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9433 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9434 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009435 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009436 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009437
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009439 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 /* fix functions return the new maximum character in a string,
9442 if the kind of the resulting unicode object does not change,
9443 everything is fine. Otherwise we need to change the string kind
9444 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009445 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 if (maxchar_new == 0)
9447 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9448 else if (maxchar_new <= 127)
9449 maxchar_new = 127;
9450 else if (maxchar_new <= 255)
9451 maxchar_new = 255;
9452 else if (maxchar_new <= 65535)
9453 maxchar_new = 65535;
9454 else
9455 maxchar_new = 1114111; /* 0x10ffff */
9456
9457 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009458 /* fixfct should return TRUE if it modified the buffer. If
9459 FALSE, return a reference to the original buffer instead
9460 (to save space, not time) */
9461 Py_INCREF(self);
9462 Py_DECREF(u);
9463 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 else if (maxchar_new == maxchar_old) {
9466 return u;
9467 }
9468 else {
9469 /* In case the maximum character changed, we need to
9470 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009471 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472 if (v == NULL) {
9473 Py_DECREF(u);
9474 return NULL;
9475 }
9476 if (maxchar_new > maxchar_old) {
9477 /* If the maxchar increased so that the kind changed, not all
9478 characters are representable anymore and we need to fix the
9479 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009480 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009481 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009482 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9483 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009484 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009485 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009486 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487
9488 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009489 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 return v;
9491 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492}
9493
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009494static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009495fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009496{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009497 /* No need to call PyUnicode_READY(self) because this function is only
9498 called as a callback from fixup() which does it already. */
9499 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9500 const int kind = PyUnicode_KIND(self);
9501 void *data = PyUnicode_DATA(self);
9502 int touched = 0;
9503 Py_UCS4 maxchar = 0;
9504 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009505
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 for (i = 0; i < len; ++i) {
9507 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9508 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9509 if (up != ch) {
9510 if (up > maxchar)
9511 maxchar = up;
9512 PyUnicode_WRITE(kind, data, i, up);
9513 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009514 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515 else if (ch > maxchar)
9516 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009517 }
9518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009519 if (touched)
9520 return maxchar;
9521 else
9522 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009523}
9524
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009526fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009527{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009528 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9529 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9530 const int kind = PyUnicode_KIND(self);
9531 void *data = PyUnicode_DATA(self);
9532 int touched = 0;
9533 Py_UCS4 maxchar = 0;
9534 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 for(i = 0; i < len; ++i) {
9537 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9538 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9539 if (lo != ch) {
9540 if (lo > maxchar)
9541 maxchar = lo;
9542 PyUnicode_WRITE(kind, data, i, lo);
9543 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009544 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 else if (ch > maxchar)
9546 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547 }
9548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009549 if (touched)
9550 return maxchar;
9551 else
9552 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009553}
9554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009555static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009556fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009558 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9559 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9560 const int kind = PyUnicode_KIND(self);
9561 void *data = PyUnicode_DATA(self);
9562 int touched = 0;
9563 Py_UCS4 maxchar = 0;
9564 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009566 for(i = 0; i < len; ++i) {
9567 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9568 Py_UCS4 nu = 0;
9569
9570 if (Py_UNICODE_ISUPPER(ch))
9571 nu = Py_UNICODE_TOLOWER(ch);
9572 else if (Py_UNICODE_ISLOWER(ch))
9573 nu = Py_UNICODE_TOUPPER(ch);
9574
9575 if (nu != 0) {
9576 if (nu > maxchar)
9577 maxchar = nu;
9578 PyUnicode_WRITE(kind, data, i, nu);
9579 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009580 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009581 else if (ch > maxchar)
9582 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009583 }
9584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 if (touched)
9586 return maxchar;
9587 else
9588 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009589}
9590
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009592fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009593{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009594 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9595 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9596 const int kind = PyUnicode_KIND(self);
9597 void *data = PyUnicode_DATA(self);
9598 int touched = 0;
9599 Py_UCS4 maxchar = 0;
9600 Py_ssize_t i = 0;
9601 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009602
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009603 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009604 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605
9606 ch = PyUnicode_READ(kind, data, i);
9607 if (!Py_UNICODE_ISUPPER(ch)) {
9608 maxchar = Py_UNICODE_TOUPPER(ch);
9609 PyUnicode_WRITE(kind, data, i, maxchar);
9610 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009612 ++i;
9613 for(; i < len; ++i) {
9614 ch = PyUnicode_READ(kind, data, i);
9615 if (!Py_UNICODE_ISLOWER(ch)) {
9616 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9617 if (lo > maxchar)
9618 maxchar = lo;
9619 PyUnicode_WRITE(kind, data, i, lo);
9620 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009621 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009622 else if (ch > maxchar)
9623 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009624 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625
9626 if (touched)
9627 return maxchar;
9628 else
9629 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009630}
9631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009632static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009633fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009635 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9636 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9637 const int kind = PyUnicode_KIND(self);
9638 void *data = PyUnicode_DATA(self);
9639 Py_UCS4 maxchar = 0;
9640 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009641 int previous_is_cased;
9642
9643 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009644 if (len == 1) {
9645 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9646 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9647 if (ti != ch) {
9648 PyUnicode_WRITE(kind, data, i, ti);
9649 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009650 }
9651 else
9652 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009653 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009654 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009655 for(; i < len; ++i) {
9656 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9657 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009658
Benjamin Peterson29060642009-01-31 22:14:21 +00009659 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009660 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009661 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009662 nu = Py_UNICODE_TOTITLE(ch);
9663
9664 if (nu > maxchar)
9665 maxchar = nu;
9666 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009667
Benjamin Peterson29060642009-01-31 22:14:21 +00009668 if (Py_UNICODE_ISLOWER(ch) ||
9669 Py_UNICODE_ISUPPER(ch) ||
9670 Py_UNICODE_ISTITLE(ch))
9671 previous_is_cased = 1;
9672 else
9673 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009674 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009675 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009676}
9677
Tim Peters8ce9f162004-08-27 01:49:32 +00009678PyObject *
9679PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009680{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009681 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009682 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009683 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009684 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009685 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9686 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009687 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009688 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009689 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009690 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009691 int use_memcpy;
9692 unsigned char *res_data = NULL, *sep_data = NULL;
9693 PyObject *last_obj;
9694 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009695
Tim Peters05eba1f2004-08-27 21:32:02 +00009696 fseq = PySequence_Fast(seq, "");
9697 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009698 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009699 }
9700
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009701 /* NOTE: the following code can't call back into Python code,
9702 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009703 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009704
Tim Peters05eba1f2004-08-27 21:32:02 +00009705 seqlen = PySequence_Fast_GET_SIZE(fseq);
9706 /* If empty sequence, return u"". */
9707 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009708 Py_DECREF(fseq);
9709 Py_INCREF(unicode_empty);
9710 res = unicode_empty;
9711 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009712 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009713
Tim Peters05eba1f2004-08-27 21:32:02 +00009714 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009715 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009716 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009717 if (seqlen == 1) {
9718 if (PyUnicode_CheckExact(items[0])) {
9719 res = items[0];
9720 Py_INCREF(res);
9721 Py_DECREF(fseq);
9722 return res;
9723 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009724 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009725 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009726 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009727 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009728 /* Set up sep and seplen */
9729 if (separator == NULL) {
9730 /* fall back to a blank space separator */
9731 sep = PyUnicode_FromOrdinal(' ');
9732 if (!sep)
9733 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009734 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009735 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009736 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009737 else {
9738 if (!PyUnicode_Check(separator)) {
9739 PyErr_Format(PyExc_TypeError,
9740 "separator: expected str instance,"
9741 " %.80s found",
9742 Py_TYPE(separator)->tp_name);
9743 goto onError;
9744 }
9745 if (PyUnicode_READY(separator))
9746 goto onError;
9747 sep = separator;
9748 seplen = PyUnicode_GET_LENGTH(separator);
9749 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9750 /* inc refcount to keep this code path symmetric with the
9751 above case of a blank separator */
9752 Py_INCREF(sep);
9753 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009754 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009755 }
9756
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009757 /* There are at least two things to join, or else we have a subclass
9758 * of str in the sequence.
9759 * Do a pre-pass to figure out the total amount of space we'll
9760 * need (sz), and see whether all argument are strings.
9761 */
9762 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009763#ifdef Py_DEBUG
9764 use_memcpy = 0;
9765#else
9766 use_memcpy = 1;
9767#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009768 for (i = 0; i < seqlen; i++) {
9769 const Py_ssize_t old_sz = sz;
9770 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009771 if (!PyUnicode_Check(item)) {
9772 PyErr_Format(PyExc_TypeError,
9773 "sequence item %zd: expected str instance,"
9774 " %.80s found",
9775 i, Py_TYPE(item)->tp_name);
9776 goto onError;
9777 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009778 if (PyUnicode_READY(item) == -1)
9779 goto onError;
9780 sz += PyUnicode_GET_LENGTH(item);
9781 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009782 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009783 if (i != 0)
9784 sz += seplen;
9785 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9786 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009787 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009788 goto onError;
9789 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009790 if (use_memcpy && last_obj != NULL) {
9791 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9792 use_memcpy = 0;
9793 }
9794 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009795 }
Tim Petersced69f82003-09-16 20:30:58 +00009796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009798 if (res == NULL)
9799 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009800
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009801 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009802#ifdef Py_DEBUG
9803 use_memcpy = 0;
9804#else
9805 if (use_memcpy) {
9806 res_data = PyUnicode_1BYTE_DATA(res);
9807 kind = PyUnicode_KIND(res);
9808 if (seplen != 0)
9809 sep_data = PyUnicode_1BYTE_DATA(sep);
9810 }
9811#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009813 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009814 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009815 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009816 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009817 if (use_memcpy) {
9818 Py_MEMCPY(res_data,
9819 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009820 kind * seplen);
9821 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009822 }
9823 else {
9824 copy_characters(res, res_offset, sep, 0, seplen);
9825 res_offset += seplen;
9826 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009827 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009828 itemlen = PyUnicode_GET_LENGTH(item);
9829 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009830 if (use_memcpy) {
9831 Py_MEMCPY(res_data,
9832 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009833 kind * itemlen);
9834 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009835 }
9836 else {
9837 copy_characters(res, res_offset, item, 0, itemlen);
9838 res_offset += itemlen;
9839 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009840 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009841 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009842 if (use_memcpy)
9843 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009844 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009845 else
9846 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009847
Tim Peters05eba1f2004-08-27 21:32:02 +00009848 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009849 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009850 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009852
Benjamin Peterson29060642009-01-31 22:14:21 +00009853 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009854 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009855 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009856 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857 return NULL;
9858}
9859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860#define FILL(kind, data, value, start, length) \
9861 do { \
9862 Py_ssize_t i_ = 0; \
9863 assert(kind != PyUnicode_WCHAR_KIND); \
9864 switch ((kind)) { \
9865 case PyUnicode_1BYTE_KIND: { \
9866 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9867 memset(to_, (unsigned char)value, length); \
9868 break; \
9869 } \
9870 case PyUnicode_2BYTE_KIND: { \
9871 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9872 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9873 break; \
9874 } \
9875 default: { \
9876 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9877 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9878 break; \
9879 } \
9880 } \
9881 } while (0)
9882
Victor Stinner9310abb2011-10-05 00:59:23 +02009883static PyObject *
9884pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009885 Py_ssize_t left,
9886 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009887 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 PyObject *u;
9890 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009891 int kind;
9892 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009893
9894 if (left < 0)
9895 left = 0;
9896 if (right < 0)
9897 right = 0;
9898
Tim Peters7a29bd52001-09-12 03:03:31 +00009899 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009900 Py_INCREF(self);
9901 return self;
9902 }
9903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009904 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9905 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009906 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9907 return NULL;
9908 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009909 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9910 if (fill > maxchar)
9911 maxchar = fill;
9912 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009913 if (!u)
9914 return NULL;
9915
9916 kind = PyUnicode_KIND(u);
9917 data = PyUnicode_DATA(u);
9918 if (left)
9919 FILL(kind, data, fill, 0, left);
9920 if (right)
9921 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009922 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009923 assert(_PyUnicode_CheckConsistency(u, 1));
9924 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009925}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009926#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927
Alexander Belopolsky40018472011-02-26 01:02:56 +00009928PyObject *
9929PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009930{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009931 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009932
9933 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009935 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009937 switch(PyUnicode_KIND(string)) {
9938 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009939 if (PyUnicode_IS_ASCII(string))
9940 list = asciilib_splitlines(
9941 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9942 PyUnicode_GET_LENGTH(string), keepends);
9943 else
9944 list = ucs1lib_splitlines(
9945 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9946 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009947 break;
9948 case PyUnicode_2BYTE_KIND:
9949 list = ucs2lib_splitlines(
9950 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9951 PyUnicode_GET_LENGTH(string), keepends);
9952 break;
9953 case PyUnicode_4BYTE_KIND:
9954 list = ucs4lib_splitlines(
9955 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9956 PyUnicode_GET_LENGTH(string), keepends);
9957 break;
9958 default:
9959 assert(0);
9960 list = 0;
9961 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009962 Py_DECREF(string);
9963 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009964}
9965
Alexander Belopolsky40018472011-02-26 01:02:56 +00009966static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009967split(PyObject *self,
9968 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009969 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009970{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 int kind1, kind2, kind;
9972 void *buf1, *buf2;
9973 Py_ssize_t len1, len2;
9974 PyObject* out;
9975
Guido van Rossumd57fd912000-03-10 22:53:23 +00009976 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009977 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009978
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009979 if (PyUnicode_READY(self) == -1)
9980 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009981
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009982 if (substring == NULL)
9983 switch(PyUnicode_KIND(self)) {
9984 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009985 if (PyUnicode_IS_ASCII(self))
9986 return asciilib_split_whitespace(
9987 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9988 PyUnicode_GET_LENGTH(self), maxcount
9989 );
9990 else
9991 return ucs1lib_split_whitespace(
9992 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9993 PyUnicode_GET_LENGTH(self), maxcount
9994 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 case PyUnicode_2BYTE_KIND:
9996 return ucs2lib_split_whitespace(
9997 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9998 PyUnicode_GET_LENGTH(self), maxcount
9999 );
10000 case PyUnicode_4BYTE_KIND:
10001 return ucs4lib_split_whitespace(
10002 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10003 PyUnicode_GET_LENGTH(self), maxcount
10004 );
10005 default:
10006 assert(0);
10007 return NULL;
10008 }
10009
10010 if (PyUnicode_READY(substring) == -1)
10011 return NULL;
10012
10013 kind1 = PyUnicode_KIND(self);
10014 kind2 = PyUnicode_KIND(substring);
10015 kind = kind1 > kind2 ? kind1 : kind2;
10016 buf1 = PyUnicode_DATA(self);
10017 buf2 = PyUnicode_DATA(substring);
10018 if (kind1 != kind)
10019 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10020 if (!buf1)
10021 return NULL;
10022 if (kind2 != kind)
10023 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10024 if (!buf2) {
10025 if (kind1 != kind) PyMem_Free(buf1);
10026 return NULL;
10027 }
10028 len1 = PyUnicode_GET_LENGTH(self);
10029 len2 = PyUnicode_GET_LENGTH(substring);
10030
10031 switch(kind) {
10032 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010033 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10034 out = asciilib_split(
10035 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10036 else
10037 out = ucs1lib_split(
10038 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010039 break;
10040 case PyUnicode_2BYTE_KIND:
10041 out = ucs2lib_split(
10042 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10043 break;
10044 case PyUnicode_4BYTE_KIND:
10045 out = ucs4lib_split(
10046 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10047 break;
10048 default:
10049 out = NULL;
10050 }
10051 if (kind1 != kind)
10052 PyMem_Free(buf1);
10053 if (kind2 != kind)
10054 PyMem_Free(buf2);
10055 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010056}
10057
Alexander Belopolsky40018472011-02-26 01:02:56 +000010058static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010059rsplit(PyObject *self,
10060 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010061 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010062{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 int kind1, kind2, kind;
10064 void *buf1, *buf2;
10065 Py_ssize_t len1, len2;
10066 PyObject* out;
10067
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010068 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010069 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010070
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010071 if (PyUnicode_READY(self) == -1)
10072 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010074 if (substring == NULL)
10075 switch(PyUnicode_KIND(self)) {
10076 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010077 if (PyUnicode_IS_ASCII(self))
10078 return asciilib_rsplit_whitespace(
10079 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10080 PyUnicode_GET_LENGTH(self), maxcount
10081 );
10082 else
10083 return ucs1lib_rsplit_whitespace(
10084 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
10085 PyUnicode_GET_LENGTH(self), maxcount
10086 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010087 case PyUnicode_2BYTE_KIND:
10088 return ucs2lib_rsplit_whitespace(
10089 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10090 PyUnicode_GET_LENGTH(self), maxcount
10091 );
10092 case PyUnicode_4BYTE_KIND:
10093 return ucs4lib_rsplit_whitespace(
10094 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10095 PyUnicode_GET_LENGTH(self), maxcount
10096 );
10097 default:
10098 assert(0);
10099 return NULL;
10100 }
10101
10102 if (PyUnicode_READY(substring) == -1)
10103 return NULL;
10104
10105 kind1 = PyUnicode_KIND(self);
10106 kind2 = PyUnicode_KIND(substring);
10107 kind = kind1 > kind2 ? kind1 : kind2;
10108 buf1 = PyUnicode_DATA(self);
10109 buf2 = PyUnicode_DATA(substring);
10110 if (kind1 != kind)
10111 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10112 if (!buf1)
10113 return NULL;
10114 if (kind2 != kind)
10115 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10116 if (!buf2) {
10117 if (kind1 != kind) PyMem_Free(buf1);
10118 return NULL;
10119 }
10120 len1 = PyUnicode_GET_LENGTH(self);
10121 len2 = PyUnicode_GET_LENGTH(substring);
10122
10123 switch(kind) {
10124 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010125 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10126 out = asciilib_rsplit(
10127 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10128 else
10129 out = ucs1lib_rsplit(
10130 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010131 break;
10132 case PyUnicode_2BYTE_KIND:
10133 out = ucs2lib_rsplit(
10134 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10135 break;
10136 case PyUnicode_4BYTE_KIND:
10137 out = ucs4lib_rsplit(
10138 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10139 break;
10140 default:
10141 out = NULL;
10142 }
10143 if (kind1 != kind)
10144 PyMem_Free(buf1);
10145 if (kind2 != kind)
10146 PyMem_Free(buf2);
10147 return out;
10148}
10149
10150static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010151anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10152 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153{
10154 switch(kind) {
10155 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010156 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10157 return asciilib_find(buf1, len1, buf2, len2, offset);
10158 else
10159 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 case PyUnicode_2BYTE_KIND:
10161 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10162 case PyUnicode_4BYTE_KIND:
10163 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10164 }
10165 assert(0);
10166 return -1;
10167}
10168
10169static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010170anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10171 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172{
10173 switch(kind) {
10174 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010175 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10176 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10177 else
10178 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 case PyUnicode_2BYTE_KIND:
10180 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10181 case PyUnicode_4BYTE_KIND:
10182 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10183 }
10184 assert(0);
10185 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010186}
10187
Alexander Belopolsky40018472011-02-26 01:02:56 +000010188static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189replace(PyObject *self, PyObject *str1,
10190 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010191{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 PyObject *u;
10193 char *sbuf = PyUnicode_DATA(self);
10194 char *buf1 = PyUnicode_DATA(str1);
10195 char *buf2 = PyUnicode_DATA(str2);
10196 int srelease = 0, release1 = 0, release2 = 0;
10197 int skind = PyUnicode_KIND(self);
10198 int kind1 = PyUnicode_KIND(str1);
10199 int kind2 = PyUnicode_KIND(str2);
10200 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10201 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10202 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010203 int mayshrink;
10204 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010205
10206 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010207 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010209 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010210
Victor Stinner59de0ee2011-10-07 10:01:28 +020010211 if (str1 == str2)
10212 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 if (skind < kind1)
10214 /* substring too wide to be present */
10215 goto nothing;
10216
Victor Stinner49a0a212011-10-12 23:46:10 +020010217 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10218 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10219 /* Replacing str1 with str2 may cause a maxchar reduction in the
10220 result string. */
10221 mayshrink = (maxchar_str2 < maxchar);
10222 maxchar = Py_MAX(maxchar, maxchar_str2);
10223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010225 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010226 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010228 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010230 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010231 Py_UCS4 u1, u2;
10232 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010234 if (findchar(sbuf, PyUnicode_KIND(self),
10235 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010236 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010238 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010239 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010241 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010242 rkind = PyUnicode_KIND(u);
10243 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10244 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010245 if (--maxcount < 0)
10246 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010248 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010249 }
10250 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 int rkind = skind;
10252 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010253
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 if (kind1 < rkind) {
10255 /* widen substring */
10256 buf1 = _PyUnicode_AsKind(str1, rkind);
10257 if (!buf1) goto error;
10258 release1 = 1;
10259 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010260 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 if (i < 0)
10262 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010263 if (rkind > kind2) {
10264 /* widen replacement */
10265 buf2 = _PyUnicode_AsKind(str2, rkind);
10266 if (!buf2) goto error;
10267 release2 = 1;
10268 }
10269 else if (rkind < kind2) {
10270 /* widen self and buf1 */
10271 rkind = kind2;
10272 if (release1) PyMem_Free(buf1);
10273 sbuf = _PyUnicode_AsKind(self, rkind);
10274 if (!sbuf) goto error;
10275 srelease = 1;
10276 buf1 = _PyUnicode_AsKind(str1, rkind);
10277 if (!buf1) goto error;
10278 release1 = 1;
10279 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010280 u = PyUnicode_New(slen, maxchar);
10281 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010283 assert(PyUnicode_KIND(u) == rkind);
10284 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010285
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010286 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010287 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010288 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010290 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010292
10293 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010294 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010295 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010296 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010297 if (i == -1)
10298 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010299 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010301 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010303 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010305 }
10306 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 Py_ssize_t n, i, j, ires;
10308 Py_ssize_t product, new_size;
10309 int rkind = skind;
10310 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010312 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010313 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 buf1 = _PyUnicode_AsKind(str1, rkind);
10315 if (!buf1) goto error;
10316 release1 = 1;
10317 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010318 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 if (n == 0)
10320 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010321 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010322 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010323 buf2 = _PyUnicode_AsKind(str2, rkind);
10324 if (!buf2) goto error;
10325 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010326 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010327 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010328 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010329 rkind = kind2;
10330 sbuf = _PyUnicode_AsKind(self, rkind);
10331 if (!sbuf) goto error;
10332 srelease = 1;
10333 if (release1) PyMem_Free(buf1);
10334 buf1 = _PyUnicode_AsKind(str1, rkind);
10335 if (!buf1) goto error;
10336 release1 = 1;
10337 }
10338 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10339 PyUnicode_GET_LENGTH(str1))); */
10340 product = n * (len2-len1);
10341 if ((product / (len2-len1)) != n) {
10342 PyErr_SetString(PyExc_OverflowError,
10343 "replace string is too long");
10344 goto error;
10345 }
10346 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010347 if (new_size == 0) {
10348 Py_INCREF(unicode_empty);
10349 u = unicode_empty;
10350 goto done;
10351 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10353 PyErr_SetString(PyExc_OverflowError,
10354 "replace string is too long");
10355 goto error;
10356 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010357 u = PyUnicode_New(new_size, maxchar);
10358 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010359 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010360 assert(PyUnicode_KIND(u) == rkind);
10361 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010362 ires = i = 0;
10363 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010364 while (n-- > 0) {
10365 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010366 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010367 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010368 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010369 if (j == -1)
10370 break;
10371 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010372 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010373 memcpy(res + rkind * ires,
10374 sbuf + rkind * i,
10375 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010377 }
10378 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010379 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010380 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010381 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010382 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010384 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010385 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010386 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010388 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010389 memcpy(res + rkind * ires,
10390 sbuf + rkind * i,
10391 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010392 }
10393 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010394 /* interleave */
10395 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010396 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010397 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010398 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010399 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010400 if (--n <= 0)
10401 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010402 memcpy(res + rkind * ires,
10403 sbuf + rkind * i,
10404 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010405 ires++;
10406 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010407 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010408 memcpy(res + rkind * ires,
10409 sbuf + rkind * i,
10410 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010411 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010412 }
10413
10414 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010415 unicode_adjust_maxchar(&u);
10416 if (u == NULL)
10417 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010419
10420 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 if (srelease)
10422 PyMem_FREE(sbuf);
10423 if (release1)
10424 PyMem_FREE(buf1);
10425 if (release2)
10426 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010427 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010429
Benjamin Peterson29060642009-01-31 22:14:21 +000010430 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010431 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 if (srelease)
10433 PyMem_FREE(sbuf);
10434 if (release1)
10435 PyMem_FREE(buf1);
10436 if (release2)
10437 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010438 if (PyUnicode_CheckExact(self)) {
10439 Py_INCREF(self);
10440 return (PyObject *) self;
10441 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010442 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443 error:
10444 if (srelease && sbuf)
10445 PyMem_FREE(sbuf);
10446 if (release1 && buf1)
10447 PyMem_FREE(buf1);
10448 if (release2 && buf2)
10449 PyMem_FREE(buf2);
10450 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451}
10452
10453/* --- Unicode Object Methods --------------------------------------------- */
10454
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010455PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010456 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010457\n\
10458Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010459characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460
10461static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010462unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010463{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010464 return fixup(self, fixtitle);
10465}
10466
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010467PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010468 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469\n\
10470Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010471have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472
10473static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010474unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010476 return fixup(self, fixcapitalize);
10477}
10478
10479#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010480PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010481 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010482\n\
10483Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010484normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010485
10486static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010487unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010488{
10489 PyObject *list;
10490 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010491 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010492
Guido van Rossumd57fd912000-03-10 22:53:23 +000010493 /* Split into words */
10494 list = split(self, NULL, -1);
10495 if (!list)
10496 return NULL;
10497
10498 /* Capitalize each word */
10499 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010500 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010501 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010502 if (item == NULL)
10503 goto onError;
10504 Py_DECREF(PyList_GET_ITEM(list, i));
10505 PyList_SET_ITEM(list, i, item);
10506 }
10507
10508 /* Join the words to form a new string */
10509 item = PyUnicode_Join(NULL, list);
10510
Benjamin Peterson29060642009-01-31 22:14:21 +000010511 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512 Py_DECREF(list);
10513 return (PyObject *)item;
10514}
10515#endif
10516
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010517/* Argument converter. Coerces to a single unicode character */
10518
10519static int
10520convert_uc(PyObject *obj, void *addr)
10521{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010522 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010523 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010524
Benjamin Peterson14339b62009-01-31 16:36:08 +000010525 uniobj = PyUnicode_FromObject(obj);
10526 if (uniobj == NULL) {
10527 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010528 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010529 return 0;
10530 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010531 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010532 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010533 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010534 Py_DECREF(uniobj);
10535 return 0;
10536 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010538 Py_DECREF(uniobj);
10539 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010540}
10541
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010542PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010543 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010544\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010545Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010546done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010547
10548static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010549unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010551 Py_ssize_t marg, left;
10552 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010553 Py_UCS4 fillchar = ' ';
10554
Victor Stinnere9a29352011-10-01 02:14:59 +020010555 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010556 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010557
Victor Stinnere9a29352011-10-01 02:14:59 +020010558 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010559 return NULL;
10560
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010561 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010562 Py_INCREF(self);
10563 return (PyObject*) self;
10564 }
10565
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010567 left = marg / 2 + (marg & width & 1);
10568
Victor Stinner9310abb2011-10-05 00:59:23 +020010569 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010570}
10571
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572/* This function assumes that str1 and str2 are readied by the caller. */
10573
Marc-André Lemburge5034372000-08-08 08:04:29 +000010574static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010575unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010576{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010577 int kind1, kind2;
10578 void *data1, *data2;
10579 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 kind1 = PyUnicode_KIND(str1);
10582 kind2 = PyUnicode_KIND(str2);
10583 data1 = PyUnicode_DATA(str1);
10584 data2 = PyUnicode_DATA(str2);
10585 len1 = PyUnicode_GET_LENGTH(str1);
10586 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 for (i = 0; i < len1 && i < len2; ++i) {
10589 Py_UCS4 c1, c2;
10590 c1 = PyUnicode_READ(kind1, data1, i);
10591 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010592
10593 if (c1 != c2)
10594 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010595 }
10596
10597 return (len1 < len2) ? -1 : (len1 != len2);
10598}
10599
Alexander Belopolsky40018472011-02-26 01:02:56 +000010600int
10601PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010602{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010603 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10604 if (PyUnicode_READY(left) == -1 ||
10605 PyUnicode_READY(right) == -1)
10606 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010607 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010608 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010609 PyErr_Format(PyExc_TypeError,
10610 "Can't compare %.100s and %.100s",
10611 left->ob_type->tp_name,
10612 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613 return -1;
10614}
10615
Martin v. Löwis5b222132007-06-10 09:51:05 +000010616int
10617PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10618{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 Py_ssize_t i;
10620 int kind;
10621 void *data;
10622 Py_UCS4 chr;
10623
Victor Stinner910337b2011-10-03 03:20:16 +020010624 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 if (PyUnicode_READY(uni) == -1)
10626 return -1;
10627 kind = PyUnicode_KIND(uni);
10628 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010629 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010630 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10631 if (chr != str[i])
10632 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010633 /* This check keeps Python strings that end in '\0' from comparing equal
10634 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010636 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010637 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010638 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010639 return 0;
10640}
10641
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010642
Benjamin Peterson29060642009-01-31 22:14:21 +000010643#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010644 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010645
Alexander Belopolsky40018472011-02-26 01:02:56 +000010646PyObject *
10647PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010648{
10649 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010650
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010651 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10652 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010653 if (PyUnicode_READY(left) == -1 ||
10654 PyUnicode_READY(right) == -1)
10655 return NULL;
10656 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10657 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010658 if (op == Py_EQ) {
10659 Py_INCREF(Py_False);
10660 return Py_False;
10661 }
10662 if (op == Py_NE) {
10663 Py_INCREF(Py_True);
10664 return Py_True;
10665 }
10666 }
10667 if (left == right)
10668 result = 0;
10669 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010670 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010671
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010672 /* Convert the return value to a Boolean */
10673 switch (op) {
10674 case Py_EQ:
10675 v = TEST_COND(result == 0);
10676 break;
10677 case Py_NE:
10678 v = TEST_COND(result != 0);
10679 break;
10680 case Py_LE:
10681 v = TEST_COND(result <= 0);
10682 break;
10683 case Py_GE:
10684 v = TEST_COND(result >= 0);
10685 break;
10686 case Py_LT:
10687 v = TEST_COND(result == -1);
10688 break;
10689 case Py_GT:
10690 v = TEST_COND(result == 1);
10691 break;
10692 default:
10693 PyErr_BadArgument();
10694 return NULL;
10695 }
10696 Py_INCREF(v);
10697 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010698 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010699
Brian Curtindfc80e32011-08-10 20:28:54 -050010700 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010701}
10702
Alexander Belopolsky40018472011-02-26 01:02:56 +000010703int
10704PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010705{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010706 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 int kind1, kind2, kind;
10708 void *buf1, *buf2;
10709 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010710 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010711
10712 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010713 sub = PyUnicode_FromObject(element);
10714 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010715 PyErr_Format(PyExc_TypeError,
10716 "'in <string>' requires string as left operand, not %s",
10717 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010718 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010719 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010720 if (PyUnicode_READY(sub) == -1)
10721 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010722
Thomas Wouters477c8d52006-05-27 19:21:47 +000010723 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010724 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010725 Py_DECREF(sub);
10726 return -1;
10727 }
10728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010729 kind1 = PyUnicode_KIND(str);
10730 kind2 = PyUnicode_KIND(sub);
10731 kind = kind1 > kind2 ? kind1 : kind2;
10732 buf1 = PyUnicode_DATA(str);
10733 buf2 = PyUnicode_DATA(sub);
10734 if (kind1 != kind)
10735 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10736 if (!buf1) {
10737 Py_DECREF(sub);
10738 return -1;
10739 }
10740 if (kind2 != kind)
10741 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10742 if (!buf2) {
10743 Py_DECREF(sub);
10744 if (kind1 != kind) PyMem_Free(buf1);
10745 return -1;
10746 }
10747 len1 = PyUnicode_GET_LENGTH(str);
10748 len2 = PyUnicode_GET_LENGTH(sub);
10749
10750 switch(kind) {
10751 case PyUnicode_1BYTE_KIND:
10752 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10753 break;
10754 case PyUnicode_2BYTE_KIND:
10755 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10756 break;
10757 case PyUnicode_4BYTE_KIND:
10758 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10759 break;
10760 default:
10761 result = -1;
10762 assert(0);
10763 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010764
10765 Py_DECREF(str);
10766 Py_DECREF(sub);
10767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010768 if (kind1 != kind)
10769 PyMem_Free(buf1);
10770 if (kind2 != kind)
10771 PyMem_Free(buf2);
10772
Guido van Rossum403d68b2000-03-13 15:55:09 +000010773 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010774}
10775
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776/* Concat to string or Unicode object giving a new Unicode object. */
10777
Alexander Belopolsky40018472011-02-26 01:02:56 +000010778PyObject *
10779PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010780{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010782 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010783
10784 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010785 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010787 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010790 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010791
10792 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010793 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010794 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010796 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010797 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010798 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010799 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010800 }
10801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010803 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10804 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010805
Guido van Rossumd57fd912000-03-10 22:53:23 +000010806 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010807 w = PyUnicode_New(
10808 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10809 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010810 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010811 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010812 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10813 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814 Py_DECREF(u);
10815 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010816 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818
Benjamin Peterson29060642009-01-31 22:14:21 +000010819 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010820 Py_XDECREF(u);
10821 Py_XDECREF(v);
10822 return NULL;
10823}
10824
Victor Stinnerb0923652011-10-04 01:17:31 +020010825static void
10826unicode_append_inplace(PyObject **p_left, PyObject *right)
10827{
10828 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010829
10830 assert(PyUnicode_IS_READY(*p_left));
10831 assert(PyUnicode_IS_READY(right));
10832
10833 left_len = PyUnicode_GET_LENGTH(*p_left);
10834 right_len = PyUnicode_GET_LENGTH(right);
10835 if (left_len > PY_SSIZE_T_MAX - right_len) {
10836 PyErr_SetString(PyExc_OverflowError,
10837 "strings are too large to concat");
10838 goto error;
10839 }
10840 new_len = left_len + right_len;
10841
10842 /* Now we own the last reference to 'left', so we can resize it
10843 * in-place.
10844 */
10845 if (unicode_resize(p_left, new_len) != 0) {
10846 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10847 * deallocated so it cannot be put back into
10848 * 'variable'. The MemoryError is raised when there
10849 * is no value in 'variable', which might (very
10850 * remotely) be a cause of incompatibilities.
10851 */
10852 goto error;
10853 }
10854 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010855 copy_characters(*p_left, left_len, right, 0, right_len);
10856 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010857 return;
10858
10859error:
10860 Py_DECREF(*p_left);
10861 *p_left = NULL;
10862}
10863
Walter Dörwald1ab83302007-05-18 17:15:44 +000010864void
Victor Stinner23e56682011-10-03 03:54:37 +020010865PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010866{
Victor Stinner23e56682011-10-03 03:54:37 +020010867 PyObject *left, *res;
10868
10869 if (p_left == NULL) {
10870 if (!PyErr_Occurred())
10871 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010872 return;
10873 }
Victor Stinner23e56682011-10-03 03:54:37 +020010874 left = *p_left;
10875 if (right == NULL || !PyUnicode_Check(left)) {
10876 if (!PyErr_Occurred())
10877 PyErr_BadInternalCall();
10878 goto error;
10879 }
10880
Victor Stinnere1335c72011-10-04 20:53:03 +020010881 if (PyUnicode_READY(left))
10882 goto error;
10883 if (PyUnicode_READY(right))
10884 goto error;
10885
Victor Stinner23e56682011-10-03 03:54:37 +020010886 if (PyUnicode_CheckExact(left) && left != unicode_empty
10887 && PyUnicode_CheckExact(right) && right != unicode_empty
10888 && unicode_resizable(left)
10889 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10890 || _PyUnicode_WSTR(left) != NULL))
10891 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010892 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10893 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010894 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010895 not so different than duplicating the string. */
10896 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010897 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010898 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010899 if (p_left != NULL)
10900 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010901 return;
10902 }
10903 }
10904
10905 res = PyUnicode_Concat(left, right);
10906 if (res == NULL)
10907 goto error;
10908 Py_DECREF(left);
10909 *p_left = res;
10910 return;
10911
10912error:
10913 Py_DECREF(*p_left);
10914 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010915}
10916
10917void
10918PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10919{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010920 PyUnicode_Append(pleft, right);
10921 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010922}
10923
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010924PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010925 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010927Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010928string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010929interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010930
10931static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010932unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010933{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010934 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010935 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010936 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010938 int kind1, kind2, kind;
10939 void *buf1, *buf2;
10940 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010941
Jesus Ceaac451502011-04-20 17:09:23 +020010942 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10943 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010944 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010945
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946 kind1 = PyUnicode_KIND(self);
10947 kind2 = PyUnicode_KIND(substring);
10948 kind = kind1 > kind2 ? kind1 : kind2;
10949 buf1 = PyUnicode_DATA(self);
10950 buf2 = PyUnicode_DATA(substring);
10951 if (kind1 != kind)
10952 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10953 if (!buf1) {
10954 Py_DECREF(substring);
10955 return NULL;
10956 }
10957 if (kind2 != kind)
10958 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10959 if (!buf2) {
10960 Py_DECREF(substring);
10961 if (kind1 != kind) PyMem_Free(buf1);
10962 return NULL;
10963 }
10964 len1 = PyUnicode_GET_LENGTH(self);
10965 len2 = PyUnicode_GET_LENGTH(substring);
10966
10967 ADJUST_INDICES(start, end, len1);
10968 switch(kind) {
10969 case PyUnicode_1BYTE_KIND:
10970 iresult = ucs1lib_count(
10971 ((Py_UCS1*)buf1) + start, end - start,
10972 buf2, len2, PY_SSIZE_T_MAX
10973 );
10974 break;
10975 case PyUnicode_2BYTE_KIND:
10976 iresult = ucs2lib_count(
10977 ((Py_UCS2*)buf1) + start, end - start,
10978 buf2, len2, PY_SSIZE_T_MAX
10979 );
10980 break;
10981 case PyUnicode_4BYTE_KIND:
10982 iresult = ucs4lib_count(
10983 ((Py_UCS4*)buf1) + start, end - start,
10984 buf2, len2, PY_SSIZE_T_MAX
10985 );
10986 break;
10987 default:
10988 assert(0); iresult = 0;
10989 }
10990
10991 result = PyLong_FromSsize_t(iresult);
10992
10993 if (kind1 != kind)
10994 PyMem_Free(buf1);
10995 if (kind2 != kind)
10996 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997
10998 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010999
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000 return result;
11001}
11002
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011003PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000011004 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000011006Encode S using the codec registered for encoding. Default encoding\n\
11007is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011008handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011009a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11010'xmlcharrefreplace' as well as any other name registered with\n\
11011codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011012
11013static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011014unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011016 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011017 char *encoding = NULL;
11018 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011019
Benjamin Peterson308d6372009-09-18 21:42:35 +000011020 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11021 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011023 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011024}
11025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011026PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011027 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011028\n\
11029Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011030If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011031
11032static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011033unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011035 Py_ssize_t i, j, line_pos, src_len, incr;
11036 Py_UCS4 ch;
11037 PyObject *u;
11038 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011040 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011041 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011042
11043 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011044 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045
Antoine Pitrou22425222011-10-04 19:10:51 +020011046 if (PyUnicode_READY(self) == -1)
11047 return NULL;
11048
Thomas Wouters7e474022000-07-16 12:04:32 +000011049 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011050 src_len = PyUnicode_GET_LENGTH(self);
11051 i = j = line_pos = 0;
11052 kind = PyUnicode_KIND(self);
11053 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011054 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011055 for (; i < src_len; i++) {
11056 ch = PyUnicode_READ(kind, src_data, i);
11057 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011058 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011059 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011060 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011061 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011062 goto overflow;
11063 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011064 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011065 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011066 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011068 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011069 goto overflow;
11070 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011072 if (ch == '\n' || ch == '\r')
11073 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011074 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011075 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011076 if (!found && PyUnicode_CheckExact(self)) {
11077 Py_INCREF((PyObject *) self);
11078 return (PyObject *) self;
11079 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011080
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011082 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083 if (!u)
11084 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011085 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086
Antoine Pitroue71d5742011-10-04 15:55:09 +020011087 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
Antoine Pitroue71d5742011-10-04 15:55:09 +020011089 for (; i < src_len; i++) {
11090 ch = PyUnicode_READ(kind, src_data, i);
11091 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011092 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011093 incr = tabsize - (line_pos % tabsize);
11094 line_pos += incr;
11095 while (incr--) {
11096 PyUnicode_WRITE(kind, dest_data, j, ' ');
11097 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011098 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011099 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011100 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011101 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011102 line_pos++;
11103 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011104 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011105 if (ch == '\n' || ch == '\r')
11106 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011107 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011108 }
11109 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011110#ifndef DONT_MAKE_RESULT_READY
11111 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011112 Py_DECREF(u);
11113 return NULL;
11114 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011115#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011116 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011117 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011118
Antoine Pitroue71d5742011-10-04 15:55:09 +020011119 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011120 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11121 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122}
11123
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011124PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011125 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011126\n\
11127Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011128such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129arguments start and end are interpreted as in slice notation.\n\
11130\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011131Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011132
11133static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011134unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011136 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011137 Py_ssize_t start;
11138 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011139 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140
Jesus Ceaac451502011-04-20 17:09:23 +020011141 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11142 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011143 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 if (PyUnicode_READY(self) == -1)
11146 return NULL;
11147 if (PyUnicode_READY(substring) == -1)
11148 return NULL;
11149
Victor Stinner794d5672011-10-10 03:21:36 +020011150 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011151 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011152 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011153
11154 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 if (result == -2)
11157 return NULL;
11158
Christian Heimes217cfd12007-12-02 14:31:20 +000011159 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160}
11161
11162static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011163unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011165 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11166 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011167 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011168 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169}
11170
Guido van Rossumc2504932007-09-18 19:42:40 +000011171/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011172 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011173static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011174unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175{
Guido van Rossumc2504932007-09-18 19:42:40 +000011176 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011177 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011179 if (_PyUnicode_HASH(self) != -1)
11180 return _PyUnicode_HASH(self);
11181 if (PyUnicode_READY(self) == -1)
11182 return -1;
11183 len = PyUnicode_GET_LENGTH(self);
11184
11185 /* The hash function as a macro, gets expanded three times below. */
11186#define HASH(P) \
11187 x = (Py_uhash_t)*P << 7; \
11188 while (--len >= 0) \
11189 x = (1000003*x) ^ (Py_uhash_t)*P++;
11190
11191 switch (PyUnicode_KIND(self)) {
11192 case PyUnicode_1BYTE_KIND: {
11193 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11194 HASH(c);
11195 break;
11196 }
11197 case PyUnicode_2BYTE_KIND: {
11198 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11199 HASH(s);
11200 break;
11201 }
11202 default: {
11203 Py_UCS4 *l;
11204 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11205 "Impossible switch case in unicode_hash");
11206 l = PyUnicode_4BYTE_DATA(self);
11207 HASH(l);
11208 break;
11209 }
11210 }
11211 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11212
Guido van Rossumc2504932007-09-18 19:42:40 +000011213 if (x == -1)
11214 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011215 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011216 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011218#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011220PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011221 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011223Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224
11225static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011228 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011229 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011230 Py_ssize_t start;
11231 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232
Jesus Ceaac451502011-04-20 17:09:23 +020011233 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11234 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011235 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 if (PyUnicode_READY(self) == -1)
11238 return NULL;
11239 if (PyUnicode_READY(substring) == -1)
11240 return NULL;
11241
Victor Stinner794d5672011-10-10 03:21:36 +020011242 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011243 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011244 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245
11246 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 if (result == -2)
11249 return NULL;
11250
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 if (result < 0) {
11252 PyErr_SetString(PyExc_ValueError, "substring not found");
11253 return NULL;
11254 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011255
Christian Heimes217cfd12007-12-02 14:31:20 +000011256 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257}
11258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011259PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011261\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011262Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011263at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011264
11265static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011266unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 Py_ssize_t i, length;
11269 int kind;
11270 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011271 int cased;
11272
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011273 if (PyUnicode_READY(self) == -1)
11274 return NULL;
11275 length = PyUnicode_GET_LENGTH(self);
11276 kind = PyUnicode_KIND(self);
11277 data = PyUnicode_DATA(self);
11278
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011280 if (length == 1)
11281 return PyBool_FromLong(
11282 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011284 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011285 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011286 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011287
Guido van Rossumd57fd912000-03-10 22:53:23 +000011288 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 for (i = 0; i < length; i++) {
11290 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011291
Benjamin Peterson29060642009-01-31 22:14:21 +000011292 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11293 return PyBool_FromLong(0);
11294 else if (!cased && Py_UNICODE_ISLOWER(ch))
11295 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011297 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298}
11299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011300PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011301 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011302\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011303Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011304at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305
11306static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011307unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 Py_ssize_t i, length;
11310 int kind;
11311 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011312 int cased;
11313
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011314 if (PyUnicode_READY(self) == -1)
11315 return NULL;
11316 length = PyUnicode_GET_LENGTH(self);
11317 kind = PyUnicode_KIND(self);
11318 data = PyUnicode_DATA(self);
11319
Guido van Rossumd57fd912000-03-10 22:53:23 +000011320 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 if (length == 1)
11322 return PyBool_FromLong(
11323 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011324
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011325 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011326 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011327 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011328
Guido van Rossumd57fd912000-03-10 22:53:23 +000011329 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 for (i = 0; i < length; i++) {
11331 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011332
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11334 return PyBool_FromLong(0);
11335 else if (!cased && Py_UNICODE_ISUPPER(ch))
11336 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011338 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011339}
11340
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011341PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011342 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011344Return True if S is a titlecased string and there is at least one\n\
11345character in S, i.e. upper- and titlecase characters may only\n\
11346follow uncased characters and lowercase characters only cased ones.\n\
11347Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011348
11349static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011350unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 Py_ssize_t i, length;
11353 int kind;
11354 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355 int cased, previous_is_cased;
11356
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 if (PyUnicode_READY(self) == -1)
11358 return NULL;
11359 length = PyUnicode_GET_LENGTH(self);
11360 kind = PyUnicode_KIND(self);
11361 data = PyUnicode_DATA(self);
11362
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011364 if (length == 1) {
11365 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11366 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11367 (Py_UNICODE_ISUPPER(ch) != 0));
11368 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011369
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011370 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011371 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011372 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011373
Guido van Rossumd57fd912000-03-10 22:53:23 +000011374 cased = 0;
11375 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 for (i = 0; i < length; i++) {
11377 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011378
Benjamin Peterson29060642009-01-31 22:14:21 +000011379 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11380 if (previous_is_cased)
11381 return PyBool_FromLong(0);
11382 previous_is_cased = 1;
11383 cased = 1;
11384 }
11385 else if (Py_UNICODE_ISLOWER(ch)) {
11386 if (!previous_is_cased)
11387 return PyBool_FromLong(0);
11388 previous_is_cased = 1;
11389 cased = 1;
11390 }
11391 else
11392 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011393 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011394 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395}
11396
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011397PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011400Return True if all characters in S are whitespace\n\
11401and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402
11403static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011404unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011406 Py_ssize_t i, length;
11407 int kind;
11408 void *data;
11409
11410 if (PyUnicode_READY(self) == -1)
11411 return NULL;
11412 length = PyUnicode_GET_LENGTH(self);
11413 kind = PyUnicode_KIND(self);
11414 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011415
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011417 if (length == 1)
11418 return PyBool_FromLong(
11419 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011421 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011423 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011424
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011425 for (i = 0; i < length; i++) {
11426 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011427 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011428 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011429 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011430 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431}
11432
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011433PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011434 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011435\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011436Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011437and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011438
11439static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011440unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011441{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 Py_ssize_t i, length;
11443 int kind;
11444 void *data;
11445
11446 if (PyUnicode_READY(self) == -1)
11447 return NULL;
11448 length = PyUnicode_GET_LENGTH(self);
11449 kind = PyUnicode_KIND(self);
11450 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011451
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011452 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 if (length == 1)
11454 return PyBool_FromLong(
11455 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011456
11457 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011458 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011461 for (i = 0; i < length; i++) {
11462 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011463 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011464 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011465 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011466}
11467
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011468PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011469 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011470\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011471Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011472and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011473
11474static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011475unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011477 int kind;
11478 void *data;
11479 Py_ssize_t len, i;
11480
11481 if (PyUnicode_READY(self) == -1)
11482 return NULL;
11483
11484 kind = PyUnicode_KIND(self);
11485 data = PyUnicode_DATA(self);
11486 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011487
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011488 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011489 if (len == 1) {
11490 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11491 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11492 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011493
11494 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011495 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 for (i = 0; i < len; i++) {
11499 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011500 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011501 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011502 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011503 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011504}
11505
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011506PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011507 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011509Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011510False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011511
11512static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011513unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 Py_ssize_t i, length;
11516 int kind;
11517 void *data;
11518
11519 if (PyUnicode_READY(self) == -1)
11520 return NULL;
11521 length = PyUnicode_GET_LENGTH(self);
11522 kind = PyUnicode_KIND(self);
11523 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
Guido van Rossumd57fd912000-03-10 22:53:23 +000011525 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011526 if (length == 1)
11527 return PyBool_FromLong(
11528 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011530 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011531 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011532 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011533
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 for (i = 0; i < length; i++) {
11535 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011536 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011538 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011539}
11540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011541PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011542 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011543\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011544Return True if all characters in S are digits\n\
11545and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011546
11547static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011548unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 Py_ssize_t i, length;
11551 int kind;
11552 void *data;
11553
11554 if (PyUnicode_READY(self) == -1)
11555 return NULL;
11556 length = PyUnicode_GET_LENGTH(self);
11557 kind = PyUnicode_KIND(self);
11558 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011561 if (length == 1) {
11562 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11563 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11564 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011566 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011567 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011568 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011569
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011570 for (i = 0; i < length; i++) {
11571 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011572 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011574 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575}
11576
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011577PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011578 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011579\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011580Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011581False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582
11583static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011584unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 Py_ssize_t i, length;
11587 int kind;
11588 void *data;
11589
11590 if (PyUnicode_READY(self) == -1)
11591 return NULL;
11592 length = PyUnicode_GET_LENGTH(self);
11593 kind = PyUnicode_KIND(self);
11594 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 if (length == 1)
11598 return PyBool_FromLong(
11599 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011600
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011601 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011602 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011603 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011604
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011605 for (i = 0; i < length; i++) {
11606 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011609 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610}
11611
Martin v. Löwis47383402007-08-15 07:32:56 +000011612int
11613PyUnicode_IsIdentifier(PyObject *self)
11614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 int kind;
11616 void *data;
11617 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011618 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (PyUnicode_READY(self) == -1) {
11621 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011622 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011623 }
11624
11625 /* Special case for empty strings */
11626 if (PyUnicode_GET_LENGTH(self) == 0)
11627 return 0;
11628 kind = PyUnicode_KIND(self);
11629 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011630
11631 /* PEP 3131 says that the first character must be in
11632 XID_Start and subsequent characters in XID_Continue,
11633 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011634 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011635 letters, digits, underscore). However, given the current
11636 definition of XID_Start and XID_Continue, it is sufficient
11637 to check just for these, except that _ must be allowed
11638 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011639 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011640 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011641 return 0;
11642
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011643 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011645 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011646 return 1;
11647}
11648
11649PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011650 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011651\n\
11652Return True if S is a valid identifier according\n\
11653to the language definition.");
11654
11655static PyObject*
11656unicode_isidentifier(PyObject *self)
11657{
11658 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11659}
11660
Georg Brandl559e5d72008-06-11 18:37:52 +000011661PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011662 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011663\n\
11664Return True if all characters in S are considered\n\
11665printable in repr() or S is empty, False otherwise.");
11666
11667static PyObject*
11668unicode_isprintable(PyObject *self)
11669{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 Py_ssize_t i, length;
11671 int kind;
11672 void *data;
11673
11674 if (PyUnicode_READY(self) == -1)
11675 return NULL;
11676 length = PyUnicode_GET_LENGTH(self);
11677 kind = PyUnicode_KIND(self);
11678 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011679
11680 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681 if (length == 1)
11682 return PyBool_FromLong(
11683 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011684
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 for (i = 0; i < length; i++) {
11686 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011687 Py_RETURN_FALSE;
11688 }
11689 }
11690 Py_RETURN_TRUE;
11691}
11692
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011693PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011694 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011695\n\
11696Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011697iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011698
11699static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011700unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011701{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011702 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011703}
11704
Martin v. Löwis18e16552006-02-15 17:27:45 +000011705static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011706unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708 if (PyUnicode_READY(self) == -1)
11709 return -1;
11710 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011711}
11712
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011713PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011714 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011715\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011716Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011717done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718
11719static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011720unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011722 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 Py_UCS4 fillchar = ' ';
11724
11725 if (PyUnicode_READY(self) == -1)
11726 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011727
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011728 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011729 return NULL;
11730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011731 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732 Py_INCREF(self);
11733 return (PyObject*) self;
11734 }
11735
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011737}
11738
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011739PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011740 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011741\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011742Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011743
11744static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011745unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011746{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011747 return fixup(self, fixlower);
11748}
11749
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750#define LEFTSTRIP 0
11751#define RIGHTSTRIP 1
11752#define BOTHSTRIP 2
11753
11754/* Arrays indexed by above */
11755static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11756
11757#define STRIPNAME(i) (stripformat[i]+3)
11758
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011759/* externally visible for str.strip(unicode) */
11760PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011761_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011762{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011763 void *data;
11764 int kind;
11765 Py_ssize_t i, j, len;
11766 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011768 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11769 return NULL;
11770
11771 kind = PyUnicode_KIND(self);
11772 data = PyUnicode_DATA(self);
11773 len = PyUnicode_GET_LENGTH(self);
11774 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11775 PyUnicode_DATA(sepobj),
11776 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011777
Benjamin Peterson14339b62009-01-31 16:36:08 +000011778 i = 0;
11779 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 while (i < len &&
11781 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011782 i++;
11783 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011784 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011785
Benjamin Peterson14339b62009-01-31 16:36:08 +000011786 j = len;
11787 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011788 do {
11789 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011790 } while (j >= i &&
11791 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011792 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011793 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011794
Victor Stinner12bab6d2011-10-01 01:53:49 +020011795 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011796}
11797
11798PyObject*
11799PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11800{
11801 unsigned char *data;
11802 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011803 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804
Victor Stinnerde636f32011-10-01 03:55:54 +020011805 if (PyUnicode_READY(self) == -1)
11806 return NULL;
11807
11808 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11809
Victor Stinner12bab6d2011-10-01 01:53:49 +020011810 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011811 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011812 if (PyUnicode_CheckExact(self)) {
11813 Py_INCREF(self);
11814 return self;
11815 }
11816 else
11817 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011818 }
11819
Victor Stinner12bab6d2011-10-01 01:53:49 +020011820 length = end - start;
11821 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011822 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011823
Victor Stinnerde636f32011-10-01 03:55:54 +020011824 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011825 PyErr_SetString(PyExc_IndexError, "string index out of range");
11826 return NULL;
11827 }
11828
Victor Stinnerb9275c12011-10-05 14:01:42 +020011829 if (PyUnicode_IS_ASCII(self)) {
11830 kind = PyUnicode_KIND(self);
11831 data = PyUnicode_1BYTE_DATA(self);
11832 return unicode_fromascii(data + start, length);
11833 }
11834 else {
11835 kind = PyUnicode_KIND(self);
11836 data = PyUnicode_1BYTE_DATA(self);
11837 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011838 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011839 length);
11840 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011841}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011842
11843static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011844do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011845{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011846 int kind;
11847 void *data;
11848 Py_ssize_t len, i, j;
11849
11850 if (PyUnicode_READY(self) == -1)
11851 return NULL;
11852
11853 kind = PyUnicode_KIND(self);
11854 data = PyUnicode_DATA(self);
11855 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011856
Benjamin Peterson14339b62009-01-31 16:36:08 +000011857 i = 0;
11858 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011859 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011860 i++;
11861 }
11862 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011863
Benjamin Peterson14339b62009-01-31 16:36:08 +000011864 j = len;
11865 if (striptype != LEFTSTRIP) {
11866 do {
11867 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011868 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011869 j++;
11870 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011871
Victor Stinner12bab6d2011-10-01 01:53:49 +020011872 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873}
11874
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011875
11876static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011877do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011878{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011879 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011880
Benjamin Peterson14339b62009-01-31 16:36:08 +000011881 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11882 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011883
Benjamin Peterson14339b62009-01-31 16:36:08 +000011884 if (sep != NULL && sep != Py_None) {
11885 if (PyUnicode_Check(sep))
11886 return _PyUnicode_XStrip(self, striptype, sep);
11887 else {
11888 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011889 "%s arg must be None or str",
11890 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011891 return NULL;
11892 }
11893 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011894
Benjamin Peterson14339b62009-01-31 16:36:08 +000011895 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011896}
11897
11898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011899PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011900 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011901\n\
11902Return a copy of the string S with leading and trailing\n\
11903whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011904If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011905
11906static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011907unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011908{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011909 if (PyTuple_GET_SIZE(args) == 0)
11910 return do_strip(self, BOTHSTRIP); /* Common case */
11911 else
11912 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011913}
11914
11915
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011916PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011917 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011918\n\
11919Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011920If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011921
11922static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011923unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011924{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011925 if (PyTuple_GET_SIZE(args) == 0)
11926 return do_strip(self, LEFTSTRIP); /* Common case */
11927 else
11928 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011929}
11930
11931
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011932PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011933 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934\n\
11935Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011936If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011937
11938static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011939unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011940{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011941 if (PyTuple_GET_SIZE(args) == 0)
11942 return do_strip(self, RIGHTSTRIP); /* Common case */
11943 else
11944 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011945}
11946
11947
Guido van Rossumd57fd912000-03-10 22:53:23 +000011948static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011949unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011950{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011951 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011952 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011953
Georg Brandl222de0f2009-04-12 12:01:50 +000011954 if (len < 1) {
11955 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011956 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011957 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011958
Tim Peters7a29bd52001-09-12 03:03:31 +000011959 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011960 /* no repeat, return original string */
11961 Py_INCREF(str);
11962 return (PyObject*) str;
11963 }
Tim Peters8f422462000-09-09 06:13:41 +000011964
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011965 if (PyUnicode_READY(str) == -1)
11966 return NULL;
11967
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011968 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011969 PyErr_SetString(PyExc_OverflowError,
11970 "repeated string is too long");
11971 return NULL;
11972 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011974
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011975 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011976 if (!u)
11977 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011978 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011979
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011980 if (PyUnicode_GET_LENGTH(str) == 1) {
11981 const int kind = PyUnicode_KIND(str);
11982 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11983 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011984 if (kind == PyUnicode_1BYTE_KIND)
11985 memset(to, (unsigned char)fill_char, len);
11986 else {
11987 for (n = 0; n < len; ++n)
11988 PyUnicode_WRITE(kind, to, n, fill_char);
11989 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011990 }
11991 else {
11992 /* number of characters copied this far */
11993 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011994 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 char *to = (char *) PyUnicode_DATA(u);
11996 Py_MEMCPY(to, PyUnicode_DATA(str),
11997 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011998 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 n = (done <= nchars-done) ? done : nchars-done;
12000 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012001 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000012002 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003 }
12004
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012005 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012006 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012007}
12008
Alexander Belopolsky40018472011-02-26 01:02:56 +000012009PyObject *
12010PyUnicode_Replace(PyObject *obj,
12011 PyObject *subobj,
12012 PyObject *replobj,
12013 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012014{
12015 PyObject *self;
12016 PyObject *str1;
12017 PyObject *str2;
12018 PyObject *result;
12019
12020 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012021 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012022 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012023 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012024 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012025 Py_DECREF(self);
12026 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012027 }
12028 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012029 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012030 Py_DECREF(self);
12031 Py_DECREF(str1);
12032 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012033 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012035 Py_DECREF(self);
12036 Py_DECREF(str1);
12037 Py_DECREF(str2);
12038 return result;
12039}
12040
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012041PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012042 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043\n\
12044Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012045old replaced by new. If the optional argument count is\n\
12046given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012047
12048static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012050{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012051 PyObject *str1;
12052 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012053 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012054 PyObject *result;
12055
Martin v. Löwis18e16552006-02-15 17:27:45 +000012056 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012058 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012059 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 str1 = PyUnicode_FromObject(str1);
12061 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12062 return NULL;
12063 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012064 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012065 Py_DECREF(str1);
12066 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012067 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012068
12069 result = replace(self, str1, str2, maxcount);
12070
12071 Py_DECREF(str1);
12072 Py_DECREF(str2);
12073 return result;
12074}
12075
Alexander Belopolsky40018472011-02-26 01:02:56 +000012076static PyObject *
12077unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012078{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012079 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012080 Py_ssize_t isize;
12081 Py_ssize_t osize, squote, dquote, i, o;
12082 Py_UCS4 max, quote;
12083 int ikind, okind;
12084 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012085
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012086 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012087 return NULL;
12088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 isize = PyUnicode_GET_LENGTH(unicode);
12090 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012091
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012092 /* Compute length of output, quote characters, and
12093 maximum character */
12094 osize = 2; /* quotes */
12095 max = 127;
12096 squote = dquote = 0;
12097 ikind = PyUnicode_KIND(unicode);
12098 for (i = 0; i < isize; i++) {
12099 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12100 switch (ch) {
12101 case '\'': squote++; osize++; break;
12102 case '"': dquote++; osize++; break;
12103 case '\\': case '\t': case '\r': case '\n':
12104 osize += 2; break;
12105 default:
12106 /* Fast-path ASCII */
12107 if (ch < ' ' || ch == 0x7f)
12108 osize += 4; /* \xHH */
12109 else if (ch < 0x7f)
12110 osize++;
12111 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12112 osize++;
12113 max = ch > max ? ch : max;
12114 }
12115 else if (ch < 0x100)
12116 osize += 4; /* \xHH */
12117 else if (ch < 0x10000)
12118 osize += 6; /* \uHHHH */
12119 else
12120 osize += 10; /* \uHHHHHHHH */
12121 }
12122 }
12123
12124 quote = '\'';
12125 if (squote) {
12126 if (dquote)
12127 /* Both squote and dquote present. Use squote,
12128 and escape them */
12129 osize += squote;
12130 else
12131 quote = '"';
12132 }
12133
12134 repr = PyUnicode_New(osize, max);
12135 if (repr == NULL)
12136 return NULL;
12137 okind = PyUnicode_KIND(repr);
12138 odata = PyUnicode_DATA(repr);
12139
12140 PyUnicode_WRITE(okind, odata, 0, quote);
12141 PyUnicode_WRITE(okind, odata, osize-1, quote);
12142
12143 for (i = 0, o = 1; i < isize; i++) {
12144 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012145
12146 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 if ((ch == quote) || (ch == '\\')) {
12148 PyUnicode_WRITE(okind, odata, o++, '\\');
12149 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012150 continue;
12151 }
12152
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012154 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012155 PyUnicode_WRITE(okind, odata, o++, '\\');
12156 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012157 }
12158 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012159 PyUnicode_WRITE(okind, odata, o++, '\\');
12160 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012161 }
12162 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163 PyUnicode_WRITE(okind, odata, o++, '\\');
12164 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012165 }
12166
12167 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012168 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012169 PyUnicode_WRITE(okind, odata, o++, '\\');
12170 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012171 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12172 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012173 }
12174
Georg Brandl559e5d72008-06-11 18:37:52 +000012175 /* Copy ASCII characters as-is */
12176 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012177 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012178 }
12179
Benjamin Peterson29060642009-01-31 22:14:21 +000012180 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012181 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012182 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012183 (categories Z* and C* except ASCII space)
12184 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012186 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012187 if (ch <= 0xff) {
12188 PyUnicode_WRITE(okind, odata, o++, '\\');
12189 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012190 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12191 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012192 }
12193 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194 else if (ch >= 0x10000) {
12195 PyUnicode_WRITE(okind, odata, o++, '\\');
12196 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012197 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12198 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12199 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12200 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12201 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12202 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12203 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12204 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012205 }
12206 /* Map 16-bit characters to '\uxxxx' */
12207 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012208 PyUnicode_WRITE(okind, odata, o++, '\\');
12209 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012210 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12211 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12212 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12213 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012214 }
12215 }
12216 /* Copy characters as-is */
12217 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012218 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012219 }
12220 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012221 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012222 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012223 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012224 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225}
12226
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012227PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012228 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012229\n\
12230Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012231such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232arguments start and end are interpreted as in slice notation.\n\
12233\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012234Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235
12236static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012237unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012239 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012240 Py_ssize_t start;
12241 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012242 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243
Jesus Ceaac451502011-04-20 17:09:23 +020012244 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12245 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012246 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 if (PyUnicode_READY(self) == -1)
12249 return NULL;
12250 if (PyUnicode_READY(substring) == -1)
12251 return NULL;
12252
Victor Stinner794d5672011-10-10 03:21:36 +020012253 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012254 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012255 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256
12257 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012258
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012259 if (result == -2)
12260 return NULL;
12261
Christian Heimes217cfd12007-12-02 14:31:20 +000012262 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012263}
12264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012265PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012266 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012268Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012269
12270static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012271unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012272{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012273 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012274 Py_ssize_t start;
12275 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012276 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012277
Jesus Ceaac451502011-04-20 17:09:23 +020012278 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12279 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012280 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012282 if (PyUnicode_READY(self) == -1)
12283 return NULL;
12284 if (PyUnicode_READY(substring) == -1)
12285 return NULL;
12286
Victor Stinner794d5672011-10-10 03:21:36 +020012287 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012289 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012290
12291 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012292
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 if (result == -2)
12294 return NULL;
12295
Guido van Rossumd57fd912000-03-10 22:53:23 +000012296 if (result < 0) {
12297 PyErr_SetString(PyExc_ValueError, "substring not found");
12298 return NULL;
12299 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012300
Christian Heimes217cfd12007-12-02 14:31:20 +000012301 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012302}
12303
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012304PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012305 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012306\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012307Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012308done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012309
12310static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012311unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012312{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012313 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 Py_UCS4 fillchar = ' ';
12315
Victor Stinnere9a29352011-10-01 02:14:59 +020012316 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012317 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012318
Victor Stinnere9a29352011-10-01 02:14:59 +020012319 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320 return NULL;
12321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012322 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012323 Py_INCREF(self);
12324 return (PyObject*) self;
12325 }
12326
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012328}
12329
Alexander Belopolsky40018472011-02-26 01:02:56 +000012330PyObject *
12331PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012332{
12333 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012334
Guido van Rossumd57fd912000-03-10 22:53:23 +000012335 s = PyUnicode_FromObject(s);
12336 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012337 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012338 if (sep != NULL) {
12339 sep = PyUnicode_FromObject(sep);
12340 if (sep == NULL) {
12341 Py_DECREF(s);
12342 return NULL;
12343 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012344 }
12345
Victor Stinner9310abb2011-10-05 00:59:23 +020012346 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012347
12348 Py_DECREF(s);
12349 Py_XDECREF(sep);
12350 return result;
12351}
12352
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012353PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012354 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012355\n\
12356Return a list of the words in S, using sep as the\n\
12357delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012358splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012359whitespace string is a separator and empty strings are\n\
12360removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012361
12362static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012363unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012364{
12365 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012366 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012367
Martin v. Löwis18e16552006-02-15 17:27:45 +000012368 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012369 return NULL;
12370
12371 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012372 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012373 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012374 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012375 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012377}
12378
Thomas Wouters477c8d52006-05-27 19:21:47 +000012379PyObject *
12380PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12381{
12382 PyObject* str_obj;
12383 PyObject* sep_obj;
12384 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 int kind1, kind2, kind;
12386 void *buf1 = NULL, *buf2 = NULL;
12387 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012388
12389 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012390 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012391 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012392 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012393 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012394 Py_DECREF(str_obj);
12395 return NULL;
12396 }
12397
Victor Stinner14f8f022011-10-05 20:58:25 +020012398 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012399 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012400 kind = Py_MAX(kind1, kind2);
12401 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012402 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012403 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012404 if (!buf1)
12405 goto onError;
12406 buf2 = PyUnicode_DATA(sep_obj);
12407 if (kind2 != kind)
12408 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12409 if (!buf2)
12410 goto onError;
12411 len1 = PyUnicode_GET_LENGTH(str_obj);
12412 len2 = PyUnicode_GET_LENGTH(sep_obj);
12413
Victor Stinner14f8f022011-10-05 20:58:25 +020012414 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012415 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012416 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12417 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12418 else
12419 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012420 break;
12421 case PyUnicode_2BYTE_KIND:
12422 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12423 break;
12424 case PyUnicode_4BYTE_KIND:
12425 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12426 break;
12427 default:
12428 assert(0);
12429 out = 0;
12430 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012431
12432 Py_DECREF(sep_obj);
12433 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012434 if (kind1 != kind)
12435 PyMem_Free(buf1);
12436 if (kind2 != kind)
12437 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012438
12439 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012440 onError:
12441 Py_DECREF(sep_obj);
12442 Py_DECREF(str_obj);
12443 if (kind1 != kind && buf1)
12444 PyMem_Free(buf1);
12445 if (kind2 != kind && buf2)
12446 PyMem_Free(buf2);
12447 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012448}
12449
12450
12451PyObject *
12452PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12453{
12454 PyObject* str_obj;
12455 PyObject* sep_obj;
12456 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012457 int kind1, kind2, kind;
12458 void *buf1 = NULL, *buf2 = NULL;
12459 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012460
12461 str_obj = PyUnicode_FromObject(str_in);
12462 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012464 sep_obj = PyUnicode_FromObject(sep_in);
12465 if (!sep_obj) {
12466 Py_DECREF(str_obj);
12467 return NULL;
12468 }
12469
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012470 kind1 = PyUnicode_KIND(str_in);
12471 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012472 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012473 buf1 = PyUnicode_DATA(str_in);
12474 if (kind1 != kind)
12475 buf1 = _PyUnicode_AsKind(str_in, kind);
12476 if (!buf1)
12477 goto onError;
12478 buf2 = PyUnicode_DATA(sep_obj);
12479 if (kind2 != kind)
12480 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12481 if (!buf2)
12482 goto onError;
12483 len1 = PyUnicode_GET_LENGTH(str_obj);
12484 len2 = PyUnicode_GET_LENGTH(sep_obj);
12485
12486 switch(PyUnicode_KIND(str_in)) {
12487 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012488 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12489 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12490 else
12491 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012492 break;
12493 case PyUnicode_2BYTE_KIND:
12494 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12495 break;
12496 case PyUnicode_4BYTE_KIND:
12497 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12498 break;
12499 default:
12500 assert(0);
12501 out = 0;
12502 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012503
12504 Py_DECREF(sep_obj);
12505 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012506 if (kind1 != kind)
12507 PyMem_Free(buf1);
12508 if (kind2 != kind)
12509 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012510
12511 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012512 onError:
12513 Py_DECREF(sep_obj);
12514 Py_DECREF(str_obj);
12515 if (kind1 != kind && buf1)
12516 PyMem_Free(buf1);
12517 if (kind2 != kind && buf2)
12518 PyMem_Free(buf2);
12519 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012520}
12521
12522PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012523 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012524\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012525Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012527found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012528
12529static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012530unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012531{
Victor Stinner9310abb2011-10-05 00:59:23 +020012532 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012533}
12534
12535PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012536 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012537\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012538Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012539the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012540separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012541
12542static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012543unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012544{
Victor Stinner9310abb2011-10-05 00:59:23 +020012545 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012546}
12547
Alexander Belopolsky40018472011-02-26 01:02:56 +000012548PyObject *
12549PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012550{
12551 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012552
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012553 s = PyUnicode_FromObject(s);
12554 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012555 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012556 if (sep != NULL) {
12557 sep = PyUnicode_FromObject(sep);
12558 if (sep == NULL) {
12559 Py_DECREF(s);
12560 return NULL;
12561 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012562 }
12563
Victor Stinner9310abb2011-10-05 00:59:23 +020012564 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012565
12566 Py_DECREF(s);
12567 Py_XDECREF(sep);
12568 return result;
12569}
12570
12571PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012572 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012573\n\
12574Return a list of the words in S, using sep as the\n\
12575delimiter string, starting at the end of the string and\n\
12576working to the front. If maxsplit is given, at most maxsplit\n\
12577splits are done. If sep is not specified, any whitespace string\n\
12578is a separator.");
12579
12580static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012581unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012582{
12583 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012584 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012585
Martin v. Löwis18e16552006-02-15 17:27:45 +000012586 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012587 return NULL;
12588
12589 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012590 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012591 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012592 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012593 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012594 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012595}
12596
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012597PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012598 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012599\n\
12600Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012601Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012602is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012603
12604static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012605unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012607 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012608 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012610 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12611 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612 return NULL;
12613
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012614 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615}
12616
12617static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012618PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012619{
Walter Dörwald346737f2007-05-31 10:44:43 +000012620 if (PyUnicode_CheckExact(self)) {
12621 Py_INCREF(self);
12622 return self;
12623 } else
12624 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012625 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626}
12627
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012628PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012629 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630\n\
12631Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012632and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633
12634static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012635unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637 return fixup(self, fixswapcase);
12638}
12639
Georg Brandlceee0772007-11-27 23:48:05 +000012640PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012641 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012642\n\
12643Return a translation table usable for str.translate().\n\
12644If there is only one argument, it must be a dictionary mapping Unicode\n\
12645ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012646Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012647If there are two arguments, they must be strings of equal length, and\n\
12648in the resulting dictionary, each character in x will be mapped to the\n\
12649character at the same position in y. If there is a third argument, it\n\
12650must be a string, whose characters will be mapped to None in the result.");
12651
12652static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012653unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012654{
12655 PyObject *x, *y = NULL, *z = NULL;
12656 PyObject *new = NULL, *key, *value;
12657 Py_ssize_t i = 0;
12658 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012659
Georg Brandlceee0772007-11-27 23:48:05 +000012660 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12661 return NULL;
12662 new = PyDict_New();
12663 if (!new)
12664 return NULL;
12665 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 int x_kind, y_kind, z_kind;
12667 void *x_data, *y_data, *z_data;
12668
Georg Brandlceee0772007-11-27 23:48:05 +000012669 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012670 if (!PyUnicode_Check(x)) {
12671 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12672 "be a string if there is a second argument");
12673 goto err;
12674 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012675 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012676 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12677 "arguments must have equal length");
12678 goto err;
12679 }
12680 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012681 x_kind = PyUnicode_KIND(x);
12682 y_kind = PyUnicode_KIND(y);
12683 x_data = PyUnicode_DATA(x);
12684 y_data = PyUnicode_DATA(y);
12685 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12686 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12687 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012688 if (!key || !value)
12689 goto err;
12690 res = PyDict_SetItem(new, key, value);
12691 Py_DECREF(key);
12692 Py_DECREF(value);
12693 if (res < 0)
12694 goto err;
12695 }
12696 /* create entries for deleting chars in z */
12697 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012698 z_kind = PyUnicode_KIND(z);
12699 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012700 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012702 if (!key)
12703 goto err;
12704 res = PyDict_SetItem(new, key, Py_None);
12705 Py_DECREF(key);
12706 if (res < 0)
12707 goto err;
12708 }
12709 }
12710 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 int kind;
12712 void *data;
12713
Georg Brandlceee0772007-11-27 23:48:05 +000012714 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012715 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012716 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12717 "to maketrans it must be a dict");
12718 goto err;
12719 }
12720 /* copy entries into the new dict, converting string keys to int keys */
12721 while (PyDict_Next(x, &i, &key, &value)) {
12722 if (PyUnicode_Check(key)) {
12723 /* convert string keys to integer keys */
12724 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012725 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012726 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12727 "table must be of length 1");
12728 goto err;
12729 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012730 kind = PyUnicode_KIND(key);
12731 data = PyUnicode_DATA(key);
12732 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012733 if (!newkey)
12734 goto err;
12735 res = PyDict_SetItem(new, newkey, value);
12736 Py_DECREF(newkey);
12737 if (res < 0)
12738 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012739 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012740 /* just keep integer keys */
12741 if (PyDict_SetItem(new, key, value) < 0)
12742 goto err;
12743 } else {
12744 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12745 "be strings or integers");
12746 goto err;
12747 }
12748 }
12749 }
12750 return new;
12751 err:
12752 Py_DECREF(new);
12753 return NULL;
12754}
12755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012756PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758\n\
12759Return a copy of the string S, where all characters have been mapped\n\
12760through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012761Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012762Unmapped characters are left untouched. Characters mapped to None\n\
12763are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764
12765static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012766unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012768 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769}
12770
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012771PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012772 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012773\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012774Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775
12776static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012777unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012778{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012779 return fixup(self, fixupper);
12780}
12781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012782PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012783 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012784\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012785Pad a numeric string S with zeros on the left, to fill a field\n\
12786of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787
12788static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012789unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012790{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012791 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012792 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012793 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012794 int kind;
12795 void *data;
12796 Py_UCS4 chr;
12797
12798 if (PyUnicode_READY(self) == -1)
12799 return NULL;
12800
Martin v. Löwis18e16552006-02-15 17:27:45 +000012801 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012802 return NULL;
12803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012804 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012805 if (PyUnicode_CheckExact(self)) {
12806 Py_INCREF(self);
12807 return (PyObject*) self;
12808 }
12809 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012810 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012811 }
12812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012813 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814
12815 u = pad(self, fill, 0, '0');
12816
Walter Dörwald068325e2002-04-15 13:36:47 +000012817 if (u == NULL)
12818 return NULL;
12819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012820 kind = PyUnicode_KIND(u);
12821 data = PyUnicode_DATA(u);
12822 chr = PyUnicode_READ(kind, data, fill);
12823
12824 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012826 PyUnicode_WRITE(kind, data, 0, chr);
12827 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012828 }
12829
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012830 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012831 return (PyObject*) u;
12832}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833
12834#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012835static PyObject *
12836unicode__decimal2ascii(PyObject *self)
12837{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012838 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012839}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012840#endif
12841
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012842PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012843 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012845Return True if S starts with the specified prefix, False otherwise.\n\
12846With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012847With optional end, stop comparing S at that position.\n\
12848prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012849
12850static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012851unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012852 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012853{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012854 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012855 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012856 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012857 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012858 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859
Jesus Ceaac451502011-04-20 17:09:23 +020012860 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012861 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012862 if (PyTuple_Check(subobj)) {
12863 Py_ssize_t i;
12864 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012865 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012866 if (substring == NULL)
12867 return NULL;
12868 result = tailmatch(self, substring, start, end, -1);
12869 Py_DECREF(substring);
12870 if (result) {
12871 Py_RETURN_TRUE;
12872 }
12873 }
12874 /* nothing matched */
12875 Py_RETURN_FALSE;
12876 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012877 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012878 if (substring == NULL) {
12879 if (PyErr_ExceptionMatches(PyExc_TypeError))
12880 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12881 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012882 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012883 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012884 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012885 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012886 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012887}
12888
12889
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012890PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012891 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012893Return True if S ends with the specified suffix, False otherwise.\n\
12894With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012895With optional end, stop comparing S at that position.\n\
12896suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012897
12898static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012899unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012900 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012901{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012902 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012903 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012904 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012905 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012906 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012907
Jesus Ceaac451502011-04-20 17:09:23 +020012908 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012909 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012910 if (PyTuple_Check(subobj)) {
12911 Py_ssize_t i;
12912 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012913 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012914 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012915 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012916 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012917 result = tailmatch(self, substring, start, end, +1);
12918 Py_DECREF(substring);
12919 if (result) {
12920 Py_RETURN_TRUE;
12921 }
12922 }
12923 Py_RETURN_FALSE;
12924 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012925 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012926 if (substring == NULL) {
12927 if (PyErr_ExceptionMatches(PyExc_TypeError))
12928 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12929 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012930 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012931 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012932 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012933 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012934 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935}
12936
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012937#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012938
12939PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012940 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012941\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012942Return a formatted version of S, using substitutions from args and kwargs.\n\
12943The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012944
Eric Smith27bbca62010-11-04 17:06:58 +000012945PyDoc_STRVAR(format_map__doc__,
12946 "S.format_map(mapping) -> str\n\
12947\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012948Return a formatted version of S, using substitutions from mapping.\n\
12949The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012950
Eric Smith4a7d76d2008-05-30 18:10:19 +000012951static PyObject *
12952unicode__format__(PyObject* self, PyObject* args)
12953{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012954 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012955
12956 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12957 return NULL;
12958
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012959 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012961 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012962}
12963
Eric Smith8c663262007-08-25 02:26:07 +000012964PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012965 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012966\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012967Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012968
12969static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012970unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012971{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012972 Py_ssize_t size;
12973
12974 /* If it's a compact object, account for base structure +
12975 character data. */
12976 if (PyUnicode_IS_COMPACT_ASCII(v))
12977 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12978 else if (PyUnicode_IS_COMPACT(v))
12979 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012980 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012981 else {
12982 /* If it is a two-block object, account for base object, and
12983 for character block if present. */
12984 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012985 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012986 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012987 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012988 }
12989 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012990 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012991 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012992 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012993 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012994 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012995
12996 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012997}
12998
12999PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000013000 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013001
13002static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020013003unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013004{
Victor Stinner034f6cf2011-09-30 02:26:44 +020013005 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013006 if (!copy)
13007 return NULL;
13008 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000013009}
13010
Guido van Rossumd57fd912000-03-10 22:53:23 +000013011static PyMethodDef unicode_methods[] = {
13012
13013 /* Order is according to common usage: often used methods should
13014 appear first, since lookup is done sequentially. */
13015
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013016 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013017 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13018 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013019 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013020 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13021 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13022 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13023 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13024 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13025 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13026 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013027 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013028 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13029 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13030 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013031 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013032 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13033 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13034 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013035 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013036 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013037 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013038 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013039 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13040 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13041 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13042 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13043 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13044 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13045 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13046 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13047 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13048 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13049 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13050 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13051 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13052 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013053 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013054 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013055 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013056 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013057 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013058 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013059 {"maketrans", (PyCFunction) unicode_maketrans,
13060 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013061 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013062#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013063 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013064#endif
13065
13066#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013067 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013068 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069#endif
13070
Benjamin Peterson14339b62009-01-31 16:36:08 +000013071 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013072 {NULL, NULL}
13073};
13074
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013075static PyObject *
13076unicode_mod(PyObject *v, PyObject *w)
13077{
Brian Curtindfc80e32011-08-10 20:28:54 -050013078 if (!PyUnicode_Check(v))
13079 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013080 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013081}
13082
13083static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013084 0, /*nb_add*/
13085 0, /*nb_subtract*/
13086 0, /*nb_multiply*/
13087 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013088};
13089
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013091 (lenfunc) unicode_length, /* sq_length */
13092 PyUnicode_Concat, /* sq_concat */
13093 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13094 (ssizeargfunc) unicode_getitem, /* sq_item */
13095 0, /* sq_slice */
13096 0, /* sq_ass_item */
13097 0, /* sq_ass_slice */
13098 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013099};
13100
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013101static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013102unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013103{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013104 if (PyUnicode_READY(self) == -1)
13105 return NULL;
13106
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013107 if (PyIndex_Check(item)) {
13108 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013109 if (i == -1 && PyErr_Occurred())
13110 return NULL;
13111 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013112 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013113 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013114 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013115 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013116 PyObject *result;
13117 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013118 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013119 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013120
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013121 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013122 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013123 return NULL;
13124 }
13125
13126 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013127 return PyUnicode_New(0, 0);
13128 } else if (start == 0 && step == 1 &&
13129 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013130 PyUnicode_CheckExact(self)) {
13131 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013132 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013133 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013134 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013135 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013136 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013137 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013138 src_kind = PyUnicode_KIND(self);
13139 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013140 if (!PyUnicode_IS_ASCII(self)) {
13141 kind_limit = kind_maxchar_limit(src_kind);
13142 max_char = 0;
13143 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13144 ch = PyUnicode_READ(src_kind, src_data, cur);
13145 if (ch > max_char) {
13146 max_char = ch;
13147 if (max_char >= kind_limit)
13148 break;
13149 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013150 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013151 }
Victor Stinner55c99112011-10-13 01:17:06 +020013152 else
13153 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013154 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013155 if (result == NULL)
13156 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013157 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013158 dest_data = PyUnicode_DATA(result);
13159
13160 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013161 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13162 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013163 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013164 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013165 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013166 } else {
13167 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13168 return NULL;
13169 }
13170}
13171
13172static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013173 (lenfunc)unicode_length, /* mp_length */
13174 (binaryfunc)unicode_subscript, /* mp_subscript */
13175 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013176};
13177
Guido van Rossumd57fd912000-03-10 22:53:23 +000013178
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179/* Helpers for PyUnicode_Format() */
13180
13181static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013182getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013184 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013185 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013186 (*p_argidx)++;
13187 if (arglen < 0)
13188 return args;
13189 else
13190 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191 }
13192 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013193 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194 return NULL;
13195}
13196
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013197/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013199static PyObject *
13200formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013202 char *p;
13203 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013204 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013205
Guido van Rossumd57fd912000-03-10 22:53:23 +000013206 x = PyFloat_AsDouble(v);
13207 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013208 return NULL;
13209
Guido van Rossumd57fd912000-03-10 22:53:23 +000013210 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013211 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013212
Eric Smith0923d1d2009-04-16 20:16:10 +000013213 p = PyOS_double_to_string(x, type, prec,
13214 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013215 if (p == NULL)
13216 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013217 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013218 PyMem_Free(p);
13219 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013220}
13221
Tim Peters38fd5b62000-09-21 05:43:11 +000013222static PyObject*
13223formatlong(PyObject *val, int flags, int prec, int type)
13224{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013225 char *buf;
13226 int len;
13227 PyObject *str; /* temporary string object. */
13228 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013229
Benjamin Peterson14339b62009-01-31 16:36:08 +000013230 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13231 if (!str)
13232 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013233 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013234 Py_DECREF(str);
13235 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013236}
13237
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013238static Py_UCS4
13239formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013241 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013242 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013244 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 goto onError;
13247 }
13248 else {
13249 /* Integer input truncated to a character */
13250 long x;
13251 x = PyLong_AsLong(v);
13252 if (x == -1 && PyErr_Occurred())
13253 goto onError;
13254
13255 if (x < 0 || x > 0x10ffff) {
13256 PyErr_SetString(PyExc_OverflowError,
13257 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013258 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013259 }
13260
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013261 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013262 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013263
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013265 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013266 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013267 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013268}
13269
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013270static int
13271repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13272{
13273 int r;
13274 assert(count > 0);
13275 assert(PyUnicode_Check(obj));
13276 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013277 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013278 if (repeated == NULL)
13279 return -1;
13280 r = _PyAccu_Accumulate(acc, repeated);
13281 Py_DECREF(repeated);
13282 return r;
13283 }
13284 else {
13285 do {
13286 if (_PyAccu_Accumulate(acc, obj))
13287 return -1;
13288 } while (--count);
13289 return 0;
13290 }
13291}
13292
Alexander Belopolsky40018472011-02-26 01:02:56 +000013293PyObject *
13294PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013295{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013296 void *fmt;
13297 int fmtkind;
13298 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013299 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013300 int r;
13301 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013302 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013303 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013304 PyObject *temp = NULL;
13305 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013306 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013307 _PyAccu acc;
13308 static PyObject *plus, *minus, *blank, *zero, *percent;
13309
13310 if (!plus && !(plus = get_latin1_char('+')))
13311 return NULL;
13312 if (!minus && !(minus = get_latin1_char('-')))
13313 return NULL;
13314 if (!blank && !(blank = get_latin1_char(' ')))
13315 return NULL;
13316 if (!zero && !(zero = get_latin1_char('0')))
13317 return NULL;
13318 if (!percent && !(percent = get_latin1_char('%')))
13319 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013320
Guido van Rossumd57fd912000-03-10 22:53:23 +000013321 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013322 PyErr_BadInternalCall();
13323 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013324 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013325 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013326 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013327 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013328 if (_PyAccu_Init(&acc))
13329 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013330 fmt = PyUnicode_DATA(uformat);
13331 fmtkind = PyUnicode_KIND(uformat);
13332 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13333 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013334
Guido van Rossumd57fd912000-03-10 22:53:23 +000013335 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013336 arglen = PyTuple_Size(args);
13337 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013338 }
13339 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 arglen = -1;
13341 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013342 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013343 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013344 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013345 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013346
13347 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013348 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013349 PyObject *nonfmt;
13350 Py_ssize_t nonfmtpos;
13351 nonfmtpos = fmtpos++;
13352 while (fmtcnt >= 0 &&
13353 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13354 fmtpos++;
13355 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013356 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013357 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
13358 if (nonfmt == NULL)
13359 goto onError;
13360 r = _PyAccu_Accumulate(&acc, nonfmt);
13361 Py_DECREF(nonfmt);
13362 if (r)
13363 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013364 }
13365 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 /* Got a format specifier */
13367 int flags = 0;
13368 Py_ssize_t width = -1;
13369 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013370 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013371 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013372 int isnumok;
13373 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013374 void *pbuf = NULL;
13375 Py_ssize_t pindex, len;
13376 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013377
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013378 fmtpos++;
13379 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13380 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 Py_ssize_t keylen;
13382 PyObject *key;
13383 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013384
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 if (dict == NULL) {
13386 PyErr_SetString(PyExc_TypeError,
13387 "format requires a mapping");
13388 goto onError;
13389 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013390 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013391 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013392 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013393 /* Skip over balanced parentheses */
13394 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013395 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013396 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013397 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013398 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013399 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013400 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013401 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013402 if (fmtcnt < 0 || pcount > 0) {
13403 PyErr_SetString(PyExc_ValueError,
13404 "incomplete format key");
13405 goto onError;
13406 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020013407 key = PyUnicode_Substring((PyObject*)uformat,
13408 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013409 if (key == NULL)
13410 goto onError;
13411 if (args_owned) {
13412 Py_DECREF(args);
13413 args_owned = 0;
13414 }
13415 args = PyObject_GetItem(dict, key);
13416 Py_DECREF(key);
13417 if (args == NULL) {
13418 goto onError;
13419 }
13420 args_owned = 1;
13421 arglen = -1;
13422 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013423 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013424 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013425 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013426 case '-': flags |= F_LJUST; continue;
13427 case '+': flags |= F_SIGN; continue;
13428 case ' ': flags |= F_BLANK; continue;
13429 case '#': flags |= F_ALT; continue;
13430 case '0': flags |= F_ZERO; continue;
13431 }
13432 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013433 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013434 if (c == '*') {
13435 v = getnextarg(args, arglen, &argidx);
13436 if (v == NULL)
13437 goto onError;
13438 if (!PyLong_Check(v)) {
13439 PyErr_SetString(PyExc_TypeError,
13440 "* wants int");
13441 goto onError;
13442 }
13443 width = PyLong_AsLong(v);
13444 if (width == -1 && PyErr_Occurred())
13445 goto onError;
13446 if (width < 0) {
13447 flags |= F_LJUST;
13448 width = -width;
13449 }
13450 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013451 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013452 }
13453 else if (c >= '0' && c <= '9') {
13454 width = c - '0';
13455 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013456 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 if (c < '0' || c > '9')
13458 break;
13459 if ((width*10) / 10 != width) {
13460 PyErr_SetString(PyExc_ValueError,
13461 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013462 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013463 }
13464 width = width*10 + (c - '0');
13465 }
13466 }
13467 if (c == '.') {
13468 prec = 0;
13469 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013470 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013471 if (c == '*') {
13472 v = getnextarg(args, arglen, &argidx);
13473 if (v == NULL)
13474 goto onError;
13475 if (!PyLong_Check(v)) {
13476 PyErr_SetString(PyExc_TypeError,
13477 "* wants int");
13478 goto onError;
13479 }
13480 prec = PyLong_AsLong(v);
13481 if (prec == -1 && PyErr_Occurred())
13482 goto onError;
13483 if (prec < 0)
13484 prec = 0;
13485 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013486 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 }
13488 else if (c >= '0' && c <= '9') {
13489 prec = c - '0';
13490 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013491 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013492 if (c < '0' || c > '9')
13493 break;
13494 if ((prec*10) / 10 != prec) {
13495 PyErr_SetString(PyExc_ValueError,
13496 "prec too big");
13497 goto onError;
13498 }
13499 prec = prec*10 + (c - '0');
13500 }
13501 }
13502 } /* prec */
13503 if (fmtcnt >= 0) {
13504 if (c == 'h' || c == 'l' || c == 'L') {
13505 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013506 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 }
13508 }
13509 if (fmtcnt < 0) {
13510 PyErr_SetString(PyExc_ValueError,
13511 "incomplete format");
13512 goto onError;
13513 }
13514 if (c != '%') {
13515 v = getnextarg(args, arglen, &argidx);
13516 if (v == NULL)
13517 goto onError;
13518 }
13519 sign = 0;
13520 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013521 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 switch (c) {
13523
13524 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013525 _PyAccu_Accumulate(&acc, percent);
13526 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013527
13528 case 's':
13529 case 'r':
13530 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013531 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013532 temp = v;
13533 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013534 }
13535 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013536 if (c == 's')
13537 temp = PyObject_Str(v);
13538 else if (c == 'r')
13539 temp = PyObject_Repr(v);
13540 else
13541 temp = PyObject_ASCII(v);
13542 if (temp == NULL)
13543 goto onError;
13544 if (PyUnicode_Check(temp))
13545 /* nothing to do */;
13546 else {
13547 Py_DECREF(temp);
13548 PyErr_SetString(PyExc_TypeError,
13549 "%s argument has non-string str()");
13550 goto onError;
13551 }
13552 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013553 if (PyUnicode_READY(temp) == -1) {
13554 Py_CLEAR(temp);
13555 goto onError;
13556 }
13557 pbuf = PyUnicode_DATA(temp);
13558 kind = PyUnicode_KIND(temp);
13559 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013560 if (prec >= 0 && len > prec)
13561 len = prec;
13562 break;
13563
13564 case 'i':
13565 case 'd':
13566 case 'u':
13567 case 'o':
13568 case 'x':
13569 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013570 isnumok = 0;
13571 if (PyNumber_Check(v)) {
13572 PyObject *iobj=NULL;
13573
13574 if (PyLong_Check(v)) {
13575 iobj = v;
13576 Py_INCREF(iobj);
13577 }
13578 else {
13579 iobj = PyNumber_Long(v);
13580 }
13581 if (iobj!=NULL) {
13582 if (PyLong_Check(iobj)) {
13583 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013584 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013585 Py_DECREF(iobj);
13586 if (!temp)
13587 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013588 if (PyUnicode_READY(temp) == -1) {
13589 Py_CLEAR(temp);
13590 goto onError;
13591 }
13592 pbuf = PyUnicode_DATA(temp);
13593 kind = PyUnicode_KIND(temp);
13594 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 sign = 1;
13596 }
13597 else {
13598 Py_DECREF(iobj);
13599 }
13600 }
13601 }
13602 if (!isnumok) {
13603 PyErr_Format(PyExc_TypeError,
13604 "%%%c format: a number is required, "
13605 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13606 goto onError;
13607 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013608 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013609 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013610 fillobj = zero;
13611 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013612 break;
13613
13614 case 'e':
13615 case 'E':
13616 case 'f':
13617 case 'F':
13618 case 'g':
13619 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013620 temp = formatfloat(v, flags, prec, c);
13621 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013623 if (PyUnicode_READY(temp) == -1) {
13624 Py_CLEAR(temp);
13625 goto onError;
13626 }
13627 pbuf = PyUnicode_DATA(temp);
13628 kind = PyUnicode_KIND(temp);
13629 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013631 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013633 fillobj = zero;
13634 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 break;
13636
13637 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013638 {
13639 Py_UCS4 ch = formatchar(v);
13640 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013642 temp = _PyUnicode_FromUCS4(&ch, 1);
13643 if (temp == NULL)
13644 goto onError;
13645 pbuf = PyUnicode_DATA(temp);
13646 kind = PyUnicode_KIND(temp);
13647 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013648 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013649 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013650
13651 default:
13652 PyErr_Format(PyExc_ValueError,
13653 "unsupported format character '%c' (0x%x) "
13654 "at index %zd",
13655 (31<=c && c<=126) ? (char)c : '?',
13656 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013657 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013658 goto onError;
13659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013660 /* pbuf is initialized here. */
13661 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013663 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13664 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013665 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013666 pindex++;
13667 }
13668 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13669 signobj = plus;
13670 len--;
13671 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 }
13673 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013674 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013675 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013676 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013677 else
13678 sign = 0;
13679 }
13680 if (width < len)
13681 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013682 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013683 if (fill != ' ') {
13684 assert(signobj != NULL);
13685 if (_PyAccu_Accumulate(&acc, signobj))
13686 goto onError;
13687 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013688 if (width > len)
13689 width--;
13690 }
13691 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013692 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013693 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013694 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013695 second = get_latin1_char(
13696 PyUnicode_READ(kind, pbuf, pindex + 1));
13697 pindex += 2;
13698 if (second == NULL ||
13699 _PyAccu_Accumulate(&acc, zero) ||
13700 _PyAccu_Accumulate(&acc, second))
13701 goto onError;
13702 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013703 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013704 width -= 2;
13705 if (width < 0)
13706 width = 0;
13707 len -= 2;
13708 }
13709 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013710 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013711 if (repeat_accumulate(&acc, fillobj, width - len))
13712 goto onError;
13713 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013714 }
13715 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013716 if (sign) {
13717 assert(signobj != NULL);
13718 if (_PyAccu_Accumulate(&acc, signobj))
13719 goto onError;
13720 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013721 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013722 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13723 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013724 second = get_latin1_char(
13725 PyUnicode_READ(kind, pbuf, pindex + 1));
13726 pindex += 2;
13727 if (second == NULL ||
13728 _PyAccu_Accumulate(&acc, zero) ||
13729 _PyAccu_Accumulate(&acc, second))
13730 goto onError;
13731 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013732 }
13733 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013734 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013735 if (temp != NULL) {
13736 assert(pbuf == PyUnicode_DATA(temp));
13737 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013738 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013739 else {
13740 const char *p = (const char *) pbuf;
13741 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013742 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013743 v = PyUnicode_FromKindAndData(kind, p, len);
13744 }
13745 if (v == NULL)
13746 goto onError;
13747 r = _PyAccu_Accumulate(&acc, v);
13748 Py_DECREF(v);
13749 if (r)
13750 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013751 if (width > len && repeat_accumulate(&acc, blank, width - len))
13752 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013753 if (dict && (argidx < arglen) && c != '%') {
13754 PyErr_SetString(PyExc_TypeError,
13755 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013756 goto onError;
13757 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013758 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013759 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013760 } /* until end */
13761 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013762 PyErr_SetString(PyExc_TypeError,
13763 "not all arguments converted during string formatting");
13764 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013765 }
13766
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013767 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013768 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013769 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013770 }
13771 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013772 Py_XDECREF(temp);
13773 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013774 return (PyObject *)result;
13775
Benjamin Peterson29060642009-01-31 22:14:21 +000013776 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013777 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013778 Py_XDECREF(temp);
13779 Py_XDECREF(second);
13780 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013781 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013782 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013783 }
13784 return NULL;
13785}
13786
Jeremy Hylton938ace62002-07-17 16:30:39 +000013787static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013788unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13789
Tim Peters6d6c1a32001-08-02 04:15:00 +000013790static PyObject *
13791unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13792{
Benjamin Peterson29060642009-01-31 22:14:21 +000013793 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013794 static char *kwlist[] = {"object", "encoding", "errors", 0};
13795 char *encoding = NULL;
13796 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013797
Benjamin Peterson14339b62009-01-31 16:36:08 +000013798 if (type != &PyUnicode_Type)
13799 return unicode_subtype_new(type, args, kwds);
13800 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013801 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013802 return NULL;
13803 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013804 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013805 if (encoding == NULL && errors == NULL)
13806 return PyObject_Str(x);
13807 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013808 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013809}
13810
Guido van Rossume023fe02001-08-30 03:12:59 +000013811static PyObject *
13812unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13813{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013814 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013815 Py_ssize_t length, char_size;
13816 int share_wstr, share_utf8;
13817 unsigned int kind;
13818 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013819
Benjamin Peterson14339b62009-01-31 16:36:08 +000013820 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013821
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013822 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013823 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013824 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013825 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013826 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013827 return NULL;
13828
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013829 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013830 if (self == NULL) {
13831 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013832 return NULL;
13833 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013834 kind = PyUnicode_KIND(unicode);
13835 length = PyUnicode_GET_LENGTH(unicode);
13836
13837 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013838#ifdef Py_DEBUG
13839 _PyUnicode_HASH(self) = -1;
13840#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013841 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013842#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013843 _PyUnicode_STATE(self).interned = 0;
13844 _PyUnicode_STATE(self).kind = kind;
13845 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013846 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013847 _PyUnicode_STATE(self).ready = 1;
13848 _PyUnicode_WSTR(self) = NULL;
13849 _PyUnicode_UTF8_LENGTH(self) = 0;
13850 _PyUnicode_UTF8(self) = NULL;
13851 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013852 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013853
13854 share_utf8 = 0;
13855 share_wstr = 0;
13856 if (kind == PyUnicode_1BYTE_KIND) {
13857 char_size = 1;
13858 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13859 share_utf8 = 1;
13860 }
13861 else if (kind == PyUnicode_2BYTE_KIND) {
13862 char_size = 2;
13863 if (sizeof(wchar_t) == 2)
13864 share_wstr = 1;
13865 }
13866 else {
13867 assert(kind == PyUnicode_4BYTE_KIND);
13868 char_size = 4;
13869 if (sizeof(wchar_t) == 4)
13870 share_wstr = 1;
13871 }
13872
13873 /* Ensure we won't overflow the length. */
13874 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13875 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013876 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013877 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013878 data = PyObject_MALLOC((length + 1) * char_size);
13879 if (data == NULL) {
13880 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013881 goto onError;
13882 }
13883
Victor Stinnerc3c74152011-10-02 20:39:55 +020013884 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013885 if (share_utf8) {
13886 _PyUnicode_UTF8_LENGTH(self) = length;
13887 _PyUnicode_UTF8(self) = data;
13888 }
13889 if (share_wstr) {
13890 _PyUnicode_WSTR_LENGTH(self) = length;
13891 _PyUnicode_WSTR(self) = (wchar_t *)data;
13892 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013893
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013894 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013895 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013896 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013897#ifdef Py_DEBUG
13898 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13899#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013900 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013901 return (PyObject *)self;
13902
13903onError:
13904 Py_DECREF(unicode);
13905 Py_DECREF(self);
13906 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013907}
13908
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013909PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013910 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013911\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013912Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013913encoding defaults to the current default string encoding.\n\
13914errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013915
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013916static PyObject *unicode_iter(PyObject *seq);
13917
Guido van Rossumd57fd912000-03-10 22:53:23 +000013918PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013919 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013920 "str", /* tp_name */
13921 sizeof(PyUnicodeObject), /* tp_size */
13922 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013923 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013924 (destructor)unicode_dealloc, /* tp_dealloc */
13925 0, /* tp_print */
13926 0, /* tp_getattr */
13927 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013928 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013929 unicode_repr, /* tp_repr */
13930 &unicode_as_number, /* tp_as_number */
13931 &unicode_as_sequence, /* tp_as_sequence */
13932 &unicode_as_mapping, /* tp_as_mapping */
13933 (hashfunc) unicode_hash, /* tp_hash*/
13934 0, /* tp_call*/
13935 (reprfunc) unicode_str, /* tp_str */
13936 PyObject_GenericGetAttr, /* tp_getattro */
13937 0, /* tp_setattro */
13938 0, /* tp_as_buffer */
13939 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013940 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013941 unicode_doc, /* tp_doc */
13942 0, /* tp_traverse */
13943 0, /* tp_clear */
13944 PyUnicode_RichCompare, /* tp_richcompare */
13945 0, /* tp_weaklistoffset */
13946 unicode_iter, /* tp_iter */
13947 0, /* tp_iternext */
13948 unicode_methods, /* tp_methods */
13949 0, /* tp_members */
13950 0, /* tp_getset */
13951 &PyBaseObject_Type, /* tp_base */
13952 0, /* tp_dict */
13953 0, /* tp_descr_get */
13954 0, /* tp_descr_set */
13955 0, /* tp_dictoffset */
13956 0, /* tp_init */
13957 0, /* tp_alloc */
13958 unicode_new, /* tp_new */
13959 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013960};
13961
13962/* Initialize the Unicode implementation */
13963
Victor Stinner3a50e702011-10-18 21:21:00 +020013964int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013965{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013966 int i;
13967
Thomas Wouters477c8d52006-05-27 19:21:47 +000013968 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013969 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013970 0x000A, /* LINE FEED */
13971 0x000D, /* CARRIAGE RETURN */
13972 0x001C, /* FILE SEPARATOR */
13973 0x001D, /* GROUP SEPARATOR */
13974 0x001E, /* RECORD SEPARATOR */
13975 0x0085, /* NEXT LINE */
13976 0x2028, /* LINE SEPARATOR */
13977 0x2029, /* PARAGRAPH SEPARATOR */
13978 };
13979
Fred Drakee4315f52000-05-09 19:53:39 +000013980 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013981 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013982 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013983 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013984 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013985
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013986 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013987 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013988 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013989 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013990
13991 /* initialize the linebreak bloom filter */
13992 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013993 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013994 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013995
13996 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013997
13998#ifdef HAVE_MBCS
13999 winver.dwOSVersionInfoSize = sizeof(winver);
14000 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
14001 PyErr_SetFromWindowsErr(0);
14002 return -1;
14003 }
14004#endif
14005 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014006}
14007
14008/* Finalize the Unicode implementation */
14009
Christian Heimesa156e092008-02-16 07:38:31 +000014010int
14011PyUnicode_ClearFreeList(void)
14012{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014013 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000014014}
14015
Guido van Rossumd57fd912000-03-10 22:53:23 +000014016void
Thomas Wouters78890102000-07-22 19:25:51 +000014017_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014018{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014019 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014020
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014021 Py_XDECREF(unicode_empty);
14022 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014023
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014024 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014025 if (unicode_latin1[i]) {
14026 Py_DECREF(unicode_latin1[i]);
14027 unicode_latin1[i] = NULL;
14028 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014029 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014030 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014031 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014032}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014033
Walter Dörwald16807132007-05-25 13:52:07 +000014034void
14035PyUnicode_InternInPlace(PyObject **p)
14036{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014037 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014038 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014039#ifdef Py_DEBUG
14040 assert(s != NULL);
14041 assert(_PyUnicode_CHECK(s));
14042#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014043 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014044 return;
14045#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014046 /* If it's a subclass, we don't really know what putting
14047 it in the interned dict might do. */
14048 if (!PyUnicode_CheckExact(s))
14049 return;
14050 if (PyUnicode_CHECK_INTERNED(s))
14051 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020014052 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014053 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014054 return;
14055 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014056 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 if (interned == NULL) {
14058 interned = PyDict_New();
14059 if (interned == NULL) {
14060 PyErr_Clear(); /* Don't leave an exception */
14061 return;
14062 }
14063 }
14064 /* It might be that the GetItem call fails even
14065 though the key is present in the dictionary,
14066 namely when this happens during a stack overflow. */
14067 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000014068 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014069 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014070
Benjamin Peterson29060642009-01-31 22:14:21 +000014071 if (t) {
14072 Py_INCREF(t);
14073 Py_DECREF(*p);
14074 *p = t;
14075 return;
14076 }
Walter Dörwald16807132007-05-25 13:52:07 +000014077
Benjamin Peterson14339b62009-01-31 16:36:08 +000014078 PyThreadState_GET()->recursion_critical = 1;
14079 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
14080 PyErr_Clear();
14081 PyThreadState_GET()->recursion_critical = 0;
14082 return;
14083 }
14084 PyThreadState_GET()->recursion_critical = 0;
14085 /* The two references in interned are not counted by refcnt.
14086 The deallocator will take care of this */
14087 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014088 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014089}
14090
14091void
14092PyUnicode_InternImmortal(PyObject **p)
14093{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 PyUnicode_InternInPlace(p);
14095 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014096 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014097 Py_INCREF(*p);
14098 }
Walter Dörwald16807132007-05-25 13:52:07 +000014099}
14100
14101PyObject *
14102PyUnicode_InternFromString(const char *cp)
14103{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014104 PyObject *s = PyUnicode_FromString(cp);
14105 if (s == NULL)
14106 return NULL;
14107 PyUnicode_InternInPlace(&s);
14108 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014109}
14110
Alexander Belopolsky40018472011-02-26 01:02:56 +000014111void
14112_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014113{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014114 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014115 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014116 Py_ssize_t i, n;
14117 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014118
Benjamin Peterson14339b62009-01-31 16:36:08 +000014119 if (interned == NULL || !PyDict_Check(interned))
14120 return;
14121 keys = PyDict_Keys(interned);
14122 if (keys == NULL || !PyList_Check(keys)) {
14123 PyErr_Clear();
14124 return;
14125 }
Walter Dörwald16807132007-05-25 13:52:07 +000014126
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14128 detector, interned unicode strings are not forcibly deallocated;
14129 rather, we give them their stolen references back, and then clear
14130 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014131
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 n = PyList_GET_SIZE(keys);
14133 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014134 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014136 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014137 if (PyUnicode_READY(s) == -1) {
14138 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014139 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014140 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014141 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014142 case SSTATE_NOT_INTERNED:
14143 /* XXX Shouldn't happen */
14144 break;
14145 case SSTATE_INTERNED_IMMORTAL:
14146 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014147 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014148 break;
14149 case SSTATE_INTERNED_MORTAL:
14150 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014151 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014152 break;
14153 default:
14154 Py_FatalError("Inconsistent interned string state.");
14155 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014156 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014157 }
14158 fprintf(stderr, "total size of all interned strings: "
14159 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14160 "mortal/immortal\n", mortal_size, immortal_size);
14161 Py_DECREF(keys);
14162 PyDict_Clear(interned);
14163 Py_DECREF(interned);
14164 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014165}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014166
14167
14168/********************* Unicode Iterator **************************/
14169
14170typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014171 PyObject_HEAD
14172 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014173 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014174} unicodeiterobject;
14175
14176static void
14177unicodeiter_dealloc(unicodeiterobject *it)
14178{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014179 _PyObject_GC_UNTRACK(it);
14180 Py_XDECREF(it->it_seq);
14181 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014182}
14183
14184static int
14185unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14186{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014187 Py_VISIT(it->it_seq);
14188 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014189}
14190
14191static PyObject *
14192unicodeiter_next(unicodeiterobject *it)
14193{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014194 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014195
Benjamin Peterson14339b62009-01-31 16:36:08 +000014196 assert(it != NULL);
14197 seq = it->it_seq;
14198 if (seq == NULL)
14199 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014200 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014202 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14203 int kind = PyUnicode_KIND(seq);
14204 void *data = PyUnicode_DATA(seq);
14205 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14206 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014207 if (item != NULL)
14208 ++it->it_index;
14209 return item;
14210 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014211
Benjamin Peterson14339b62009-01-31 16:36:08 +000014212 Py_DECREF(seq);
14213 it->it_seq = NULL;
14214 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014215}
14216
14217static PyObject *
14218unicodeiter_len(unicodeiterobject *it)
14219{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014220 Py_ssize_t len = 0;
14221 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014222 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014223 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014224}
14225
14226PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14227
14228static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014229 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014230 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014231 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014232};
14233
14234PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014235 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14236 "str_iterator", /* tp_name */
14237 sizeof(unicodeiterobject), /* tp_basicsize */
14238 0, /* tp_itemsize */
14239 /* methods */
14240 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14241 0, /* tp_print */
14242 0, /* tp_getattr */
14243 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014244 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014245 0, /* tp_repr */
14246 0, /* tp_as_number */
14247 0, /* tp_as_sequence */
14248 0, /* tp_as_mapping */
14249 0, /* tp_hash */
14250 0, /* tp_call */
14251 0, /* tp_str */
14252 PyObject_GenericGetAttr, /* tp_getattro */
14253 0, /* tp_setattro */
14254 0, /* tp_as_buffer */
14255 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14256 0, /* tp_doc */
14257 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14258 0, /* tp_clear */
14259 0, /* tp_richcompare */
14260 0, /* tp_weaklistoffset */
14261 PyObject_SelfIter, /* tp_iter */
14262 (iternextfunc)unicodeiter_next, /* tp_iternext */
14263 unicodeiter_methods, /* tp_methods */
14264 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014265};
14266
14267static PyObject *
14268unicode_iter(PyObject *seq)
14269{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014270 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014271
Benjamin Peterson14339b62009-01-31 16:36:08 +000014272 if (!PyUnicode_Check(seq)) {
14273 PyErr_BadInternalCall();
14274 return NULL;
14275 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014276 if (PyUnicode_READY(seq) == -1)
14277 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014278 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14279 if (it == NULL)
14280 return NULL;
14281 it->it_index = 0;
14282 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014283 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014284 _PyObject_GC_TRACK(it);
14285 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014286}
14287
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014288
14289size_t
14290Py_UNICODE_strlen(const Py_UNICODE *u)
14291{
14292 int res = 0;
14293 while(*u++)
14294 res++;
14295 return res;
14296}
14297
14298Py_UNICODE*
14299Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14300{
14301 Py_UNICODE *u = s1;
14302 while ((*u++ = *s2++));
14303 return s1;
14304}
14305
14306Py_UNICODE*
14307Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14308{
14309 Py_UNICODE *u = s1;
14310 while ((*u++ = *s2++))
14311 if (n-- == 0)
14312 break;
14313 return s1;
14314}
14315
14316Py_UNICODE*
14317Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14318{
14319 Py_UNICODE *u1 = s1;
14320 u1 += Py_UNICODE_strlen(u1);
14321 Py_UNICODE_strcpy(u1, s2);
14322 return s1;
14323}
14324
14325int
14326Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14327{
14328 while (*s1 && *s2 && *s1 == *s2)
14329 s1++, s2++;
14330 if (*s1 && *s2)
14331 return (*s1 < *s2) ? -1 : +1;
14332 if (*s1)
14333 return 1;
14334 if (*s2)
14335 return -1;
14336 return 0;
14337}
14338
14339int
14340Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14341{
14342 register Py_UNICODE u1, u2;
14343 for (; n != 0; n--) {
14344 u1 = *s1;
14345 u2 = *s2;
14346 if (u1 != u2)
14347 return (u1 < u2) ? -1 : +1;
14348 if (u1 == '\0')
14349 return 0;
14350 s1++;
14351 s2++;
14352 }
14353 return 0;
14354}
14355
14356Py_UNICODE*
14357Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14358{
14359 const Py_UNICODE *p;
14360 for (p = s; *p; p++)
14361 if (*p == c)
14362 return (Py_UNICODE*)p;
14363 return NULL;
14364}
14365
14366Py_UNICODE*
14367Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14368{
14369 const Py_UNICODE *p;
14370 p = s + Py_UNICODE_strlen(s);
14371 while (p != s) {
14372 p--;
14373 if (*p == c)
14374 return (Py_UNICODE*)p;
14375 }
14376 return NULL;
14377}
Victor Stinner331ea922010-08-10 16:37:20 +000014378
Victor Stinner71133ff2010-09-01 23:43:53 +000014379Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014380PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014381{
Victor Stinner577db2c2011-10-11 22:12:48 +020014382 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014383 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014385 if (!PyUnicode_Check(unicode)) {
14386 PyErr_BadArgument();
14387 return NULL;
14388 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014389 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014390 if (u == NULL)
14391 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014392 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014393 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014394 PyErr_NoMemory();
14395 return NULL;
14396 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014397 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014398 size *= sizeof(Py_UNICODE);
14399 copy = PyMem_Malloc(size);
14400 if (copy == NULL) {
14401 PyErr_NoMemory();
14402 return NULL;
14403 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014404 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014405 return copy;
14406}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014407
Georg Brandl66c221e2010-10-14 07:04:07 +000014408/* A _string module, to export formatter_parser and formatter_field_name_split
14409 to the string.Formatter class implemented in Python. */
14410
14411static PyMethodDef _string_methods[] = {
14412 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14413 METH_O, PyDoc_STR("split the argument as a field name")},
14414 {"formatter_parser", (PyCFunction) formatter_parser,
14415 METH_O, PyDoc_STR("parse the argument as a format string")},
14416 {NULL, NULL}
14417};
14418
14419static struct PyModuleDef _string_module = {
14420 PyModuleDef_HEAD_INIT,
14421 "_string",
14422 PyDoc_STR("string helper module"),
14423 0,
14424 _string_methods,
14425 NULL,
14426 NULL,
14427 NULL,
14428 NULL
14429};
14430
14431PyMODINIT_FUNC
14432PyInit__string(void)
14433{
14434 return PyModule_Create(&_string_module);
14435}
14436
14437
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014438#ifdef __cplusplus
14439}
14440#endif