blob: 8b33f4495c5b393d356029e28f76b93b4e9a0950 [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 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(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 Stinner7931d9a2011-11-04 00:22:48 +0100311_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200312{
313 PyASCIIObject *ascii;
314 unsigned int kind;
315
316 assert(PyUnicode_Check(op));
317
318 ascii = (PyASCIIObject *)op;
319 kind = ascii->state.kind;
320
Victor Stinnera3b334d2011-10-03 13:53:37 +0200321 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200322 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200323 assert(ascii->state.ready == 1);
324 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200325 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200326 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200327 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200328
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 if (ascii->state.compact == 1) {
330 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200331 assert(kind == PyUnicode_1BYTE_KIND
332 || kind == PyUnicode_2BYTE_KIND
333 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200334 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200335 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200336 assert (compact->utf8 != data);
337 } else {
338 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
339
340 data = unicode->data.any;
341 if (kind == PyUnicode_WCHAR_KIND) {
342 assert(ascii->state.compact == 0);
343 assert(ascii->state.ascii == 0);
344 assert(ascii->state.ready == 0);
345 assert(ascii->wstr != NULL);
346 assert(data == NULL);
347 assert(compact->utf8 == NULL);
348 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
349 }
350 else {
351 assert(kind == PyUnicode_1BYTE_KIND
352 || kind == PyUnicode_2BYTE_KIND
353 || kind == PyUnicode_4BYTE_KIND);
354 assert(ascii->state.compact == 0);
355 assert(ascii->state.ready == 1);
356 assert(data != NULL);
357 if (ascii->state.ascii) {
358 assert (compact->utf8 == data);
359 assert (compact->utf8_length == ascii->length);
360 }
361 else
362 assert (compact->utf8 != data);
363 }
364 }
365 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200366 if (
367#if SIZEOF_WCHAR_T == 2
368 kind == PyUnicode_2BYTE_KIND
369#else
370 kind == PyUnicode_4BYTE_KIND
371#endif
372 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200373 {
374 assert(ascii->wstr == data);
375 assert(compact->wstr_length == ascii->length);
376 } else
377 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200378 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200379
380 if (compact->utf8 == NULL)
381 assert(compact->utf8_length == 0);
382 if (ascii->wstr == NULL)
383 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200384 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200385 /* check that the best kind is used */
386 if (check_content && kind != PyUnicode_WCHAR_KIND)
387 {
388 Py_ssize_t i;
389 Py_UCS4 maxchar = 0;
390 void *data = PyUnicode_DATA(ascii);
391 for (i=0; i < ascii->length; i++)
392 {
393 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
394 if (ch > maxchar)
395 maxchar = ch;
396 }
397 if (kind == PyUnicode_1BYTE_KIND) {
398 if (ascii->state.ascii == 0)
399 assert(maxchar >= 128);
400 else
401 assert(maxchar < 128);
402 }
403 else if (kind == PyUnicode_2BYTE_KIND)
404 assert(maxchar >= 0x100);
405 else
406 assert(maxchar >= 0x10000);
407 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100408 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200409 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400410 return 1;
411}
Victor Stinner910337b2011-10-03 03:20:16 +0200412#endif
413
Victor Stinner3a50e702011-10-18 21:21:00 +0200414#ifdef HAVE_MBCS
415static OSVERSIONINFOEX winver;
416#endif
417
Thomas Wouters477c8d52006-05-27 19:21:47 +0000418/* --- Bloom Filters ----------------------------------------------------- */
419
420/* stuff to implement simple "bloom filters" for Unicode characters.
421 to keep things simple, we use a single bitmask, using the least 5
422 bits from each unicode characters as the bit index. */
423
424/* the linebreak mask is set up by Unicode_Init below */
425
Antoine Pitrouf068f942010-01-13 14:19:12 +0000426#if LONG_BIT >= 128
427#define BLOOM_WIDTH 128
428#elif LONG_BIT >= 64
429#define BLOOM_WIDTH 64
430#elif LONG_BIT >= 32
431#define BLOOM_WIDTH 32
432#else
433#error "LONG_BIT is smaller than 32"
434#endif
435
Thomas Wouters477c8d52006-05-27 19:21:47 +0000436#define BLOOM_MASK unsigned long
437
438static BLOOM_MASK bloom_linebreak;
439
Antoine Pitrouf068f942010-01-13 14:19:12 +0000440#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
441#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000442
Benjamin Peterson29060642009-01-31 22:14:21 +0000443#define BLOOM_LINEBREAK(ch) \
444 ((ch) < 128U ? ascii_linebreak[(ch)] : \
445 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446
Alexander Belopolsky40018472011-02-26 01:02:56 +0000447Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200448make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000449{
450 /* calculate simple bloom-style bitmask for a given unicode string */
451
Antoine Pitrouf068f942010-01-13 14:19:12 +0000452 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000453 Py_ssize_t i;
454
455 mask = 0;
456 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200457 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000458
459 return mask;
460}
461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200462#define BLOOM_MEMBER(mask, chr, str) \
463 (BLOOM(mask, chr) \
464 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000465
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200466/* Compilation of templated routines */
467
468#include "stringlib/asciilib.h"
469#include "stringlib/fastsearch.h"
470#include "stringlib/partition.h"
471#include "stringlib/split.h"
472#include "stringlib/count.h"
473#include "stringlib/find.h"
474#include "stringlib/find_max_char.h"
475#include "stringlib/localeutil.h"
476#include "stringlib/undef.h"
477
478#include "stringlib/ucs1lib.h"
479#include "stringlib/fastsearch.h"
480#include "stringlib/partition.h"
481#include "stringlib/split.h"
482#include "stringlib/count.h"
483#include "stringlib/find.h"
484#include "stringlib/find_max_char.h"
485#include "stringlib/localeutil.h"
486#include "stringlib/undef.h"
487
488#include "stringlib/ucs2lib.h"
489#include "stringlib/fastsearch.h"
490#include "stringlib/partition.h"
491#include "stringlib/split.h"
492#include "stringlib/count.h"
493#include "stringlib/find.h"
494#include "stringlib/find_max_char.h"
495#include "stringlib/localeutil.h"
496#include "stringlib/undef.h"
497
498#include "stringlib/ucs4lib.h"
499#include "stringlib/fastsearch.h"
500#include "stringlib/partition.h"
501#include "stringlib/split.h"
502#include "stringlib/count.h"
503#include "stringlib/find.h"
504#include "stringlib/find_max_char.h"
505#include "stringlib/localeutil.h"
506#include "stringlib/undef.h"
507
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200508#include "stringlib/unicodedefs.h"
509#include "stringlib/fastsearch.h"
510#include "stringlib/count.h"
511#include "stringlib/find.h"
512
Guido van Rossumd57fd912000-03-10 22:53:23 +0000513/* --- Unicode Object ----------------------------------------------------- */
514
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200515static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200516fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200517
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200518Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
519 Py_ssize_t size, Py_UCS4 ch,
520 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200521{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200522 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
523
524 switch (kind) {
525 case PyUnicode_1BYTE_KIND:
526 {
527 Py_UCS1 ch1 = (Py_UCS1) ch;
528 if (ch1 == ch)
529 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
530 else
531 return -1;
532 }
533 case PyUnicode_2BYTE_KIND:
534 {
535 Py_UCS2 ch2 = (Py_UCS2) ch;
536 if (ch2 == ch)
537 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
538 else
539 return -1;
540 }
541 case PyUnicode_4BYTE_KIND:
542 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
543 default:
544 assert(0);
545 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200546 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200547}
548
Victor Stinnerfe226c02011-10-03 03:52:20 +0200549static PyObject*
550resize_compact(PyObject *unicode, Py_ssize_t length)
551{
552 Py_ssize_t char_size;
553 Py_ssize_t struct_size;
554 Py_ssize_t new_size;
555 int share_wstr;
556
557 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200558 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200559 if (PyUnicode_IS_COMPACT_ASCII(unicode))
560 struct_size = sizeof(PyASCIIObject);
561 else
562 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200563 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200564
565 _Py_DEC_REFTOTAL;
566 _Py_ForgetReference(unicode);
567
568 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
569 PyErr_NoMemory();
570 return NULL;
571 }
572 new_size = (struct_size + (length + 1) * char_size);
573
574 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
575 if (unicode == NULL) {
576 PyObject_Del(unicode);
577 PyErr_NoMemory();
578 return NULL;
579 }
580 _Py_NewReference(unicode);
581 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200582 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200583 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200584 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
585 _PyUnicode_WSTR_LENGTH(unicode) = length;
586 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200587 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
588 length, 0);
589 return unicode;
590}
591
Alexander Belopolsky40018472011-02-26 01:02:56 +0000592static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200593resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000594{
Victor Stinner95663112011-10-04 01:03:50 +0200595 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200596 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000598
Victor Stinner95663112011-10-04 01:03:50 +0200599 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200600
601 if (PyUnicode_IS_READY(unicode)) {
602 Py_ssize_t char_size;
603 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200604 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200605 void *data;
606
607 data = _PyUnicode_DATA_ANY(unicode);
608 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200609 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200610 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
611 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200612 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
613 {
614 PyObject_DEL(_PyUnicode_UTF8(unicode));
615 _PyUnicode_UTF8(unicode) = NULL;
616 _PyUnicode_UTF8_LENGTH(unicode) = 0;
617 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200618
619 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
620 PyErr_NoMemory();
621 return -1;
622 }
623 new_size = (length + 1) * char_size;
624
625 data = (PyObject *)PyObject_REALLOC(data, new_size);
626 if (data == NULL) {
627 PyErr_NoMemory();
628 return -1;
629 }
630 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200631 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200632 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200633 _PyUnicode_WSTR_LENGTH(unicode) = length;
634 }
635 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200636 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200637 _PyUnicode_UTF8_LENGTH(unicode) = length;
638 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200639 _PyUnicode_LENGTH(unicode) = length;
640 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200641 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200642 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200643 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200644 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200645 }
Victor Stinner95663112011-10-04 01:03:50 +0200646 assert(_PyUnicode_WSTR(unicode) != NULL);
647
648 /* check for integer overflow */
649 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
650 PyErr_NoMemory();
651 return -1;
652 }
653 wstr = _PyUnicode_WSTR(unicode);
654 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
655 if (!wstr) {
656 PyErr_NoMemory();
657 return -1;
658 }
659 _PyUnicode_WSTR(unicode) = wstr;
660 _PyUnicode_WSTR(unicode)[length] = 0;
661 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200662 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000663 return 0;
664}
665
Victor Stinnerfe226c02011-10-03 03:52:20 +0200666static PyObject*
667resize_copy(PyObject *unicode, Py_ssize_t length)
668{
669 Py_ssize_t copy_length;
670 if (PyUnicode_IS_COMPACT(unicode)) {
671 PyObject *copy;
672 assert(PyUnicode_IS_READY(unicode));
673
674 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
675 if (copy == NULL)
676 return NULL;
677
678 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200679 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200680 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200681 }
682 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 assert(_PyUnicode_WSTR(unicode) != NULL);
685 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200686 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200687 if (w == NULL)
688 return NULL;
689 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
690 copy_length = Py_MIN(copy_length, length);
691 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
692 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200693 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200694 }
695}
696
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000698 Ux0000 terminated; some code (e.g. new_identifier)
699 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000702 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000703
704*/
705
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200706#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200707static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200708#endif
709
Alexander Belopolsky40018472011-02-26 01:02:56 +0000710static PyUnicodeObject *
711_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712{
713 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200714 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000715
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 if (length == 0 && unicode_empty != NULL) {
718 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200719 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000720 }
721
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000722 /* Ensure we won't overflow the size. */
723 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
724 return (PyUnicodeObject *)PyErr_NoMemory();
725 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200726 if (length < 0) {
727 PyErr_SetString(PyExc_SystemError,
728 "Negative size passed to _PyUnicode_New");
729 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000730 }
731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200732#ifdef Py_DEBUG
733 ++unicode_old_new_calls;
734#endif
735
736 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
737 if (unicode == NULL)
738 return NULL;
739 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
740 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
741 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000742 PyErr_NoMemory();
743 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200745
Jeremy Hyltond8082792003-09-16 19:41:39 +0000746 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000747 * the caller fails before initializing str -- unicode_resize()
748 * reads str[0], and the Keep-Alive optimization can keep memory
749 * allocated for str alive across a call to unicode_dealloc(unicode).
750 * We don't want unicode_resize to read uninitialized memory in
751 * that case.
752 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200753 _PyUnicode_WSTR(unicode)[0] = 0;
754 _PyUnicode_WSTR(unicode)[length] = 0;
755 _PyUnicode_WSTR_LENGTH(unicode) = length;
756 _PyUnicode_HASH(unicode) = -1;
757 _PyUnicode_STATE(unicode).interned = 0;
758 _PyUnicode_STATE(unicode).kind = 0;
759 _PyUnicode_STATE(unicode).compact = 0;
760 _PyUnicode_STATE(unicode).ready = 0;
761 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200762 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200763 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200764 _PyUnicode_UTF8(unicode) = NULL;
765 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100766 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000767 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000768
Benjamin Peterson29060642009-01-31 22:14:21 +0000769 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000770 /* XXX UNREF/NEWREF interface should be more symmetrical */
771 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000772 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000773 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000774 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000775}
776
Victor Stinnerf42dc442011-10-02 23:33:16 +0200777static const char*
778unicode_kind_name(PyObject *unicode)
779{
Victor Stinner42dfd712011-10-03 14:41:45 +0200780 /* don't check consistency: unicode_kind_name() is called from
781 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200782 if (!PyUnicode_IS_COMPACT(unicode))
783 {
784 if (!PyUnicode_IS_READY(unicode))
785 return "wstr";
786 switch(PyUnicode_KIND(unicode))
787 {
788 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200789 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200790 return "legacy ascii";
791 else
792 return "legacy latin1";
793 case PyUnicode_2BYTE_KIND:
794 return "legacy UCS2";
795 case PyUnicode_4BYTE_KIND:
796 return "legacy UCS4";
797 default:
798 return "<legacy invalid kind>";
799 }
800 }
801 assert(PyUnicode_IS_READY(unicode));
802 switch(PyUnicode_KIND(unicode))
803 {
804 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 return "ascii";
807 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200808 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200809 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200810 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200811 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200812 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200813 default:
814 return "<invalid compact kind>";
815 }
816}
817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200818#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200819static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200820
821/* Functions wrapping macros for use in debugger */
822char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200823 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200824}
825
826void *_PyUnicode_compact_data(void *unicode) {
827 return _PyUnicode_COMPACT_DATA(unicode);
828}
829void *_PyUnicode_data(void *unicode){
830 printf("obj %p\n", unicode);
831 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
832 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
833 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
834 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
835 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
836 return PyUnicode_DATA(unicode);
837}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200838
839void
840_PyUnicode_Dump(PyObject *op)
841{
842 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200843 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
844 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
845 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200846
Victor Stinnera849a4b2011-10-03 12:12:11 +0200847 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200848 {
849 if (ascii->state.ascii)
850 data = (ascii + 1);
851 else
852 data = (compact + 1);
853 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200854 else
855 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200856 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
857
Victor Stinnera849a4b2011-10-03 12:12:11 +0200858 if (ascii->wstr == data)
859 printf("shared ");
860 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200861
Victor Stinnera3b334d2011-10-03 13:53:37 +0200862 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200863 printf(" (%zu), ", compact->wstr_length);
864 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
865 printf("shared ");
866 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200867 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200868 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200869}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200870#endif
871
872PyObject *
873PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
874{
875 PyObject *obj;
876 PyCompactUnicodeObject *unicode;
877 void *data;
878 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200879 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200880 Py_ssize_t char_size;
881 Py_ssize_t struct_size;
882
883 /* Optimization for empty strings */
884 if (size == 0 && unicode_empty != NULL) {
885 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200886 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200887 }
888
889#ifdef Py_DEBUG
890 ++unicode_new_new_calls;
891#endif
892
Victor Stinner9e9d6892011-10-04 01:02:02 +0200893 is_ascii = 0;
894 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200895 struct_size = sizeof(PyCompactUnicodeObject);
896 if (maxchar < 128) {
897 kind_state = PyUnicode_1BYTE_KIND;
898 char_size = 1;
899 is_ascii = 1;
900 struct_size = sizeof(PyASCIIObject);
901 }
902 else if (maxchar < 256) {
903 kind_state = PyUnicode_1BYTE_KIND;
904 char_size = 1;
905 }
906 else if (maxchar < 65536) {
907 kind_state = PyUnicode_2BYTE_KIND;
908 char_size = 2;
909 if (sizeof(wchar_t) == 2)
910 is_sharing = 1;
911 }
912 else {
913 kind_state = PyUnicode_4BYTE_KIND;
914 char_size = 4;
915 if (sizeof(wchar_t) == 4)
916 is_sharing = 1;
917 }
918
919 /* Ensure we won't overflow the size. */
920 if (size < 0) {
921 PyErr_SetString(PyExc_SystemError,
922 "Negative size passed to PyUnicode_New");
923 return NULL;
924 }
925 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
926 return PyErr_NoMemory();
927
928 /* Duplicated allocation code from _PyObject_New() instead of a call to
929 * PyObject_New() so we are able to allocate space for the object and
930 * it's data buffer.
931 */
932 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
933 if (obj == NULL)
934 return PyErr_NoMemory();
935 obj = PyObject_INIT(obj, &PyUnicode_Type);
936 if (obj == NULL)
937 return NULL;
938
939 unicode = (PyCompactUnicodeObject *)obj;
940 if (is_ascii)
941 data = ((PyASCIIObject*)obj) + 1;
942 else
943 data = unicode + 1;
944 _PyUnicode_LENGTH(unicode) = size;
945 _PyUnicode_HASH(unicode) = -1;
946 _PyUnicode_STATE(unicode).interned = 0;
947 _PyUnicode_STATE(unicode).kind = kind_state;
948 _PyUnicode_STATE(unicode).compact = 1;
949 _PyUnicode_STATE(unicode).ready = 1;
950 _PyUnicode_STATE(unicode).ascii = is_ascii;
951 if (is_ascii) {
952 ((char*)data)[size] = 0;
953 _PyUnicode_WSTR(unicode) = NULL;
954 }
955 else if (kind_state == PyUnicode_1BYTE_KIND) {
956 ((char*)data)[size] = 0;
957 _PyUnicode_WSTR(unicode) = NULL;
958 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200959 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200960 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200961 }
962 else {
963 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200964 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200965 if (kind_state == PyUnicode_2BYTE_KIND)
966 ((Py_UCS2*)data)[size] = 0;
967 else /* kind_state == PyUnicode_4BYTE_KIND */
968 ((Py_UCS4*)data)[size] = 0;
969 if (is_sharing) {
970 _PyUnicode_WSTR_LENGTH(unicode) = size;
971 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
972 }
973 else {
974 _PyUnicode_WSTR_LENGTH(unicode) = 0;
975 _PyUnicode_WSTR(unicode) = NULL;
976 }
977 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100978 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200979 return obj;
980}
981
982#if SIZEOF_WCHAR_T == 2
983/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
984 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200985 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200986
987 This function assumes that unicode can hold one more code point than wstr
988 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200989static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200990unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200991 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200992{
993 const wchar_t *iter;
994 Py_UCS4 *ucs4_out;
995
Victor Stinner910337b2011-10-03 03:20:16 +0200996 assert(unicode != NULL);
997 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200998 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
999 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1000
1001 for (iter = begin; iter < end; ) {
1002 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1003 _PyUnicode_GET_LENGTH(unicode)));
1004 if (*iter >= 0xD800 && *iter <= 0xDBFF
1005 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1006 {
1007 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1008 iter += 2;
1009 }
1010 else {
1011 *ucs4_out++ = *iter;
1012 iter++;
1013 }
1014 }
1015 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1016 _PyUnicode_GET_LENGTH(unicode)));
1017
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001018}
1019#endif
1020
Victor Stinnercd9950f2011-10-02 00:34:53 +02001021static int
1022_PyUnicode_Dirty(PyObject *unicode)
1023{
Victor Stinner910337b2011-10-03 03:20:16 +02001024 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001025 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001026 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001027 "Cannot modify a string having more than 1 reference");
1028 return -1;
1029 }
1030 _PyUnicode_DIRTY(unicode);
1031 return 0;
1032}
1033
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001034static int
1035_copy_characters(PyObject *to, Py_ssize_t to_start,
1036 PyObject *from, Py_ssize_t from_start,
1037 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001038{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001039 unsigned int from_kind, to_kind;
1040 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001041 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001042
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001043 assert(PyUnicode_Check(from));
1044 assert(PyUnicode_Check(to));
1045 assert(PyUnicode_IS_READY(from));
1046 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001047
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001048 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1049 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1050 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001051
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001052 if (how_many == 0)
1053 return 0;
1054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001055 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001056 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001057 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001058 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001059
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001060#ifdef Py_DEBUG
1061 if (!check_maxchar
1062 && (from_kind > to_kind
1063 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001064 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001065 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1066 Py_UCS4 ch;
1067 Py_ssize_t i;
1068 for (i=0; i < how_many; i++) {
1069 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1070 assert(ch <= to_maxchar);
1071 }
1072 }
1073#endif
1074 fast = (from_kind == to_kind);
1075 if (check_maxchar
1076 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1077 {
1078 /* deny latin1 => ascii */
1079 fast = 0;
1080 }
1081
1082 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001083 Py_MEMCPY((char*)to_data + to_kind * to_start,
1084 (char*)from_data + from_kind * from_start,
1085 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001086 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001087 else if (from_kind == PyUnicode_1BYTE_KIND
1088 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001089 {
1090 _PyUnicode_CONVERT_BYTES(
1091 Py_UCS1, Py_UCS2,
1092 PyUnicode_1BYTE_DATA(from) + from_start,
1093 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1094 PyUnicode_2BYTE_DATA(to) + to_start
1095 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001096 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001097 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001098 && to_kind == PyUnicode_4BYTE_KIND)
1099 {
1100 _PyUnicode_CONVERT_BYTES(
1101 Py_UCS1, Py_UCS4,
1102 PyUnicode_1BYTE_DATA(from) + from_start,
1103 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1104 PyUnicode_4BYTE_DATA(to) + to_start
1105 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001106 }
1107 else if (from_kind == PyUnicode_2BYTE_KIND
1108 && to_kind == PyUnicode_4BYTE_KIND)
1109 {
1110 _PyUnicode_CONVERT_BYTES(
1111 Py_UCS2, Py_UCS4,
1112 PyUnicode_2BYTE_DATA(from) + from_start,
1113 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1114 PyUnicode_4BYTE_DATA(to) + to_start
1115 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001116 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001117 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001118 /* check if max_char(from substring) <= max_char(to) */
1119 if (from_kind > to_kind
1120 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001121 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001122 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 /* slow path to check for character overflow */
1124 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001125 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 Py_ssize_t i;
1127
Victor Stinner56c161a2011-10-06 02:47:11 +02001128#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 for (i=0; i < how_many; i++) {
1130 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001131 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001132 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1133 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001134#else
1135 if (!check_maxchar) {
1136 for (i=0; i < how_many; i++) {
1137 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1138 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1139 }
1140 }
1141 else {
1142 for (i=0; i < how_many; i++) {
1143 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1144 if (ch > to_maxchar)
1145 return 1;
1146 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1147 }
1148 }
1149#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001150 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001151 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001152 assert(0 && "inconsistent state");
1153 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001154 }
1155 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001156 return 0;
1157}
1158
1159static void
1160copy_characters(PyObject *to, Py_ssize_t to_start,
1161 PyObject *from, Py_ssize_t from_start,
1162 Py_ssize_t how_many)
1163{
1164 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1165}
1166
1167Py_ssize_t
1168PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1169 PyObject *from, Py_ssize_t from_start,
1170 Py_ssize_t how_many)
1171{
1172 int err;
1173
1174 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1175 PyErr_BadInternalCall();
1176 return -1;
1177 }
1178
1179 if (PyUnicode_READY(from))
1180 return -1;
1181 if (PyUnicode_READY(to))
1182 return -1;
1183
1184 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1185 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1186 PyErr_Format(PyExc_SystemError,
1187 "Cannot write %zi characters at %zi "
1188 "in a string of %zi characters",
1189 how_many, to_start, PyUnicode_GET_LENGTH(to));
1190 return -1;
1191 }
1192
1193 if (how_many == 0)
1194 return 0;
1195
1196 if (_PyUnicode_Dirty(to))
1197 return -1;
1198
1199 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1200 if (err) {
1201 PyErr_Format(PyExc_SystemError,
1202 "Cannot copy %s characters "
1203 "into a string of %s characters",
1204 unicode_kind_name(from),
1205 unicode_kind_name(to));
1206 return -1;
1207 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001208 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001209}
1210
Victor Stinner17222162011-09-28 22:15:37 +02001211/* Find the maximum code point and count the number of surrogate pairs so a
1212 correct string length can be computed before converting a string to UCS4.
1213 This function counts single surrogates as a character and not as a pair.
1214
1215 Return 0 on success, or -1 on error. */
1216static int
1217find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1218 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001219{
1220 const wchar_t *iter;
1221
Victor Stinnerc53be962011-10-02 21:33:54 +02001222 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001223 *num_surrogates = 0;
1224 *maxchar = 0;
1225
1226 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001227 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001228 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001229#if SIZEOF_WCHAR_T != 2
1230 if (*maxchar >= 0x10000)
1231 return 0;
1232#endif
1233 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001234#if SIZEOF_WCHAR_T == 2
1235 if (*iter >= 0xD800 && *iter <= 0xDBFF
1236 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1237 {
1238 Py_UCS4 surrogate_val;
1239 surrogate_val = (((iter[0] & 0x3FF)<<10)
1240 | (iter[1] & 0x3FF)) + 0x10000;
1241 ++(*num_surrogates);
1242 if (surrogate_val > *maxchar)
1243 *maxchar = surrogate_val;
1244 iter += 2;
1245 }
1246 else
1247 iter++;
1248#else
1249 iter++;
1250#endif
1251 }
1252 return 0;
1253}
1254
1255#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001256static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001257#endif
1258
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001259static int
1260unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001261{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001262 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001263 wchar_t *end;
1264 Py_UCS4 maxchar = 0;
1265 Py_ssize_t num_surrogates;
1266#if SIZEOF_WCHAR_T == 2
1267 Py_ssize_t length_wo_surrogates;
1268#endif
1269
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001270 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001271 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001272
Georg Brandl7597add2011-10-05 16:36:47 +02001273 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001274 strings were created using _PyObject_New() and where no canonical
1275 representation (the str field) has been set yet aka strings
1276 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001277 assert(_PyUnicode_CHECK(unicode));
1278 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001279 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001280 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001281 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001282 /* Actually, it should neither be interned nor be anything else: */
1283 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001284
1285#ifdef Py_DEBUG
1286 ++unicode_ready_calls;
1287#endif
1288
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001289#ifdef Py_DEBUG
1290 assert(!replace || Py_REFCNT(unicode) == 1);
1291#else
1292 if (replace && Py_REFCNT(unicode) != 1)
1293 replace = 0;
1294#endif
1295 if (replace) {
1296 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1297 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1298 /* Optimization for empty strings */
1299 if (len == 0) {
1300 Py_INCREF(unicode_empty);
1301 Py_DECREF(*p_obj);
1302 *p_obj = unicode_empty;
1303 return 0;
1304 }
1305 if (len == 1 && wstr[0] < 256) {
1306 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1307 if (latin1_char == NULL)
1308 return -1;
1309 Py_DECREF(*p_obj);
1310 *p_obj = latin1_char;
1311 return 0;
1312 }
1313 }
1314
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001316 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001317 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001318 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319
1320 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001321 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1322 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 PyErr_NoMemory();
1324 return -1;
1325 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001326 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001327 _PyUnicode_WSTR(unicode), end,
1328 PyUnicode_1BYTE_DATA(unicode));
1329 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1330 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1331 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1332 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001333 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001334 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001335 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001336 }
1337 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001338 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001339 _PyUnicode_UTF8(unicode) = NULL;
1340 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001341 }
1342 PyObject_FREE(_PyUnicode_WSTR(unicode));
1343 _PyUnicode_WSTR(unicode) = NULL;
1344 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1345 }
1346 /* In this case we might have to convert down from 4-byte native
1347 wchar_t to 2-byte unicode. */
1348 else if (maxchar < 65536) {
1349 assert(num_surrogates == 0 &&
1350 "FindMaxCharAndNumSurrogatePairs() messed up");
1351
Victor Stinner506f5922011-09-28 22:34:18 +02001352#if SIZEOF_WCHAR_T == 2
1353 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001354 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001355 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1356 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1357 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001358 _PyUnicode_UTF8(unicode) = NULL;
1359 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001360#else
1361 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001362 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001363 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001364 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001365 PyErr_NoMemory();
1366 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 }
Victor Stinner506f5922011-09-28 22:34:18 +02001368 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1369 _PyUnicode_WSTR(unicode), end,
1370 PyUnicode_2BYTE_DATA(unicode));
1371 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1372 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1373 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001374 _PyUnicode_UTF8(unicode) = NULL;
1375 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001376 PyObject_FREE(_PyUnicode_WSTR(unicode));
1377 _PyUnicode_WSTR(unicode) = NULL;
1378 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1379#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001380 }
1381 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1382 else {
1383#if SIZEOF_WCHAR_T == 2
1384 /* in case the native representation is 2-bytes, we need to allocate a
1385 new normalized 4-byte version. */
1386 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001387 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1388 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001389 PyErr_NoMemory();
1390 return -1;
1391 }
1392 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1393 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001394 _PyUnicode_UTF8(unicode) = NULL;
1395 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001396 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1397 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001398 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001399 PyObject_FREE(_PyUnicode_WSTR(unicode));
1400 _PyUnicode_WSTR(unicode) = NULL;
1401 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1402#else
1403 assert(num_surrogates == 0);
1404
Victor Stinnerc3c74152011-10-02 20:39:55 +02001405 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001407 _PyUnicode_UTF8(unicode) = NULL;
1408 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001409 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1410#endif
1411 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1412 }
1413 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001414 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001415 return 0;
1416}
1417
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001418int
1419_PyUnicode_ReadyReplace(PyObject **op)
1420{
1421 return unicode_ready(op, 1);
1422}
1423
1424int
1425_PyUnicode_Ready(PyObject *op)
1426{
1427 return unicode_ready(&op, 0);
1428}
1429
Alexander Belopolsky40018472011-02-26 01:02:56 +00001430static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001431unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001432{
Walter Dörwald16807132007-05-25 13:52:07 +00001433 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_NOT_INTERNED:
1435 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001436
Benjamin Peterson29060642009-01-31 22:14:21 +00001437 case SSTATE_INTERNED_MORTAL:
1438 /* revive dead object temporarily for DelItem */
1439 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001440 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001441 Py_FatalError(
1442 "deletion of interned string failed");
1443 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 case SSTATE_INTERNED_IMMORTAL:
1446 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447
Benjamin Peterson29060642009-01-31 22:14:21 +00001448 default:
1449 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001450 }
1451
Victor Stinner03490912011-10-03 23:45:12 +02001452 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001454 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001455 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001456
1457 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001458 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001459 }
1460 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001461 if (_PyUnicode_DATA_ANY(unicode))
1462 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001463 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001464 }
1465}
1466
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001467#ifdef Py_DEBUG
1468static int
1469unicode_is_singleton(PyObject *unicode)
1470{
1471 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1472 if (unicode == unicode_empty)
1473 return 1;
1474 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1475 {
1476 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1477 if (ch < 256 && unicode_latin1[ch] == unicode)
1478 return 1;
1479 }
1480 return 0;
1481}
1482#endif
1483
Alexander Belopolsky40018472011-02-26 01:02:56 +00001484static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001485unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001486{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001487 if (Py_REFCNT(unicode) != 1)
1488 return 0;
1489 if (PyUnicode_CHECK_INTERNED(unicode))
1490 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001492 /* singleton refcount is greater than 1 */
1493 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001494#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495 return 1;
1496}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001497
Victor Stinnerfe226c02011-10-03 03:52:20 +02001498static int
1499unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1500{
1501 PyObject *unicode;
1502 Py_ssize_t old_length;
1503
1504 assert(p_unicode != NULL);
1505 unicode = *p_unicode;
1506
1507 assert(unicode != NULL);
1508 assert(PyUnicode_Check(unicode));
1509 assert(0 <= length);
1510
Victor Stinner910337b2011-10-03 03:20:16 +02001511 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001512 old_length = PyUnicode_WSTR_LENGTH(unicode);
1513 else
1514 old_length = PyUnicode_GET_LENGTH(unicode);
1515 if (old_length == length)
1516 return 0;
1517
Victor Stinnerfe226c02011-10-03 03:52:20 +02001518 if (!unicode_resizable(unicode)) {
1519 PyObject *copy = resize_copy(unicode, length);
1520 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001521 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 Py_DECREF(*p_unicode);
1523 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001524 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001525 }
1526
Victor Stinnerfe226c02011-10-03 03:52:20 +02001527 if (PyUnicode_IS_COMPACT(unicode)) {
1528 *p_unicode = resize_compact(unicode, length);
1529 if (*p_unicode == NULL)
1530 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001531 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001532 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001533 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001534 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001535}
1536
Alexander Belopolsky40018472011-02-26 01:02:56 +00001537int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001538PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001539{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001540 PyObject *unicode;
1541 if (p_unicode == NULL) {
1542 PyErr_BadInternalCall();
1543 return -1;
1544 }
1545 unicode = *p_unicode;
1546 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1547 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1548 {
1549 PyErr_BadInternalCall();
1550 return -1;
1551 }
1552 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001553}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001554
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001555static PyObject*
1556get_latin1_char(unsigned char ch)
1557{
Victor Stinnera464fc12011-10-02 20:39:30 +02001558 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001559 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001560 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001561 if (!unicode)
1562 return NULL;
1563 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001564 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001565 unicode_latin1[ch] = unicode;
1566 }
1567 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001568 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001569}
1570
Alexander Belopolsky40018472011-02-26 01:02:56 +00001571PyObject *
1572PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001573{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001574 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001575 Py_UCS4 maxchar = 0;
1576 Py_ssize_t num_surrogates;
1577
1578 if (u == NULL)
1579 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001580
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001581 /* If the Unicode data is known at construction time, we can apply
1582 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001584 /* Optimization for empty strings */
1585 if (size == 0 && unicode_empty != NULL) {
1586 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001587 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001588 }
Tim Petersced69f82003-09-16 20:30:58 +00001589
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001590 /* Single character Unicode objects in the Latin-1 range are
1591 shared when using this constructor */
1592 if (size == 1 && *u < 256)
1593 return get_latin1_char((unsigned char)*u);
1594
1595 /* If not empty and not single character, copy the Unicode data
1596 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001597 if (find_maxchar_surrogates(u, u + size,
1598 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001599 return NULL;
1600
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001601 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001603 if (!unicode)
1604 return NULL;
1605
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606 switch (PyUnicode_KIND(unicode)) {
1607 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001608 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001609 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1610 break;
1611 case PyUnicode_2BYTE_KIND:
1612#if Py_UNICODE_SIZE == 2
1613 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1614#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001615 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001616 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1617#endif
1618 break;
1619 case PyUnicode_4BYTE_KIND:
1620#if SIZEOF_WCHAR_T == 2
1621 /* This is the only case which has to process surrogates, thus
1622 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001623 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001624#else
1625 assert(num_surrogates == 0);
1626 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1627#endif
1628 break;
1629 default:
1630 assert(0 && "Impossible state");
1631 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001632
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001633 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001635}
1636
Alexander Belopolsky40018472011-02-26 01:02:56 +00001637PyObject *
1638PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001639{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001640 if (size < 0) {
1641 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001642 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001643 return NULL;
1644 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001645
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001646 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001647 some optimizations which share commonly used objects.
1648 Also, this means the input must be UTF-8, so fall back to the
1649 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001650 if (u != NULL) {
1651
Benjamin Peterson29060642009-01-31 22:14:21 +00001652 /* Optimization for empty strings */
1653 if (size == 0 && unicode_empty != NULL) {
1654 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001655 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001656 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001657
1658 /* Single characters are shared when using this constructor.
1659 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001660 if (size == 1 && (unsigned char)*u < 128)
1661 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001662
1663 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001664 }
1665
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001666 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001667}
1668
Alexander Belopolsky40018472011-02-26 01:02:56 +00001669PyObject *
1670PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001671{
1672 size_t size = strlen(u);
1673 if (size > PY_SSIZE_T_MAX) {
1674 PyErr_SetString(PyExc_OverflowError, "input too long");
1675 return NULL;
1676 }
1677
1678 return PyUnicode_FromStringAndSize(u, size);
1679}
1680
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001681PyObject *
1682_PyUnicode_FromId(_Py_Identifier *id)
1683{
1684 if (!id->object) {
1685 id->object = PyUnicode_FromString(id->string);
1686 if (!id->object)
1687 return NULL;
1688 PyUnicode_InternInPlace(&id->object);
1689 assert(!id->next);
1690 id->next = static_strings;
1691 static_strings = id;
1692 }
1693 Py_INCREF(id->object);
1694 return id->object;
1695}
1696
1697void
1698_PyUnicode_ClearStaticStrings()
1699{
1700 _Py_Identifier *i;
1701 for (i = static_strings; i; i = i->next) {
1702 Py_DECREF(i->object);
1703 i->object = NULL;
1704 i->next = NULL;
1705 }
1706}
1707
Victor Stinnere57b1c02011-09-28 22:20:48 +02001708static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001709unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001710{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001711 PyObject *res;
1712#ifdef Py_DEBUG
1713 const unsigned char *p;
1714 const unsigned char *end = s + size;
1715 for (p=s; p < end; p++) {
1716 assert(*p < 128);
1717 }
1718#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001719 if (size == 1)
1720 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001721 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001722 if (!res)
1723 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001724 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001725 return res;
1726}
1727
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001728static Py_UCS4
1729kind_maxchar_limit(unsigned int kind)
1730{
1731 switch(kind) {
1732 case PyUnicode_1BYTE_KIND:
1733 return 0x80;
1734 case PyUnicode_2BYTE_KIND:
1735 return 0x100;
1736 case PyUnicode_4BYTE_KIND:
1737 return 0x10000;
1738 default:
1739 assert(0 && "invalid kind");
1740 return 0x10ffff;
1741 }
1742}
1743
Victor Stinner702c7342011-10-05 13:50:52 +02001744static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001745_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001746{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001747 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001748 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001749
1750 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001751 if (size == 1)
1752 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001753 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001754 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001755 if (!res)
1756 return NULL;
1757 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001758 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001759 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001760}
1761
Victor Stinnere57b1c02011-09-28 22:20:48 +02001762static PyObject*
1763_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001764{
1765 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001766 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001767
1768 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001769 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001770 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001771 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001772 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001773 if (!res)
1774 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001775 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001776 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001777 else {
1778 _PyUnicode_CONVERT_BYTES(
1779 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1780 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001781 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001782 return res;
1783}
1784
Victor Stinnere57b1c02011-09-28 22:20:48 +02001785static PyObject*
1786_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787{
1788 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001789 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001790
1791 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001792 if (size == 1 && u[0] < 256)
1793 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001794 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001795 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796 if (!res)
1797 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001798 if (max_char < 256)
1799 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1800 PyUnicode_1BYTE_DATA(res));
1801 else if (max_char < 0x10000)
1802 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1803 PyUnicode_2BYTE_DATA(res));
1804 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001806 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001807 return res;
1808}
1809
1810PyObject*
1811PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1812{
1813 switch(kind) {
1814 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001815 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001816 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001817 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001819 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001820 default:
1821 assert(0 && "invalid kind");
1822 PyErr_SetString(PyExc_SystemError, "invalid kind");
1823 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001825}
1826
Victor Stinner25a4b292011-10-06 12:31:55 +02001827/* Ensure that a string uses the most efficient storage, if it is not the
1828 case: create a new string with of the right kind. Write NULL into *p_unicode
1829 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001830static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001831unicode_adjust_maxchar(PyObject **p_unicode)
1832{
1833 PyObject *unicode, *copy;
1834 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001835 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001836 unsigned int kind;
1837
1838 assert(p_unicode != NULL);
1839 unicode = *p_unicode;
1840 assert(PyUnicode_IS_READY(unicode));
1841 if (PyUnicode_IS_ASCII(unicode))
1842 return;
1843
1844 len = PyUnicode_GET_LENGTH(unicode);
1845 kind = PyUnicode_KIND(unicode);
1846 if (kind == PyUnicode_1BYTE_KIND) {
1847 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001848 max_char = ucs1lib_find_max_char(u, u + len);
1849 if (max_char >= 128)
1850 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001851 }
1852 else if (kind == PyUnicode_2BYTE_KIND) {
1853 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001854 max_char = ucs2lib_find_max_char(u, u + len);
1855 if (max_char >= 256)
1856 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001857 }
1858 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001859 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001860 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001861 max_char = ucs4lib_find_max_char(u, u + len);
1862 if (max_char >= 0x10000)
1863 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001864 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001865 copy = PyUnicode_New(len, max_char);
1866 copy_characters(copy, 0, unicode, 0, len);
1867 Py_DECREF(unicode);
1868 *p_unicode = copy;
1869}
1870
Victor Stinner034f6cf2011-09-30 02:26:44 +02001871PyObject*
1872PyUnicode_Copy(PyObject *unicode)
1873{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001874 Py_ssize_t size;
1875 PyObject *copy;
1876 void *data;
1877
Victor Stinner034f6cf2011-09-30 02:26:44 +02001878 if (!PyUnicode_Check(unicode)) {
1879 PyErr_BadInternalCall();
1880 return NULL;
1881 }
1882 if (PyUnicode_READY(unicode))
1883 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001884
1885 size = PyUnicode_GET_LENGTH(unicode);
1886 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1887 if (!copy)
1888 return NULL;
1889 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1890
1891 data = PyUnicode_DATA(unicode);
1892 switch (PyUnicode_KIND(unicode))
1893 {
1894 case PyUnicode_1BYTE_KIND:
1895 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1896 break;
1897 case PyUnicode_2BYTE_KIND:
1898 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1899 break;
1900 case PyUnicode_4BYTE_KIND:
1901 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1902 break;
1903 default:
1904 assert(0);
1905 break;
1906 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001907 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001908 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001909}
1910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001911
Victor Stinnerbc603d12011-10-02 01:00:40 +02001912/* Widen Unicode objects to larger buffers. Don't write terminating null
1913 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001914
1915void*
1916_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1917{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001918 Py_ssize_t len;
1919 void *result;
1920 unsigned int skind;
1921
1922 if (PyUnicode_READY(s))
1923 return NULL;
1924
1925 len = PyUnicode_GET_LENGTH(s);
1926 skind = PyUnicode_KIND(s);
1927 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001928 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001929 return NULL;
1930 }
1931 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001932 case PyUnicode_2BYTE_KIND:
1933 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1934 if (!result)
1935 return PyErr_NoMemory();
1936 assert(skind == PyUnicode_1BYTE_KIND);
1937 _PyUnicode_CONVERT_BYTES(
1938 Py_UCS1, Py_UCS2,
1939 PyUnicode_1BYTE_DATA(s),
1940 PyUnicode_1BYTE_DATA(s) + len,
1941 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001942 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001943 case PyUnicode_4BYTE_KIND:
1944 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1945 if (!result)
1946 return PyErr_NoMemory();
1947 if (skind == PyUnicode_2BYTE_KIND) {
1948 _PyUnicode_CONVERT_BYTES(
1949 Py_UCS2, Py_UCS4,
1950 PyUnicode_2BYTE_DATA(s),
1951 PyUnicode_2BYTE_DATA(s) + len,
1952 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001953 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001954 else {
1955 assert(skind == PyUnicode_1BYTE_KIND);
1956 _PyUnicode_CONVERT_BYTES(
1957 Py_UCS1, Py_UCS4,
1958 PyUnicode_1BYTE_DATA(s),
1959 PyUnicode_1BYTE_DATA(s) + len,
1960 result);
1961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001963 default:
1964 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001965 }
Victor Stinner01698042011-10-04 00:04:26 +02001966 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001967 return NULL;
1968}
1969
1970static Py_UCS4*
1971as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1972 int copy_null)
1973{
1974 int kind;
1975 void *data;
1976 Py_ssize_t len, targetlen;
1977 if (PyUnicode_READY(string) == -1)
1978 return NULL;
1979 kind = PyUnicode_KIND(string);
1980 data = PyUnicode_DATA(string);
1981 len = PyUnicode_GET_LENGTH(string);
1982 targetlen = len;
1983 if (copy_null)
1984 targetlen++;
1985 if (!target) {
1986 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1987 PyErr_NoMemory();
1988 return NULL;
1989 }
1990 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1991 if (!target) {
1992 PyErr_NoMemory();
1993 return NULL;
1994 }
1995 }
1996 else {
1997 if (targetsize < targetlen) {
1998 PyErr_Format(PyExc_SystemError,
1999 "string is longer than the buffer");
2000 if (copy_null && 0 < targetsize)
2001 target[0] = 0;
2002 return NULL;
2003 }
2004 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002005 if (kind == PyUnicode_1BYTE_KIND) {
2006 Py_UCS1 *start = (Py_UCS1 *) data;
2007 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002009 else if (kind == PyUnicode_2BYTE_KIND) {
2010 Py_UCS2 *start = (Py_UCS2 *) data;
2011 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2012 }
2013 else {
2014 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002015 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002016 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002017 if (copy_null)
2018 target[len] = 0;
2019 return target;
2020}
2021
2022Py_UCS4*
2023PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2024 int copy_null)
2025{
2026 if (target == NULL || targetsize < 1) {
2027 PyErr_BadInternalCall();
2028 return NULL;
2029 }
2030 return as_ucs4(string, target, targetsize, copy_null);
2031}
2032
2033Py_UCS4*
2034PyUnicode_AsUCS4Copy(PyObject *string)
2035{
2036 return as_ucs4(string, NULL, 0, 1);
2037}
2038
2039#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002040
Alexander Belopolsky40018472011-02-26 01:02:56 +00002041PyObject *
2042PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002043{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002044 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002045 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002046 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002047 PyErr_BadInternalCall();
2048 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002049 }
2050
Martin v. Löwis790465f2008-04-05 20:41:37 +00002051 if (size == -1) {
2052 size = wcslen(w);
2053 }
2054
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002055 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002056}
2057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002058#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002059
Walter Dörwald346737f2007-05-31 10:44:43 +00002060static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002061makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2062 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002063{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002064 *fmt++ = '%';
2065 if (width) {
2066 if (zeropad)
2067 *fmt++ = '0';
2068 fmt += sprintf(fmt, "%d", width);
2069 }
2070 if (precision)
2071 fmt += sprintf(fmt, ".%d", precision);
2072 if (longflag)
2073 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002074 else if (longlongflag) {
2075 /* longlongflag should only ever be nonzero on machines with
2076 HAVE_LONG_LONG defined */
2077#ifdef HAVE_LONG_LONG
2078 char *f = PY_FORMAT_LONG_LONG;
2079 while (*f)
2080 *fmt++ = *f++;
2081#else
2082 /* we shouldn't ever get here */
2083 assert(0);
2084 *fmt++ = 'l';
2085#endif
2086 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002087 else if (size_tflag) {
2088 char *f = PY_FORMAT_SIZE_T;
2089 while (*f)
2090 *fmt++ = *f++;
2091 }
2092 *fmt++ = c;
2093 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002094}
2095
Victor Stinner96865452011-03-01 23:44:09 +00002096/* helper for PyUnicode_FromFormatV() */
2097
2098static const char*
2099parse_format_flags(const char *f,
2100 int *p_width, int *p_precision,
2101 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2102{
2103 int width, precision, longflag, longlongflag, size_tflag;
2104
2105 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2106 f++;
2107 width = 0;
2108 while (Py_ISDIGIT((unsigned)*f))
2109 width = (width*10) + *f++ - '0';
2110 precision = 0;
2111 if (*f == '.') {
2112 f++;
2113 while (Py_ISDIGIT((unsigned)*f))
2114 precision = (precision*10) + *f++ - '0';
2115 if (*f == '%') {
2116 /* "%.3%s" => f points to "3" */
2117 f--;
2118 }
2119 }
2120 if (*f == '\0') {
2121 /* bogus format "%.1" => go backward, f points to "1" */
2122 f--;
2123 }
2124 if (p_width != NULL)
2125 *p_width = width;
2126 if (p_precision != NULL)
2127 *p_precision = precision;
2128
2129 /* Handle %ld, %lu, %lld and %llu. */
2130 longflag = 0;
2131 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002132 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002133
2134 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002135 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002136 longflag = 1;
2137 ++f;
2138 }
2139#ifdef HAVE_LONG_LONG
2140 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002141 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002142 longlongflag = 1;
2143 f += 2;
2144 }
2145#endif
2146 }
2147 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002148 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002149 size_tflag = 1;
2150 ++f;
2151 }
2152 if (p_longflag != NULL)
2153 *p_longflag = longflag;
2154 if (p_longlongflag != NULL)
2155 *p_longlongflag = longlongflag;
2156 if (p_size_tflag != NULL)
2157 *p_size_tflag = size_tflag;
2158 return f;
2159}
2160
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002161/* maximum number of characters required for output of %ld. 21 characters
2162 allows for 64-bit integers (in decimal) and an optional sign. */
2163#define MAX_LONG_CHARS 21
2164/* maximum number of characters required for output of %lld.
2165 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2166 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2167#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2168
Walter Dörwaldd2034312007-05-18 16:29:38 +00002169PyObject *
2170PyUnicode_FromFormatV(const char *format, va_list vargs)
2171{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002172 va_list count;
2173 Py_ssize_t callcount = 0;
2174 PyObject **callresults = NULL;
2175 PyObject **callresult = NULL;
2176 Py_ssize_t n = 0;
2177 int width = 0;
2178 int precision = 0;
2179 int zeropad;
2180 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002181 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002182 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002183 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002184 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2185 Py_UCS4 argmaxchar;
2186 Py_ssize_t numbersize = 0;
2187 char *numberresults = NULL;
2188 char *numberresult = NULL;
2189 Py_ssize_t i;
2190 int kind;
2191 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002192
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002193 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002194 /* step 1: count the number of %S/%R/%A/%s format specifications
2195 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2196 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002198 * also estimate a upper bound for all the number formats in the string,
2199 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002200 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002201 for (f = format; *f; f++) {
2202 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002203 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002204 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2205 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2206 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2207 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002209 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002210#ifdef HAVE_LONG_LONG
2211 if (longlongflag) {
2212 if (width < MAX_LONG_LONG_CHARS)
2213 width = MAX_LONG_LONG_CHARS;
2214 }
2215 else
2216#endif
2217 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2218 including sign. Decimal takes the most space. This
2219 isn't enough for octal. If a width is specified we
2220 need more (which we allocate later). */
2221 if (width < MAX_LONG_CHARS)
2222 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002223
2224 /* account for the size + '\0' to separate numbers
2225 inside of the numberresults buffer */
2226 numbersize += (width + 1);
2227 }
2228 }
2229 else if ((unsigned char)*f > 127) {
2230 PyErr_Format(PyExc_ValueError,
2231 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2232 "string, got a non-ASCII byte: 0x%02x",
2233 (unsigned char)*f);
2234 return NULL;
2235 }
2236 }
2237 /* step 2: allocate memory for the results of
2238 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2239 if (callcount) {
2240 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2241 if (!callresults) {
2242 PyErr_NoMemory();
2243 return NULL;
2244 }
2245 callresult = callresults;
2246 }
2247 /* step 2.5: allocate memory for the results of formating numbers */
2248 if (numbersize) {
2249 numberresults = PyObject_Malloc(numbersize);
2250 if (!numberresults) {
2251 PyErr_NoMemory();
2252 goto fail;
2253 }
2254 numberresult = numberresults;
2255 }
2256
2257 /* step 3: format numbers and figure out how large a buffer we need */
2258 for (f = format; *f; f++) {
2259 if (*f == '%') {
2260 const char* p;
2261 int longflag;
2262 int longlongflag;
2263 int size_tflag;
2264 int numprinted;
2265
2266 p = f;
2267 zeropad = (f[1] == '0');
2268 f = parse_format_flags(f, &width, &precision,
2269 &longflag, &longlongflag, &size_tflag);
2270 switch (*f) {
2271 case 'c':
2272 {
2273 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002274 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002275 n++;
2276 break;
2277 }
2278 case '%':
2279 n++;
2280 break;
2281 case 'i':
2282 case 'd':
2283 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2284 width, precision, *f);
2285 if (longflag)
2286 numprinted = sprintf(numberresult, fmt,
2287 va_arg(count, long));
2288#ifdef HAVE_LONG_LONG
2289 else if (longlongflag)
2290 numprinted = sprintf(numberresult, fmt,
2291 va_arg(count, PY_LONG_LONG));
2292#endif
2293 else if (size_tflag)
2294 numprinted = sprintf(numberresult, fmt,
2295 va_arg(count, Py_ssize_t));
2296 else
2297 numprinted = sprintf(numberresult, fmt,
2298 va_arg(count, int));
2299 n += numprinted;
2300 /* advance by +1 to skip over the '\0' */
2301 numberresult += (numprinted + 1);
2302 assert(*(numberresult - 1) == '\0');
2303 assert(*(numberresult - 2) != '\0');
2304 assert(numprinted >= 0);
2305 assert(numberresult <= numberresults + numbersize);
2306 break;
2307 case 'u':
2308 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2309 width, precision, 'u');
2310 if (longflag)
2311 numprinted = sprintf(numberresult, fmt,
2312 va_arg(count, unsigned long));
2313#ifdef HAVE_LONG_LONG
2314 else if (longlongflag)
2315 numprinted = sprintf(numberresult, fmt,
2316 va_arg(count, unsigned PY_LONG_LONG));
2317#endif
2318 else if (size_tflag)
2319 numprinted = sprintf(numberresult, fmt,
2320 va_arg(count, size_t));
2321 else
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, unsigned int));
2324 n += numprinted;
2325 numberresult += (numprinted + 1);
2326 assert(*(numberresult - 1) == '\0');
2327 assert(*(numberresult - 2) != '\0');
2328 assert(numprinted >= 0);
2329 assert(numberresult <= numberresults + numbersize);
2330 break;
2331 case 'x':
2332 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2333 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2334 n += numprinted;
2335 numberresult += (numprinted + 1);
2336 assert(*(numberresult - 1) == '\0');
2337 assert(*(numberresult - 2) != '\0');
2338 assert(numprinted >= 0);
2339 assert(numberresult <= numberresults + numbersize);
2340 break;
2341 case 'p':
2342 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2343 /* %p is ill-defined: ensure leading 0x. */
2344 if (numberresult[1] == 'X')
2345 numberresult[1] = 'x';
2346 else if (numberresult[1] != 'x') {
2347 memmove(numberresult + 2, numberresult,
2348 strlen(numberresult) + 1);
2349 numberresult[0] = '0';
2350 numberresult[1] = 'x';
2351 numprinted += 2;
2352 }
2353 n += numprinted;
2354 numberresult += (numprinted + 1);
2355 assert(*(numberresult - 1) == '\0');
2356 assert(*(numberresult - 2) != '\0');
2357 assert(numprinted >= 0);
2358 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002359 break;
2360 case 's':
2361 {
2362 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002363 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002364 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2365 if (!str)
2366 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002367 /* since PyUnicode_DecodeUTF8 returns already flexible
2368 unicode objects, there is no need to call ready on them */
2369 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002370 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002371 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002372 /* Remember the str and switch to the next slot */
2373 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002374 break;
2375 }
2376 case 'U':
2377 {
2378 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002379 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002380 if (PyUnicode_READY(obj) == -1)
2381 goto fail;
2382 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002383 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002384 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002385 break;
2386 }
2387 case 'V':
2388 {
2389 PyObject *obj = va_arg(count, PyObject *);
2390 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002391 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002392 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002393 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002394 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002395 if (PyUnicode_READY(obj) == -1)
2396 goto fail;
2397 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002398 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002400 *callresult++ = NULL;
2401 }
2402 else {
2403 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2404 if (!str_obj)
2405 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002406 if (PyUnicode_READY(str_obj)) {
2407 Py_DECREF(str_obj);
2408 goto fail;
2409 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002410 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002411 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002413 *callresult++ = str_obj;
2414 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002415 break;
2416 }
2417 case 'S':
2418 {
2419 PyObject *obj = va_arg(count, PyObject *);
2420 PyObject *str;
2421 assert(obj);
2422 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002423 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002425 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002426 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002428 /* Remember the str and switch to the next slot */
2429 *callresult++ = str;
2430 break;
2431 }
2432 case 'R':
2433 {
2434 PyObject *obj = va_arg(count, PyObject *);
2435 PyObject *repr;
2436 assert(obj);
2437 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002438 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002439 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002440 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002441 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002443 /* Remember the repr and switch to the next slot */
2444 *callresult++ = repr;
2445 break;
2446 }
2447 case 'A':
2448 {
2449 PyObject *obj = va_arg(count, PyObject *);
2450 PyObject *ascii;
2451 assert(obj);
2452 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002453 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002454 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002456 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002458 /* Remember the repr and switch to the next slot */
2459 *callresult++ = ascii;
2460 break;
2461 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002462 default:
2463 /* if we stumble upon an unknown
2464 formatting code, copy the rest of
2465 the format string to the output
2466 string. (we cannot just skip the
2467 code, since there's no way to know
2468 what's in the argument list) */
2469 n += strlen(p);
2470 goto expand;
2471 }
2472 } else
2473 n++;
2474 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002475 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002476 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002477 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002478 we don't have to resize the string.
2479 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002480 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002481 if (!string)
2482 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002483 kind = PyUnicode_KIND(string);
2484 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002485 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002486 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002488 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002489 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002490 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002491
2492 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2494 /* checking for == because the last argument could be a empty
2495 string, which causes i to point to end, the assert at the end of
2496 the loop */
2497 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002498
Benjamin Peterson14339b62009-01-31 16:36:08 +00002499 switch (*f) {
2500 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002501 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002502 const int ordinal = va_arg(vargs, int);
2503 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002504 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002505 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002506 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002507 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 case 'p':
2511 /* unused, since we already have the result */
2512 if (*f == 'p')
2513 (void) va_arg(vargs, void *);
2514 else
2515 (void) va_arg(vargs, int);
2516 /* extract the result from numberresults and append. */
2517 for (; *numberresult; ++i, ++numberresult)
2518 PyUnicode_WRITE(kind, data, i, *numberresult);
2519 /* skip over the separating '\0' */
2520 assert(*numberresult == '\0');
2521 numberresult++;
2522 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002523 break;
2524 case 's':
2525 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002526 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002527 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002528 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002529 size = PyUnicode_GET_LENGTH(*callresult);
2530 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002531 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002532 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002533 /* We're done with the unicode()/repr() => forget it */
2534 Py_DECREF(*callresult);
2535 /* switch to next unicode()/repr() result */
2536 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002537 break;
2538 }
2539 case 'U':
2540 {
2541 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 Py_ssize_t size;
2543 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2544 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002545 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002546 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002547 break;
2548 }
2549 case 'V':
2550 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002552 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002553 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002554 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002555 size = PyUnicode_GET_LENGTH(obj);
2556 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002557 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002558 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002560 size = PyUnicode_GET_LENGTH(*callresult);
2561 assert(PyUnicode_KIND(*callresult) <=
2562 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002563 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002565 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002566 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002567 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002568 break;
2569 }
2570 case 'S':
2571 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002572 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002573 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002574 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002575 /* unused, since we already have the result */
2576 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002577 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002578 copy_characters(string, i, *callresult, 0, size);
2579 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 /* We're done with the unicode()/repr() => forget it */
2581 Py_DECREF(*callresult);
2582 /* switch to next unicode()/repr() result */
2583 ++callresult;
2584 break;
2585 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002588 break;
2589 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 for (; *p; ++p, ++i)
2591 PyUnicode_WRITE(kind, data, i, *p);
2592 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002593 goto end;
2594 }
Victor Stinner1205f272010-09-11 00:54:47 +00002595 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 else {
2597 assert(i < PyUnicode_GET_LENGTH(string));
2598 PyUnicode_WRITE(kind, data, i++, *f);
2599 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002601 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002602
Benjamin Peterson29060642009-01-31 22:14:21 +00002603 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 if (callresults)
2605 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002606 if (numberresults)
2607 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002608 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002609 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002610 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002611 if (callresults) {
2612 PyObject **callresult2 = callresults;
2613 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002614 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002615 ++callresult2;
2616 }
2617 PyObject_Free(callresults);
2618 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 if (numberresults)
2620 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002622}
2623
Walter Dörwaldd2034312007-05-18 16:29:38 +00002624PyObject *
2625PyUnicode_FromFormat(const char *format, ...)
2626{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002627 PyObject* ret;
2628 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002629
2630#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002631 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002632#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002634#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002635 ret = PyUnicode_FromFormatV(format, vargs);
2636 va_end(vargs);
2637 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002638}
2639
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002640#ifdef HAVE_WCHAR_H
2641
Victor Stinner5593d8a2010-10-02 11:11:27 +00002642/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2643 convert a Unicode object to a wide character string.
2644
Victor Stinnerd88d9832011-09-06 02:00:05 +02002645 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002646 character) required to convert the unicode object. Ignore size argument.
2647
Victor Stinnerd88d9832011-09-06 02:00:05 +02002648 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002649 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002650 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002651static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002652unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002653 wchar_t *w,
2654 Py_ssize_t size)
2655{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002656 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002657 const wchar_t *wstr;
2658
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002659 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002660 if (wstr == NULL)
2661 return -1;
2662
Victor Stinner5593d8a2010-10-02 11:11:27 +00002663 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002664 if (size > res)
2665 size = res + 1;
2666 else
2667 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002668 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002669 return res;
2670 }
2671 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002673}
2674
2675Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002676PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002677 wchar_t *w,
2678 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002679{
2680 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002681 PyErr_BadInternalCall();
2682 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002683 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002684 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002685}
2686
Victor Stinner137c34c2010-09-29 10:25:54 +00002687wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002688PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002689 Py_ssize_t *size)
2690{
2691 wchar_t* buffer;
2692 Py_ssize_t buflen;
2693
2694 if (unicode == NULL) {
2695 PyErr_BadInternalCall();
2696 return NULL;
2697 }
2698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002699 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 if (buflen == -1)
2701 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002702 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002703 PyErr_NoMemory();
2704 return NULL;
2705 }
2706
Victor Stinner137c34c2010-09-29 10:25:54 +00002707 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2708 if (buffer == NULL) {
2709 PyErr_NoMemory();
2710 return NULL;
2711 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002712 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713 if (buflen == -1)
2714 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002715 if (size != NULL)
2716 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002717 return buffer;
2718}
2719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002720#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721
Alexander Belopolsky40018472011-02-26 01:02:56 +00002722PyObject *
2723PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002724{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002725 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002726 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002727 PyErr_SetString(PyExc_ValueError,
2728 "chr() arg not in range(0x110000)");
2729 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002730 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (ordinal < 256)
2733 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002734
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002735 v = PyUnicode_New(1, ordinal);
2736 if (v == NULL)
2737 return NULL;
2738 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002739 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002740 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002741}
2742
Alexander Belopolsky40018472011-02-26 01:02:56 +00002743PyObject *
2744PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002745{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002746 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002747 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002748 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002749 if (PyUnicode_READY(obj))
2750 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002751 Py_INCREF(obj);
2752 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002753 }
2754 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002755 /* For a Unicode subtype that's not a Unicode object,
2756 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002757 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002758 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002759 PyErr_Format(PyExc_TypeError,
2760 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002761 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002762 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002763}
2764
Alexander Belopolsky40018472011-02-26 01:02:56 +00002765PyObject *
2766PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002767 const char *encoding,
2768 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002769{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002770 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002771 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002772
Guido van Rossumd57fd912000-03-10 22:53:23 +00002773 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002774 PyErr_BadInternalCall();
2775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002776 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002777
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002778 /* Decoding bytes objects is the most common case and should be fast */
2779 if (PyBytes_Check(obj)) {
2780 if (PyBytes_GET_SIZE(obj) == 0) {
2781 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002782 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002783 }
2784 else {
2785 v = PyUnicode_Decode(
2786 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2787 encoding, errors);
2788 }
2789 return v;
2790 }
2791
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002792 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002793 PyErr_SetString(PyExc_TypeError,
2794 "decoding str is not supported");
2795 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002796 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002797
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002798 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2799 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2800 PyErr_Format(PyExc_TypeError,
2801 "coercing to str: need bytes, bytearray "
2802 "or buffer-like object, %.80s found",
2803 Py_TYPE(obj)->tp_name);
2804 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002805 }
Tim Petersced69f82003-09-16 20:30:58 +00002806
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002807 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002808 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002809 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002810 }
Tim Petersced69f82003-09-16 20:30:58 +00002811 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002812 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002813
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002814 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002815 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002816}
2817
Victor Stinner600d3be2010-06-10 12:00:55 +00002818/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002819 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2820 1 on success. */
2821static int
2822normalize_encoding(const char *encoding,
2823 char *lower,
2824 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002825{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002826 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002827 char *l;
2828 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002829
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002830 if (encoding == NULL) {
2831 strcpy(lower, "utf-8");
2832 return 1;
2833 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002834 e = encoding;
2835 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002836 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002837 while (*e) {
2838 if (l == l_end)
2839 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002840 if (Py_ISUPPER(*e)) {
2841 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002842 }
2843 else if (*e == '_') {
2844 *l++ = '-';
2845 e++;
2846 }
2847 else {
2848 *l++ = *e++;
2849 }
2850 }
2851 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002852 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002853}
2854
Alexander Belopolsky40018472011-02-26 01:02:56 +00002855PyObject *
2856PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002857 Py_ssize_t size,
2858 const char *encoding,
2859 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002860{
2861 PyObject *buffer = NULL, *unicode;
2862 Py_buffer info;
2863 char lower[11]; /* Enough for any encoding shortcut */
2864
Fred Drakee4315f52000-05-09 19:53:39 +00002865 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002866 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002867 if ((strcmp(lower, "utf-8") == 0) ||
2868 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002869 return PyUnicode_DecodeUTF8(s, size, errors);
2870 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002871 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002872 (strcmp(lower, "iso-8859-1") == 0))
2873 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002874#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002875 else if (strcmp(lower, "mbcs") == 0)
2876 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002877#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002878 else if (strcmp(lower, "ascii") == 0)
2879 return PyUnicode_DecodeASCII(s, size, errors);
2880 else if (strcmp(lower, "utf-16") == 0)
2881 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2882 else if (strcmp(lower, "utf-32") == 0)
2883 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2884 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002885
2886 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002887 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002888 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002889 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002890 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002891 if (buffer == NULL)
2892 goto onError;
2893 unicode = PyCodec_Decode(buffer, encoding, errors);
2894 if (unicode == NULL)
2895 goto onError;
2896 if (!PyUnicode_Check(unicode)) {
2897 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002898 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002899 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002900 Py_DECREF(unicode);
2901 goto onError;
2902 }
2903 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002904#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002905 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002906 Py_DECREF(unicode);
2907 return NULL;
2908 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002909#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002910 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002911 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002912
Benjamin Peterson29060642009-01-31 22:14:21 +00002913 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002914 Py_XDECREF(buffer);
2915 return NULL;
2916}
2917
Alexander Belopolsky40018472011-02-26 01:02:56 +00002918PyObject *
2919PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002920 const char *encoding,
2921 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002922{
2923 PyObject *v;
2924
2925 if (!PyUnicode_Check(unicode)) {
2926 PyErr_BadArgument();
2927 goto onError;
2928 }
2929
2930 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002931 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002932
2933 /* Decode via the codec registry */
2934 v = PyCodec_Decode(unicode, encoding, errors);
2935 if (v == NULL)
2936 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002937 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002938 return v;
2939
Benjamin Peterson29060642009-01-31 22:14:21 +00002940 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002941 return NULL;
2942}
2943
Alexander Belopolsky40018472011-02-26 01:02:56 +00002944PyObject *
2945PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002946 const char *encoding,
2947 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002948{
2949 PyObject *v;
2950
2951 if (!PyUnicode_Check(unicode)) {
2952 PyErr_BadArgument();
2953 goto onError;
2954 }
2955
2956 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002957 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002958
2959 /* Decode via the codec registry */
2960 v = PyCodec_Decode(unicode, encoding, errors);
2961 if (v == NULL)
2962 goto onError;
2963 if (!PyUnicode_Check(v)) {
2964 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002965 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002966 Py_TYPE(v)->tp_name);
2967 Py_DECREF(v);
2968 goto onError;
2969 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002970 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002971 return v;
2972
Benjamin Peterson29060642009-01-31 22:14:21 +00002973 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002974 return NULL;
2975}
2976
Alexander Belopolsky40018472011-02-26 01:02:56 +00002977PyObject *
2978PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002979 Py_ssize_t size,
2980 const char *encoding,
2981 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002982{
2983 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002984
Guido van Rossumd57fd912000-03-10 22:53:23 +00002985 unicode = PyUnicode_FromUnicode(s, size);
2986 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002987 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002988 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2989 Py_DECREF(unicode);
2990 return v;
2991}
2992
Alexander Belopolsky40018472011-02-26 01:02:56 +00002993PyObject *
2994PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002995 const char *encoding,
2996 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002997{
2998 PyObject *v;
2999
3000 if (!PyUnicode_Check(unicode)) {
3001 PyErr_BadArgument();
3002 goto onError;
3003 }
3004
3005 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003006 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003007
3008 /* Encode via the codec registry */
3009 v = PyCodec_Encode(unicode, encoding, errors);
3010 if (v == NULL)
3011 goto onError;
3012 return v;
3013
Benjamin Peterson29060642009-01-31 22:14:21 +00003014 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003015 return NULL;
3016}
3017
Victor Stinnerad158722010-10-27 00:25:46 +00003018PyObject *
3019PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003020{
Victor Stinner99b95382011-07-04 14:23:54 +02003021#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003022 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3023 PyUnicode_GET_SIZE(unicode),
3024 NULL);
3025#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003026 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003027#else
Victor Stinner793b5312011-04-27 00:24:21 +02003028 PyInterpreterState *interp = PyThreadState_GET()->interp;
3029 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3030 cannot use it to encode and decode filenames before it is loaded. Load
3031 the Python codec requires to encode at least its own filename. Use the C
3032 version of the locale codec until the codec registry is initialized and
3033 the Python codec is loaded.
3034
3035 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3036 cannot only rely on it: check also interp->fscodec_initialized for
3037 subinterpreters. */
3038 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003039 return PyUnicode_AsEncodedString(unicode,
3040 Py_FileSystemDefaultEncoding,
3041 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003042 }
3043 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003044 /* locale encoding with surrogateescape */
3045 wchar_t *wchar;
3046 char *bytes;
3047 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003048 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003049
3050 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3051 if (wchar == NULL)
3052 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003053 bytes = _Py_wchar2char(wchar, &error_pos);
3054 if (bytes == NULL) {
3055 if (error_pos != (size_t)-1) {
3056 char *errmsg = strerror(errno);
3057 PyObject *exc = NULL;
3058 if (errmsg == NULL)
3059 errmsg = "Py_wchar2char() failed";
3060 raise_encode_exception(&exc,
3061 "filesystemencoding",
3062 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3063 error_pos, error_pos+1,
3064 errmsg);
3065 Py_XDECREF(exc);
3066 }
3067 else
3068 PyErr_NoMemory();
3069 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003070 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003071 }
3072 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003073
3074 bytes_obj = PyBytes_FromString(bytes);
3075 PyMem_Free(bytes);
3076 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003077 }
Victor Stinnerad158722010-10-27 00:25:46 +00003078#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003079}
3080
Alexander Belopolsky40018472011-02-26 01:02:56 +00003081PyObject *
3082PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003083 const char *encoding,
3084 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003085{
3086 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003087 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003088
Guido van Rossumd57fd912000-03-10 22:53:23 +00003089 if (!PyUnicode_Check(unicode)) {
3090 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003091 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003092 }
Fred Drakee4315f52000-05-09 19:53:39 +00003093
Fred Drakee4315f52000-05-09 19:53:39 +00003094 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003095 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003096 if ((strcmp(lower, "utf-8") == 0) ||
3097 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003098 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003099 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003100 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003101 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003102 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003103 }
Victor Stinner37296e82010-06-10 13:36:23 +00003104 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003105 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003106 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003107 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003108#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003109 else if (strcmp(lower, "mbcs") == 0)
3110 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3111 PyUnicode_GET_SIZE(unicode),
3112 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003113#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003114 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003115 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003116 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003117
3118 /* Encode via the codec registry */
3119 v = PyCodec_Encode(unicode, encoding, errors);
3120 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003121 return NULL;
3122
3123 /* The normal path */
3124 if (PyBytes_Check(v))
3125 return v;
3126
3127 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003128 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003129 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003130 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003131
3132 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3133 "encoder %s returned bytearray instead of bytes",
3134 encoding);
3135 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003136 Py_DECREF(v);
3137 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003138 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003139
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003140 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3141 Py_DECREF(v);
3142 return b;
3143 }
3144
3145 PyErr_Format(PyExc_TypeError,
3146 "encoder did not return a bytes object (type=%.400s)",
3147 Py_TYPE(v)->tp_name);
3148 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003149 return NULL;
3150}
3151
Alexander Belopolsky40018472011-02-26 01:02:56 +00003152PyObject *
3153PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003154 const char *encoding,
3155 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003156{
3157 PyObject *v;
3158
3159 if (!PyUnicode_Check(unicode)) {
3160 PyErr_BadArgument();
3161 goto onError;
3162 }
3163
3164 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003165 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003166
3167 /* Encode via the codec registry */
3168 v = PyCodec_Encode(unicode, encoding, errors);
3169 if (v == NULL)
3170 goto onError;
3171 if (!PyUnicode_Check(v)) {
3172 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003173 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003174 Py_TYPE(v)->tp_name);
3175 Py_DECREF(v);
3176 goto onError;
3177 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003178 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003179
Benjamin Peterson29060642009-01-31 22:14:21 +00003180 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003181 return NULL;
3182}
3183
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003184PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003185PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003186 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003187 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3188}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003189
Christian Heimes5894ba72007-11-04 11:43:14 +00003190PyObject*
3191PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3192{
Victor Stinner99b95382011-07-04 14:23:54 +02003193#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003194 return PyUnicode_DecodeMBCS(s, size, NULL);
3195#elif defined(__APPLE__)
3196 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3197#else
Victor Stinner793b5312011-04-27 00:24:21 +02003198 PyInterpreterState *interp = PyThreadState_GET()->interp;
3199 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3200 cannot use it to encode and decode filenames before it is loaded. Load
3201 the Python codec requires to encode at least its own filename. Use the C
3202 version of the locale codec until the codec registry is initialized and
3203 the Python codec is loaded.
3204
3205 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3206 cannot only rely on it: check also interp->fscodec_initialized for
3207 subinterpreters. */
3208 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003209 return PyUnicode_Decode(s, size,
3210 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003211 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003212 }
3213 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003214 /* locale encoding with surrogateescape */
3215 wchar_t *wchar;
3216 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003217 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003218
3219 if (s[size] != '\0' || size != strlen(s)) {
3220 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3221 return NULL;
3222 }
3223
Victor Stinner168e1172010-10-16 23:16:16 +00003224 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003225 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003226 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003227
Victor Stinner168e1172010-10-16 23:16:16 +00003228 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003229 PyMem_Free(wchar);
3230 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003231 }
Victor Stinnerad158722010-10-27 00:25:46 +00003232#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003233}
3234
Martin v. Löwis011e8422009-05-05 04:43:17 +00003235
3236int
3237PyUnicode_FSConverter(PyObject* arg, void* addr)
3238{
3239 PyObject *output = NULL;
3240 Py_ssize_t size;
3241 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003242 if (arg == NULL) {
3243 Py_DECREF(*(PyObject**)addr);
3244 return 1;
3245 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003246 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003247 output = arg;
3248 Py_INCREF(output);
3249 }
3250 else {
3251 arg = PyUnicode_FromObject(arg);
3252 if (!arg)
3253 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003254 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003255 Py_DECREF(arg);
3256 if (!output)
3257 return 0;
3258 if (!PyBytes_Check(output)) {
3259 Py_DECREF(output);
3260 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3261 return 0;
3262 }
3263 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003264 size = PyBytes_GET_SIZE(output);
3265 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003266 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003267 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003268 Py_DECREF(output);
3269 return 0;
3270 }
3271 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003272 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003273}
3274
3275
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003276int
3277PyUnicode_FSDecoder(PyObject* arg, void* addr)
3278{
3279 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003280 if (arg == NULL) {
3281 Py_DECREF(*(PyObject**)addr);
3282 return 1;
3283 }
3284 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003285 if (PyUnicode_READY(arg))
3286 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003287 output = arg;
3288 Py_INCREF(output);
3289 }
3290 else {
3291 arg = PyBytes_FromObject(arg);
3292 if (!arg)
3293 return 0;
3294 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3295 PyBytes_GET_SIZE(arg));
3296 Py_DECREF(arg);
3297 if (!output)
3298 return 0;
3299 if (!PyUnicode_Check(output)) {
3300 Py_DECREF(output);
3301 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3302 return 0;
3303 }
3304 }
Victor Stinner065836e2011-10-27 01:56:33 +02003305 if (PyUnicode_READY(output) < 0) {
3306 Py_DECREF(output);
3307 return 0;
3308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003309 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003310 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003311 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3312 Py_DECREF(output);
3313 return 0;
3314 }
3315 *(PyObject**)addr = output;
3316 return Py_CLEANUP_SUPPORTED;
3317}
3318
3319
Martin v. Löwis5b222132007-06-10 09:51:05 +00003320char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003321PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003322{
Christian Heimesf3863112007-11-22 07:46:41 +00003323 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003324
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003325 if (!PyUnicode_Check(unicode)) {
3326 PyErr_BadArgument();
3327 return NULL;
3328 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003329 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003330 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003331
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003332 if (PyUnicode_UTF8(unicode) == NULL) {
3333 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003334 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3335 if (bytes == NULL)
3336 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003337 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3338 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003339 Py_DECREF(bytes);
3340 return NULL;
3341 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003342 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3343 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3344 PyBytes_AS_STRING(bytes),
3345 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003346 Py_DECREF(bytes);
3347 }
3348
3349 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003350 *psize = PyUnicode_UTF8_LENGTH(unicode);
3351 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003352}
3353
3354char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003356{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003357 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3358}
3359
3360#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003361static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362#endif
3363
3364
3365Py_UNICODE *
3366PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003368 const unsigned char *one_byte;
3369#if SIZEOF_WCHAR_T == 4
3370 const Py_UCS2 *two_bytes;
3371#else
3372 const Py_UCS4 *four_bytes;
3373 const Py_UCS4 *ucs4_end;
3374 Py_ssize_t num_surrogates;
3375#endif
3376 wchar_t *w;
3377 wchar_t *wchar_end;
3378
3379 if (!PyUnicode_Check(unicode)) {
3380 PyErr_BadArgument();
3381 return NULL;
3382 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003383 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003384 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003385 assert(_PyUnicode_KIND(unicode) != 0);
3386 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387
3388#ifdef Py_DEBUG
3389 ++unicode_as_unicode_calls;
3390#endif
3391
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003392 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003394 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3395 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003396 num_surrogates = 0;
3397
3398 for (; four_bytes < ucs4_end; ++four_bytes) {
3399 if (*four_bytes > 0xFFFF)
3400 ++num_surrogates;
3401 }
3402
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003403 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3404 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3405 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003406 PyErr_NoMemory();
3407 return NULL;
3408 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003409 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003410
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003411 w = _PyUnicode_WSTR(unicode);
3412 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3413 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003414 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3415 if (*four_bytes > 0xFFFF) {
3416 /* encode surrogate pair in this case */
3417 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3418 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3419 }
3420 else
3421 *w = *four_bytes;
3422
3423 if (w > wchar_end) {
3424 assert(0 && "Miscalculated string end");
3425 }
3426 }
3427 *w = 0;
3428#else
3429 /* sizeof(wchar_t) == 4 */
3430 Py_FatalError("Impossible unicode object state, wstr and str "
3431 "should share memory already.");
3432 return NULL;
3433#endif
3434 }
3435 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003436 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3437 (_PyUnicode_LENGTH(unicode) + 1));
3438 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003439 PyErr_NoMemory();
3440 return NULL;
3441 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3443 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3444 w = _PyUnicode_WSTR(unicode);
3445 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003447 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3448 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003449 for (; w < wchar_end; ++one_byte, ++w)
3450 *w = *one_byte;
3451 /* null-terminate the wstr */
3452 *w = 0;
3453 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003454 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003455#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003456 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003457 for (; w < wchar_end; ++two_bytes, ++w)
3458 *w = *two_bytes;
3459 /* null-terminate the wstr */
3460 *w = 0;
3461#else
3462 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003463 PyObject_FREE(_PyUnicode_WSTR(unicode));
3464 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003465 Py_FatalError("Impossible unicode object state, wstr "
3466 "and str should share memory already.");
3467 return NULL;
3468#endif
3469 }
3470 else {
3471 assert(0 && "This should never happen.");
3472 }
3473 }
3474 }
3475 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003476 *size = PyUnicode_WSTR_LENGTH(unicode);
3477 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003478}
3479
Alexander Belopolsky40018472011-02-26 01:02:56 +00003480Py_UNICODE *
3481PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003482{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003483 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003484}
3485
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486
Alexander Belopolsky40018472011-02-26 01:02:56 +00003487Py_ssize_t
3488PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003489{
3490 if (!PyUnicode_Check(unicode)) {
3491 PyErr_BadArgument();
3492 goto onError;
3493 }
3494 return PyUnicode_GET_SIZE(unicode);
3495
Benjamin Peterson29060642009-01-31 22:14:21 +00003496 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003497 return -1;
3498}
3499
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003500Py_ssize_t
3501PyUnicode_GetLength(PyObject *unicode)
3502{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003503 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003504 PyErr_BadArgument();
3505 return -1;
3506 }
3507
3508 return PyUnicode_GET_LENGTH(unicode);
3509}
3510
3511Py_UCS4
3512PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3513{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003514 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3515 PyErr_BadArgument();
3516 return (Py_UCS4)-1;
3517 }
3518 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3519 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003520 return (Py_UCS4)-1;
3521 }
3522 return PyUnicode_READ_CHAR(unicode, index);
3523}
3524
3525int
3526PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3527{
3528 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003529 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003530 return -1;
3531 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003532 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3533 PyErr_SetString(PyExc_IndexError, "string index out of range");
3534 return -1;
3535 }
3536 if (_PyUnicode_Dirty(unicode))
3537 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003538 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3539 index, ch);
3540 return 0;
3541}
3542
Alexander Belopolsky40018472011-02-26 01:02:56 +00003543const char *
3544PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003545{
Victor Stinner42cb4622010-09-01 19:39:01 +00003546 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003547}
3548
Victor Stinner554f3f02010-06-16 23:33:54 +00003549/* create or adjust a UnicodeDecodeError */
3550static void
3551make_decode_exception(PyObject **exceptionObject,
3552 const char *encoding,
3553 const char *input, Py_ssize_t length,
3554 Py_ssize_t startpos, Py_ssize_t endpos,
3555 const char *reason)
3556{
3557 if (*exceptionObject == NULL) {
3558 *exceptionObject = PyUnicodeDecodeError_Create(
3559 encoding, input, length, startpos, endpos, reason);
3560 }
3561 else {
3562 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3563 goto onError;
3564 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3565 goto onError;
3566 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3567 goto onError;
3568 }
3569 return;
3570
3571onError:
3572 Py_DECREF(*exceptionObject);
3573 *exceptionObject = NULL;
3574}
3575
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003576/* error handling callback helper:
3577 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003578 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003579 and adjust various state variables.
3580 return 0 on success, -1 on error
3581*/
3582
Alexander Belopolsky40018472011-02-26 01:02:56 +00003583static int
3584unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003585 const char *encoding, const char *reason,
3586 const char **input, const char **inend, Py_ssize_t *startinpos,
3587 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Victor Stinner7931d9a2011-11-04 00:22:48 +01003588 PyObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003589{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003590 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003591
3592 PyObject *restuple = NULL;
3593 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003594 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003595 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003596 Py_ssize_t requiredsize;
3597 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003598 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003599 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003600 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003601 int res = -1;
3602
3603 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003604 *errorHandler = PyCodec_LookupError(errors);
3605 if (*errorHandler == NULL)
3606 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003607 }
3608
Victor Stinner554f3f02010-06-16 23:33:54 +00003609 make_decode_exception(exceptionObject,
3610 encoding,
3611 *input, *inend - *input,
3612 *startinpos, *endinpos,
3613 reason);
3614 if (*exceptionObject == NULL)
3615 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003616
3617 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3618 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003619 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003620 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003621 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003622 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003623 }
3624 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003625 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003626
3627 /* Copy back the bytes variables, which might have been modified by the
3628 callback */
3629 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3630 if (!inputobj)
3631 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003632 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003633 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003634 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003635 *input = PyBytes_AS_STRING(inputobj);
3636 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003637 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003638 /* we can DECREF safely, as the exception has another reference,
3639 so the object won't go away. */
3640 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003641
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003643 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003644 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003645 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3646 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003647 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003648
3649 /* need more space? (at least enough for what we
3650 have+the replacement+the rest of the string (starting
3651 at the new input position), so we won't have to check space
3652 when there are no errors in the rest of the string) */
3653 repptr = PyUnicode_AS_UNICODE(repunicode);
3654 repsize = PyUnicode_GET_SIZE(repunicode);
3655 requiredsize = *outpos + repsize + insize-newpos;
3656 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003657 if (requiredsize<2*outsize)
3658 requiredsize = 2*outsize;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003659 if (PyUnicode_Resize(output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003660 goto onError;
3661 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003662 }
3663 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003664 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003665 Py_UNICODE_COPY(*outptr, repptr, repsize);
3666 *outptr += repsize;
3667 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003668
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003669 /* we made it! */
3670 res = 0;
3671
Benjamin Peterson29060642009-01-31 22:14:21 +00003672 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003673 Py_XDECREF(restuple);
3674 return res;
3675}
3676
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003677/* --- UTF-7 Codec -------------------------------------------------------- */
3678
Antoine Pitrou244651a2009-05-04 18:56:13 +00003679/* See RFC2152 for details. We encode conservatively and decode liberally. */
3680
3681/* Three simple macros defining base-64. */
3682
3683/* Is c a base-64 character? */
3684
3685#define IS_BASE64(c) \
3686 (((c) >= 'A' && (c) <= 'Z') || \
3687 ((c) >= 'a' && (c) <= 'z') || \
3688 ((c) >= '0' && (c) <= '9') || \
3689 (c) == '+' || (c) == '/')
3690
3691/* given that c is a base-64 character, what is its base-64 value? */
3692
3693#define FROM_BASE64(c) \
3694 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3695 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3696 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3697 (c) == '+' ? 62 : 63)
3698
3699/* What is the base-64 character of the bottom 6 bits of n? */
3700
3701#define TO_BASE64(n) \
3702 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3703
3704/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3705 * decoded as itself. We are permissive on decoding; the only ASCII
3706 * byte not decoding to itself is the + which begins a base64
3707 * string. */
3708
3709#define DECODE_DIRECT(c) \
3710 ((c) <= 127 && (c) != '+')
3711
3712/* The UTF-7 encoder treats ASCII characters differently according to
3713 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3714 * the above). See RFC2152. This array identifies these different
3715 * sets:
3716 * 0 : "Set D"
3717 * alphanumeric and '(),-./:?
3718 * 1 : "Set O"
3719 * !"#$%&*;<=>@[]^_`{|}
3720 * 2 : "whitespace"
3721 * ht nl cr sp
3722 * 3 : special (must be base64 encoded)
3723 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3724 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003725
Tim Petersced69f82003-09-16 20:30:58 +00003726static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003727char utf7_category[128] = {
3728/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3729 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3730/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3731 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3732/* sp ! " # $ % & ' ( ) * + , - . / */
3733 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3734/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3735 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3736/* @ A B C D E F G H I J K L M N O */
3737 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3738/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3739 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3740/* ` a b c d e f g h i j k l m n o */
3741 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3742/* p q r s t u v w x y z { | } ~ del */
3743 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003744};
3745
Antoine Pitrou244651a2009-05-04 18:56:13 +00003746/* ENCODE_DIRECT: this character should be encoded as itself. The
3747 * answer depends on whether we are encoding set O as itself, and also
3748 * on whether we are encoding whitespace as itself. RFC2152 makes it
3749 * clear that the answers to these questions vary between
3750 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003751
Antoine Pitrou244651a2009-05-04 18:56:13 +00003752#define ENCODE_DIRECT(c, directO, directWS) \
3753 ((c) < 128 && (c) > 0 && \
3754 ((utf7_category[(c)] == 0) || \
3755 (directWS && (utf7_category[(c)] == 2)) || \
3756 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003757
Alexander Belopolsky40018472011-02-26 01:02:56 +00003758PyObject *
3759PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003760 Py_ssize_t size,
3761 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003762{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003763 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3764}
3765
Antoine Pitrou244651a2009-05-04 18:56:13 +00003766/* The decoder. The only state we preserve is our read position,
3767 * i.e. how many characters we have consumed. So if we end in the
3768 * middle of a shift sequence we have to back off the read position
3769 * and the output to the beginning of the sequence, otherwise we lose
3770 * all the shift state (seen bits, number of bits seen, high
3771 * surrogate). */
3772
Alexander Belopolsky40018472011-02-26 01:02:56 +00003773PyObject *
3774PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003775 Py_ssize_t size,
3776 const char *errors,
3777 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003778{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003779 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003780 Py_ssize_t startinpos;
3781 Py_ssize_t endinpos;
3782 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003783 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003784 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003785 Py_UNICODE *p;
3786 const char *errmsg = "";
3787 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003788 Py_UNICODE *shiftOutStart;
3789 unsigned int base64bits = 0;
3790 unsigned long base64buffer = 0;
3791 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003792 PyObject *errorHandler = NULL;
3793 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003794
Victor Stinner7931d9a2011-11-04 00:22:48 +01003795 unicode = (PyObject*)_PyUnicode_New(size);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003796 if (!unicode)
3797 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003798 if (size == 0) {
3799 if (consumed)
3800 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003801 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003802 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003803
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003804 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003805 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003806 e = s + size;
3807
3808 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003809 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003810 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003811 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003812
Antoine Pitrou244651a2009-05-04 18:56:13 +00003813 if (inShift) { /* in a base-64 section */
3814 if (IS_BASE64(ch)) { /* consume a base-64 character */
3815 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3816 base64bits += 6;
3817 s++;
3818 if (base64bits >= 16) {
3819 /* we have enough bits for a UTF-16 value */
3820 Py_UNICODE outCh = (Py_UNICODE)
3821 (base64buffer >> (base64bits-16));
3822 base64bits -= 16;
3823 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3824 if (surrogate) {
3825 /* expecting a second surrogate */
3826 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3827#ifdef Py_UNICODE_WIDE
3828 *p++ = (((surrogate & 0x3FF)<<10)
3829 | (outCh & 0x3FF)) + 0x10000;
3830#else
3831 *p++ = surrogate;
3832 *p++ = outCh;
3833#endif
3834 surrogate = 0;
3835 }
3836 else {
3837 surrogate = 0;
3838 errmsg = "second surrogate missing";
3839 goto utf7Error;
3840 }
3841 }
3842 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3843 /* first surrogate */
3844 surrogate = outCh;
3845 }
3846 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3847 errmsg = "unexpected second surrogate";
3848 goto utf7Error;
3849 }
3850 else {
3851 *p++ = outCh;
3852 }
3853 }
3854 }
3855 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003856 inShift = 0;
3857 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003858 if (surrogate) {
3859 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003860 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003861 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003862 if (base64bits > 0) { /* left-over bits */
3863 if (base64bits >= 6) {
3864 /* We've seen at least one base-64 character */
3865 errmsg = "partial character in shift sequence";
3866 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003867 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003868 else {
3869 /* Some bits remain; they should be zero */
3870 if (base64buffer != 0) {
3871 errmsg = "non-zero padding bits in shift sequence";
3872 goto utf7Error;
3873 }
3874 }
3875 }
3876 if (ch != '-') {
3877 /* '-' is absorbed; other terminating
3878 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003879 *p++ = ch;
3880 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003881 }
3882 }
3883 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003884 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003885 s++; /* consume '+' */
3886 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003887 s++;
3888 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003889 }
3890 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003891 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003892 shiftOutStart = p;
3893 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003894 }
3895 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003896 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003897 *p++ = ch;
3898 s++;
3899 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003900 else {
3901 startinpos = s-starts;
3902 s++;
3903 errmsg = "unexpected special character";
3904 goto utf7Error;
3905 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003906 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003907utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003908 outpos = p-PyUnicode_AS_UNICODE(unicode);
3909 endinpos = s-starts;
3910 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003911 errors, &errorHandler,
3912 "utf7", errmsg,
3913 &starts, &e, &startinpos, &endinpos, &exc, &s,
3914 &unicode, &outpos, &p))
3915 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003916 }
3917
Antoine Pitrou244651a2009-05-04 18:56:13 +00003918 /* end of string */
3919
3920 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3921 /* if we're in an inconsistent state, that's an error */
3922 if (surrogate ||
3923 (base64bits >= 6) ||
3924 (base64bits > 0 && base64buffer != 0)) {
3925 outpos = p-PyUnicode_AS_UNICODE(unicode);
3926 endinpos = size;
3927 if (unicode_decode_call_errorhandler(
3928 errors, &errorHandler,
3929 "utf7", "unterminated shift sequence",
3930 &starts, &e, &startinpos, &endinpos, &exc, &s,
3931 &unicode, &outpos, &p))
3932 goto onError;
3933 if (s < e)
3934 goto restart;
3935 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003936 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003937
3938 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003939 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003940 if (inShift) {
3941 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003942 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003943 }
3944 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003945 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003946 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003947 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003948
Victor Stinner7931d9a2011-11-04 00:22:48 +01003949 if (PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003950 goto onError;
3951
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003952 Py_XDECREF(errorHandler);
3953 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003954#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003955 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003956 Py_DECREF(unicode);
3957 return NULL;
3958 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003959#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003960 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01003961 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003962
Benjamin Peterson29060642009-01-31 22:14:21 +00003963 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003964 Py_XDECREF(errorHandler);
3965 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003966 Py_DECREF(unicode);
3967 return NULL;
3968}
3969
3970
Alexander Belopolsky40018472011-02-26 01:02:56 +00003971PyObject *
3972PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003973 Py_ssize_t size,
3974 int base64SetO,
3975 int base64WhiteSpace,
3976 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003977{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003978 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003979 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003980 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003981 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003982 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003983 unsigned int base64bits = 0;
3984 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003985 char * out;
3986 char * start;
3987
3988 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003989 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003990
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003991 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003992 return PyErr_NoMemory();
3993
Antoine Pitrou244651a2009-05-04 18:56:13 +00003994 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003995 if (v == NULL)
3996 return NULL;
3997
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003998 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003999 for (;i < size; ++i) {
4000 Py_UNICODE ch = s[i];
4001
Antoine Pitrou244651a2009-05-04 18:56:13 +00004002 if (inShift) {
4003 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4004 /* shifting out */
4005 if (base64bits) { /* output remaining bits */
4006 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4007 base64buffer = 0;
4008 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004009 }
4010 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004011 /* Characters not in the BASE64 set implicitly unshift the sequence
4012 so no '-' is required, except if the character is itself a '-' */
4013 if (IS_BASE64(ch) || ch == '-') {
4014 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004015 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004016 *out++ = (char) ch;
4017 }
4018 else {
4019 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004020 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004021 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004022 else { /* not in a shift sequence */
4023 if (ch == '+') {
4024 *out++ = '+';
4025 *out++ = '-';
4026 }
4027 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4028 *out++ = (char) ch;
4029 }
4030 else {
4031 *out++ = '+';
4032 inShift = 1;
4033 goto encode_char;
4034 }
4035 }
4036 continue;
4037encode_char:
4038#ifdef Py_UNICODE_WIDE
4039 if (ch >= 0x10000) {
4040 /* code first surrogate */
4041 base64bits += 16;
4042 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4043 while (base64bits >= 6) {
4044 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4045 base64bits -= 6;
4046 }
4047 /* prepare second surrogate */
4048 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4049 }
4050#endif
4051 base64bits += 16;
4052 base64buffer = (base64buffer << 16) | ch;
4053 while (base64bits >= 6) {
4054 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4055 base64bits -= 6;
4056 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004057 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004058 if (base64bits)
4059 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4060 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004061 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004062 if (_PyBytes_Resize(&v, out - start) < 0)
4063 return NULL;
4064 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004065}
4066
Antoine Pitrou244651a2009-05-04 18:56:13 +00004067#undef IS_BASE64
4068#undef FROM_BASE64
4069#undef TO_BASE64
4070#undef DECODE_DIRECT
4071#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004072
Guido van Rossumd57fd912000-03-10 22:53:23 +00004073/* --- UTF-8 Codec -------------------------------------------------------- */
4074
Tim Petersced69f82003-09-16 20:30:58 +00004075static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004076char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004077 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4078 illegal prefix. See RFC 3629 for details */
4079 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004081 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004082 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4083 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,
Ezio Melotti57221d02010-07-01 07:32:02 +00004086 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4087 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 +00004088 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4089 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004090 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4091 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4092 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4093 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4094 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 +00004095};
4096
Alexander Belopolsky40018472011-02-26 01:02:56 +00004097PyObject *
4098PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004099 Py_ssize_t size,
4100 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004101{
Walter Dörwald69652032004-09-07 20:24:22 +00004102 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4103}
4104
Antoine Pitrouab868312009-01-10 15:40:25 +00004105/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4106#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4107
4108/* Mask to quickly check whether a C 'long' contains a
4109 non-ASCII, UTF8-encoded char. */
4110#if (SIZEOF_LONG == 8)
4111# define ASCII_CHAR_MASK 0x8080808080808080L
4112#elif (SIZEOF_LONG == 4)
4113# define ASCII_CHAR_MASK 0x80808080L
4114#else
4115# error C 'long' size should be either 4 or 8!
4116#endif
4117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004118/* Scans a UTF-8 string and returns the maximum character to be expected,
4119 the size of the decoded unicode string and if any major errors were
4120 encountered.
4121
4122 This function does check basic UTF-8 sanity, it does however NOT CHECK
4123 if the string contains surrogates, and if all continuation bytes are
4124 within the correct ranges, these checks are performed in
4125 PyUnicode_DecodeUTF8Stateful.
4126
4127 If it sets has_errors to 1, it means the value of unicode_size and max_char
4128 will be bogus and you should not rely on useful information in them.
4129 */
4130static Py_UCS4
4131utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4132 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4133 int *has_errors)
4134{
4135 Py_ssize_t n;
4136 Py_ssize_t char_count = 0;
4137 Py_UCS4 max_char = 127, new_max;
4138 Py_UCS4 upper_bound;
4139 const unsigned char *p = (const unsigned char *)s;
4140 const unsigned char *end = p + string_size;
4141 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4142 int err = 0;
4143
4144 for (; p < end && !err; ++p, ++char_count) {
4145 /* Only check value if it's not a ASCII char... */
4146 if (*p < 0x80) {
4147 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4148 an explanation. */
4149 if (!((size_t) p & LONG_PTR_MASK)) {
4150 /* Help register allocation */
4151 register const unsigned char *_p = p;
4152 while (_p < aligned_end) {
4153 unsigned long value = *(unsigned long *) _p;
4154 if (value & ASCII_CHAR_MASK)
4155 break;
4156 _p += SIZEOF_LONG;
4157 char_count += SIZEOF_LONG;
4158 }
4159 p = _p;
4160 if (p == end)
4161 break;
4162 }
4163 }
4164 if (*p >= 0x80) {
4165 n = utf8_code_length[*p];
4166 new_max = max_char;
4167 switch (n) {
4168 /* invalid start byte */
4169 case 0:
4170 err = 1;
4171 break;
4172 case 2:
4173 /* Code points between 0x00FF and 0x07FF inclusive.
4174 Approximate the upper bound of the code point,
4175 if this flips over 255 we can be sure it will be more
4176 than 255 and the string will need 2 bytes per code coint,
4177 if it stays under or equal to 255, we can be sure 1 byte
4178 is enough.
4179 ((*p & 0b00011111) << 6) | 0b00111111 */
4180 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4181 if (max_char < upper_bound)
4182 new_max = upper_bound;
4183 /* Ensure we track at least that we left ASCII space. */
4184 if (new_max < 128)
4185 new_max = 128;
4186 break;
4187 case 3:
4188 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4189 always > 255 and <= 65535 and will always need 2 bytes. */
4190 if (max_char < 65535)
4191 new_max = 65535;
4192 break;
4193 case 4:
4194 /* Code point will be above 0xFFFF for sure in this case. */
4195 new_max = 65537;
4196 break;
4197 /* Internal error, this should be caught by the first if */
4198 case 1:
4199 default:
4200 assert(0 && "Impossible case in utf8_max_char_and_size");
4201 err = 1;
4202 }
4203 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004204 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004205 --n;
4206 /* Check if the follow up chars are all valid continuation bytes */
4207 if (n >= 1) {
4208 const unsigned char *cont;
4209 if ((p + n) >= end) {
4210 if (consumed == 0)
4211 /* incomplete data, non-incremental decoding */
4212 err = 1;
4213 break;
4214 }
4215 for (cont = p + 1; cont < (p + n); ++cont) {
4216 if ((*cont & 0xc0) != 0x80) {
4217 err = 1;
4218 break;
4219 }
4220 }
4221 p += n;
4222 }
4223 else
4224 err = 1;
4225 max_char = new_max;
4226 }
4227 }
4228
4229 if (unicode_size)
4230 *unicode_size = char_count;
4231 if (has_errors)
4232 *has_errors = err;
4233 return max_char;
4234}
4235
4236/* Similar to PyUnicode_WRITE but can also write into wstr field
4237 of the legacy unicode representation */
4238#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4239 do { \
4240 const int k_ = (kind); \
4241 if (k_ == PyUnicode_WCHAR_KIND) \
4242 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4243 else if (k_ == PyUnicode_1BYTE_KIND) \
4244 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4245 else if (k_ == PyUnicode_2BYTE_KIND) \
4246 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4247 else \
4248 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4249 } while (0)
4250
Alexander Belopolsky40018472011-02-26 01:02:56 +00004251PyObject *
4252PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004253 Py_ssize_t size,
4254 const char *errors,
4255 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004256{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004257 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004258 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004259 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004260 Py_ssize_t startinpos;
4261 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004262 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004263 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004264 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004265 PyObject *errorHandler = NULL;
4266 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004267 Py_UCS4 maxchar = 0;
4268 Py_ssize_t unicode_size;
4269 Py_ssize_t i;
4270 int kind;
4271 void *data;
4272 int has_errors;
4273 Py_UNICODE *error_outptr;
4274#if SIZEOF_WCHAR_T == 2
4275 Py_ssize_t wchar_offset = 0;
4276#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004277
Walter Dörwald69652032004-09-07 20:24:22 +00004278 if (size == 0) {
4279 if (consumed)
4280 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004281 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004282 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004283 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4284 consumed, &has_errors);
4285 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004286 unicode = (PyObject*)_PyUnicode_New(size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004287 if (!unicode)
4288 return NULL;
4289 kind = PyUnicode_WCHAR_KIND;
4290 data = PyUnicode_AS_UNICODE(unicode);
4291 assert(data != NULL);
4292 }
4293 else {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004294 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004295 if (!unicode)
4296 return NULL;
4297 /* When the string is ASCII only, just use memcpy and return.
4298 unicode_size may be != size if there is an incomplete UTF-8
4299 sequence at the end of the ASCII block. */
4300 if (maxchar < 128 && size == unicode_size) {
4301 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
Victor Stinner7931d9a2011-11-04 00:22:48 +01004302 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004303 }
4304 kind = PyUnicode_KIND(unicode);
4305 data = PyUnicode_DATA(unicode);
4306 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004307 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004308 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004309 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004310 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004311
4312 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004313 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004314
4315 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004316 /* Fast path for runs of ASCII characters. Given that common UTF-8
4317 input will consist of an overwhelming majority of ASCII
4318 characters, we try to optimize for this case by checking
4319 as many characters as a C 'long' can contain.
4320 First, check if we can do an aligned read, as most CPUs have
4321 a penalty for unaligned reads.
4322 */
4323 if (!((size_t) s & LONG_PTR_MASK)) {
4324 /* Help register allocation */
4325 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004326 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004327 while (_s < aligned_end) {
4328 /* Read a whole long at a time (either 4 or 8 bytes),
4329 and do a fast unrolled copy if it only contains ASCII
4330 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004331 unsigned long value = *(unsigned long *) _s;
4332 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004333 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004334 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4335 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4336 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4337 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004338#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004339 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4340 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4341 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4342 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004343#endif
4344 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004345 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004346 }
4347 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004348 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004349 if (s == e)
4350 break;
4351 ch = (unsigned char)*s;
4352 }
4353 }
4354
4355 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004356 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004357 s++;
4358 continue;
4359 }
4360
4361 n = utf8_code_length[ch];
4362
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004363 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004364 if (consumed)
4365 break;
4366 else {
4367 errmsg = "unexpected end of data";
4368 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004369 endinpos = startinpos+1;
4370 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4371 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004372 goto utf8Error;
4373 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004374 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004375
4376 switch (n) {
4377
4378 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004379 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004380 startinpos = s-starts;
4381 endinpos = startinpos+1;
4382 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004383
4384 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004385 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004386 startinpos = s-starts;
4387 endinpos = startinpos+1;
4388 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004389
4390 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004391 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004392 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004393 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004394 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004395 goto utf8Error;
4396 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004397 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004398 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004399 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004400 break;
4401
4402 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004403 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4404 will result in surrogates in range d800-dfff. Surrogates are
4405 not valid UTF-8 so they are rejected.
4406 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4407 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004408 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004409 (s[2] & 0xc0) != 0x80 ||
4410 ((unsigned char)s[0] == 0xE0 &&
4411 (unsigned char)s[1] < 0xA0) ||
4412 ((unsigned char)s[0] == 0xED &&
4413 (unsigned char)s[1] > 0x9F)) {
4414 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004415 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004416 endinpos = startinpos + 1;
4417
4418 /* if s[1] first two bits are 1 and 0, then the invalid
4419 continuation byte is s[2], so increment endinpos by 1,
4420 if not, s[1] is invalid and endinpos doesn't need to
4421 be incremented. */
4422 if ((s[1] & 0xC0) == 0x80)
4423 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004424 goto utf8Error;
4425 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004426 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004427 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004428 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004429 break;
4430
4431 case 4:
4432 if ((s[1] & 0xc0) != 0x80 ||
4433 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004434 (s[3] & 0xc0) != 0x80 ||
4435 ((unsigned char)s[0] == 0xF0 &&
4436 (unsigned char)s[1] < 0x90) ||
4437 ((unsigned char)s[0] == 0xF4 &&
4438 (unsigned char)s[1] > 0x8F)) {
4439 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004440 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004441 endinpos = startinpos + 1;
4442 if ((s[1] & 0xC0) == 0x80) {
4443 endinpos++;
4444 if ((s[2] & 0xC0) == 0x80)
4445 endinpos++;
4446 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 goto utf8Error;
4448 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004449 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004450 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4451 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004453 /* If the string is flexible or we have native UCS-4, write
4454 directly.. */
4455 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4456 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004458 else {
4459 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004460
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004461 /* translate from 10000..10FFFF to 0..FFFF */
4462 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004463
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004464 /* high surrogate = top 10 bits added to D800 */
4465 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4466 (Py_UNICODE)(0xD800 + (ch >> 10)));
4467
4468 /* low surrogate = bottom 10 bits added to DC00 */
4469 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4470 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4471 }
4472#if SIZEOF_WCHAR_T == 2
4473 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004474#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004475 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004476 }
4477 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004478 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004479
Benjamin Peterson29060642009-01-31 22:14:21 +00004480 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004481 /* If this is not yet a resizable string, make it one.. */
4482 if (kind != PyUnicode_WCHAR_KIND) {
4483 const Py_UNICODE *u;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004484 PyObject *new_unicode = (PyObject*)_PyUnicode_New(size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004485 if (!new_unicode)
4486 goto onError;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004487 u = PyUnicode_AsUnicode(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004488 if (!u)
4489 goto onError;
4490#if SIZEOF_WCHAR_T == 2
4491 i += wchar_offset;
4492#endif
4493 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4494 Py_DECREF(unicode);
4495 unicode = new_unicode;
4496 kind = 0;
4497 data = PyUnicode_AS_UNICODE(new_unicode);
4498 assert(data != NULL);
4499 }
4500 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 if (unicode_decode_call_errorhandler(
4502 errors, &errorHandler,
4503 "utf8", errmsg,
4504 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004505 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004506 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507 /* Update data because unicode_decode_call_errorhandler might have
4508 re-created or resized the unicode object. */
4509 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004511 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004512 /* Ensure the unicode_size calculation above was correct: */
4513 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4514
Walter Dörwald69652032004-09-07 20:24:22 +00004515 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004516 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004518 /* Adjust length and ready string when it contained errors and
4519 is of the old resizable kind. */
4520 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004521 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004522 goto onError;
4523 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004524
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004525 Py_XDECREF(errorHandler);
4526 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004527#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004528 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004529 Py_DECREF(unicode);
4530 return NULL;
4531 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004532#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004533 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004534 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004535
Benjamin Peterson29060642009-01-31 22:14:21 +00004536 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004537 Py_XDECREF(errorHandler);
4538 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004539 Py_DECREF(unicode);
4540 return NULL;
4541}
4542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004543#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004544
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004545#ifdef __APPLE__
4546
4547/* Simplified UTF-8 decoder using surrogateescape error handler,
4548 used to decode the command line arguments on Mac OS X. */
4549
4550wchar_t*
4551_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4552{
4553 int n;
4554 const char *e;
4555 wchar_t *unicode, *p;
4556
4557 /* Note: size will always be longer than the resulting Unicode
4558 character count */
4559 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4560 PyErr_NoMemory();
4561 return NULL;
4562 }
4563 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4564 if (!unicode)
4565 return NULL;
4566
4567 /* Unpack UTF-8 encoded data */
4568 p = unicode;
4569 e = s + size;
4570 while (s < e) {
4571 Py_UCS4 ch = (unsigned char)*s;
4572
4573 if (ch < 0x80) {
4574 *p++ = (wchar_t)ch;
4575 s++;
4576 continue;
4577 }
4578
4579 n = utf8_code_length[ch];
4580 if (s + n > e) {
4581 goto surrogateescape;
4582 }
4583
4584 switch (n) {
4585 case 0:
4586 case 1:
4587 goto surrogateescape;
4588
4589 case 2:
4590 if ((s[1] & 0xc0) != 0x80)
4591 goto surrogateescape;
4592 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4593 assert ((ch > 0x007F) && (ch <= 0x07FF));
4594 *p++ = (wchar_t)ch;
4595 break;
4596
4597 case 3:
4598 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4599 will result in surrogates in range d800-dfff. Surrogates are
4600 not valid UTF-8 so they are rejected.
4601 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4602 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4603 if ((s[1] & 0xc0) != 0x80 ||
4604 (s[2] & 0xc0) != 0x80 ||
4605 ((unsigned char)s[0] == 0xE0 &&
4606 (unsigned char)s[1] < 0xA0) ||
4607 ((unsigned char)s[0] == 0xED &&
4608 (unsigned char)s[1] > 0x9F)) {
4609
4610 goto surrogateescape;
4611 }
4612 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4613 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004614 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004615 break;
4616
4617 case 4:
4618 if ((s[1] & 0xc0) != 0x80 ||
4619 (s[2] & 0xc0) != 0x80 ||
4620 (s[3] & 0xc0) != 0x80 ||
4621 ((unsigned char)s[0] == 0xF0 &&
4622 (unsigned char)s[1] < 0x90) ||
4623 ((unsigned char)s[0] == 0xF4 &&
4624 (unsigned char)s[1] > 0x8F)) {
4625 goto surrogateescape;
4626 }
4627 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4628 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4629 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4630
4631#if SIZEOF_WCHAR_T == 4
4632 *p++ = (wchar_t)ch;
4633#else
4634 /* compute and append the two surrogates: */
4635
4636 /* translate from 10000..10FFFF to 0..FFFF */
4637 ch -= 0x10000;
4638
4639 /* high surrogate = top 10 bits added to D800 */
4640 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4641
4642 /* low surrogate = bottom 10 bits added to DC00 */
4643 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4644#endif
4645 break;
4646 }
4647 s += n;
4648 continue;
4649
4650 surrogateescape:
4651 *p++ = 0xDC00 + ch;
4652 s++;
4653 }
4654 *p = L'\0';
4655 return unicode;
4656}
4657
4658#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004659
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004660/* Primary internal function which creates utf8 encoded bytes objects.
4661
4662 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004663 and allocate exactly as much space needed at the end. Else allocate the
4664 maximum possible needed (4 result bytes per Unicode character), and return
4665 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004666*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004667PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004668_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004669{
Tim Peters602f7402002-04-27 18:03:26 +00004670#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004671
Guido van Rossum98297ee2007-11-06 21:34:58 +00004672 Py_ssize_t i; /* index into s of next input byte */
4673 PyObject *result; /* result string object */
4674 char *p; /* next free byte in output buffer */
4675 Py_ssize_t nallocated; /* number of result bytes allocated */
4676 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004677 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004678 PyObject *errorHandler = NULL;
4679 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004680 int kind;
4681 void *data;
4682 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004683
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004684 if (!PyUnicode_Check(unicode)) {
4685 PyErr_BadArgument();
4686 return NULL;
4687 }
4688
4689 if (PyUnicode_READY(unicode) == -1)
4690 return NULL;
4691
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004692 if (PyUnicode_UTF8(unicode))
4693 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4694 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004695
4696 kind = PyUnicode_KIND(unicode);
4697 data = PyUnicode_DATA(unicode);
4698 size = PyUnicode_GET_LENGTH(unicode);
4699
Tim Peters602f7402002-04-27 18:03:26 +00004700 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004701
Tim Peters602f7402002-04-27 18:03:26 +00004702 if (size <= MAX_SHORT_UNICHARS) {
4703 /* Write into the stack buffer; nallocated can't overflow.
4704 * At the end, we'll allocate exactly as much heap space as it
4705 * turns out we need.
4706 */
4707 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004708 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004709 p = stackbuf;
4710 }
4711 else {
4712 /* Overallocate on the heap, and give the excess back at the end. */
4713 nallocated = size * 4;
4714 if (nallocated / 4 != size) /* overflow! */
4715 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004716 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004717 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004718 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004719 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004720 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004721
Tim Peters602f7402002-04-27 18:03:26 +00004722 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004723 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004724
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004725 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004726 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004727 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004728
Guido van Rossumd57fd912000-03-10 22:53:23 +00004729 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004730 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004731 *p++ = (char)(0xc0 | (ch >> 6));
4732 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004733 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004734 Py_ssize_t newpos;
4735 PyObject *rep;
4736 Py_ssize_t repsize, k, startpos;
4737 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004738 rep = unicode_encode_call_errorhandler(
4739 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004740 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004741 if (!rep)
4742 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004743
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004744 if (PyBytes_Check(rep))
4745 repsize = PyBytes_GET_SIZE(rep);
4746 else
4747 repsize = PyUnicode_GET_SIZE(rep);
4748
4749 if (repsize > 4) {
4750 Py_ssize_t offset;
4751
4752 if (result == NULL)
4753 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004754 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004755 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004757 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4758 /* integer overflow */
4759 PyErr_NoMemory();
4760 goto error;
4761 }
4762 nallocated += repsize - 4;
4763 if (result != NULL) {
4764 if (_PyBytes_Resize(&result, nallocated) < 0)
4765 goto error;
4766 } else {
4767 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004768 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004769 goto error;
4770 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4771 }
4772 p = PyBytes_AS_STRING(result) + offset;
4773 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004775 if (PyBytes_Check(rep)) {
4776 char *prep = PyBytes_AS_STRING(rep);
4777 for(k = repsize; k > 0; k--)
4778 *p++ = *prep++;
4779 } else /* rep is unicode */ {
4780 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4781 Py_UNICODE c;
4782
4783 for(k=0; k<repsize; k++) {
4784 c = prep[k];
4785 if (0x80 <= c) {
Martin v. Löwis9e816682011-11-02 12:45:42 +01004786 raise_encode_exception_obj(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004787 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004788 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004789 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004790 goto error;
4791 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004792 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004793 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004794 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004795 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004796 } else if (ch < 0x10000) {
4797 *p++ = (char)(0xe0 | (ch >> 12));
4798 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4799 *p++ = (char)(0x80 | (ch & 0x3f));
4800 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004801 /* Encode UCS4 Unicode ordinals */
4802 *p++ = (char)(0xf0 | (ch >> 18));
4803 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4804 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4805 *p++ = (char)(0x80 | (ch & 0x3f));
4806 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004807 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004808
Guido van Rossum98297ee2007-11-06 21:34:58 +00004809 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004810 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004811 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004812 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004813 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004814 }
4815 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004816 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004817 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004818 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004819 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004820 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004821
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004822 Py_XDECREF(errorHandler);
4823 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004824 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004825 error:
4826 Py_XDECREF(errorHandler);
4827 Py_XDECREF(exc);
4828 Py_XDECREF(result);
4829 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004830
Tim Peters602f7402002-04-27 18:03:26 +00004831#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004832}
4833
Alexander Belopolsky40018472011-02-26 01:02:56 +00004834PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004835PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4836 Py_ssize_t size,
4837 const char *errors)
4838{
4839 PyObject *v, *unicode;
4840
4841 unicode = PyUnicode_FromUnicode(s, size);
4842 if (unicode == NULL)
4843 return NULL;
4844 v = _PyUnicode_AsUTF8String(unicode, errors);
4845 Py_DECREF(unicode);
4846 return v;
4847}
4848
4849PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004850PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004852 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004853}
4854
Walter Dörwald41980ca2007-08-16 21:55:45 +00004855/* --- UTF-32 Codec ------------------------------------------------------- */
4856
4857PyObject *
4858PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004859 Py_ssize_t size,
4860 const char *errors,
4861 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004862{
4863 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4864}
4865
4866PyObject *
4867PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004868 Py_ssize_t size,
4869 const char *errors,
4870 int *byteorder,
4871 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004872{
4873 const char *starts = s;
4874 Py_ssize_t startinpos;
4875 Py_ssize_t endinpos;
4876 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004877 PyObject *unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004878 Py_UNICODE *p;
4879#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004880 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004881 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004882#else
4883 const int pairs = 0;
4884#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004885 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004886 int bo = 0; /* assume native ordering by default */
4887 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004888 /* Offsets from q for retrieving bytes in the right order. */
4889#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4890 int iorder[] = {0, 1, 2, 3};
4891#else
4892 int iorder[] = {3, 2, 1, 0};
4893#endif
4894 PyObject *errorHandler = NULL;
4895 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004896
Walter Dörwald41980ca2007-08-16 21:55:45 +00004897 q = (unsigned char *)s;
4898 e = q + size;
4899
4900 if (byteorder)
4901 bo = *byteorder;
4902
4903 /* Check for BOM marks (U+FEFF) in the input and adjust current
4904 byte order setting accordingly. In native mode, the leading BOM
4905 mark is skipped, in all other modes, it is copied to the output
4906 stream as-is (giving a ZWNBSP character). */
4907 if (bo == 0) {
4908 if (size >= 4) {
4909 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004910 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004911#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004912 if (bom == 0x0000FEFF) {
4913 q += 4;
4914 bo = -1;
4915 }
4916 else if (bom == 0xFFFE0000) {
4917 q += 4;
4918 bo = 1;
4919 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004920#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004921 if (bom == 0x0000FEFF) {
4922 q += 4;
4923 bo = 1;
4924 }
4925 else if (bom == 0xFFFE0000) {
4926 q += 4;
4927 bo = -1;
4928 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004929#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004930 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931 }
4932
4933 if (bo == -1) {
4934 /* force LE */
4935 iorder[0] = 0;
4936 iorder[1] = 1;
4937 iorder[2] = 2;
4938 iorder[3] = 3;
4939 }
4940 else if (bo == 1) {
4941 /* force BE */
4942 iorder[0] = 3;
4943 iorder[1] = 2;
4944 iorder[2] = 1;
4945 iorder[3] = 0;
4946 }
4947
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004948 /* On narrow builds we split characters outside the BMP into two
4949 codepoints => count how much extra space we need. */
4950#ifndef Py_UNICODE_WIDE
4951 for (qq = q; qq < e; qq += 4)
4952 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4953 pairs++;
4954#endif
4955
4956 /* This might be one to much, because of a BOM */
Victor Stinner7931d9a2011-11-04 00:22:48 +01004957 unicode = (PyObject*)_PyUnicode_New((size+3)/4+pairs);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004958 if (!unicode)
4959 return NULL;
4960 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004961 return unicode;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004962
4963 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004964 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004965
Walter Dörwald41980ca2007-08-16 21:55:45 +00004966 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004967 Py_UCS4 ch;
4968 /* remaining bytes at the end? (size should be divisible by 4) */
4969 if (e-q<4) {
4970 if (consumed)
4971 break;
4972 errmsg = "truncated data";
4973 startinpos = ((const char *)q)-starts;
4974 endinpos = ((const char *)e)-starts;
4975 goto utf32Error;
4976 /* The remaining input chars are ignored if the callback
4977 chooses to skip the input */
4978 }
4979 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4980 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004981
Benjamin Peterson29060642009-01-31 22:14:21 +00004982 if (ch >= 0x110000)
4983 {
4984 errmsg = "codepoint not in range(0x110000)";
4985 startinpos = ((const char *)q)-starts;
4986 endinpos = startinpos+4;
4987 goto utf32Error;
4988 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004989#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004990 if (ch >= 0x10000)
4991 {
4992 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4993 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4994 }
4995 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00004996#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004997 *p++ = ch;
4998 q += 4;
4999 continue;
5000 utf32Error:
5001 outpos = p-PyUnicode_AS_UNICODE(unicode);
5002 if (unicode_decode_call_errorhandler(
5003 errors, &errorHandler,
5004 "utf32", errmsg,
5005 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5006 &unicode, &outpos, &p))
5007 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005008 }
5009
5010 if (byteorder)
5011 *byteorder = bo;
5012
5013 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005014 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005015
5016 /* Adjust length */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005017 if (PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005018 goto onError;
5019
5020 Py_XDECREF(errorHandler);
5021 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005022#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005023 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005024 Py_DECREF(unicode);
5025 return NULL;
5026 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005027#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005028 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005029 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005030
Benjamin Peterson29060642009-01-31 22:14:21 +00005031 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005032 Py_DECREF(unicode);
5033 Py_XDECREF(errorHandler);
5034 Py_XDECREF(exc);
5035 return NULL;
5036}
5037
5038PyObject *
5039PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005040 Py_ssize_t size,
5041 const char *errors,
5042 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005044 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005046 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005047#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005048 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005049#else
5050 const int pairs = 0;
5051#endif
5052 /* Offsets from p for storing byte pairs in the right order. */
5053#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5054 int iorder[] = {0, 1, 2, 3};
5055#else
5056 int iorder[] = {3, 2, 1, 0};
5057#endif
5058
Benjamin Peterson29060642009-01-31 22:14:21 +00005059#define STORECHAR(CH) \
5060 do { \
5061 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5062 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5063 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5064 p[iorder[0]] = (CH) & 0xff; \
5065 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005066 } while(0)
5067
5068 /* In narrow builds we can output surrogate pairs as one codepoint,
5069 so we need less space. */
5070#ifndef Py_UNICODE_WIDE
5071 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005072 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5073 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5074 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005075#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005076 nsize = (size - pairs + (byteorder == 0));
5077 bytesize = nsize * 4;
5078 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005079 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005080 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005081 if (v == NULL)
5082 return NULL;
5083
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005084 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005085 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005086 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005087 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005088 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005089
5090 if (byteorder == -1) {
5091 /* force LE */
5092 iorder[0] = 0;
5093 iorder[1] = 1;
5094 iorder[2] = 2;
5095 iorder[3] = 3;
5096 }
5097 else if (byteorder == 1) {
5098 /* force BE */
5099 iorder[0] = 3;
5100 iorder[1] = 2;
5101 iorder[2] = 1;
5102 iorder[3] = 0;
5103 }
5104
5105 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005106 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005107#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005108 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5109 Py_UCS4 ch2 = *s;
5110 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5111 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5112 s++;
5113 size--;
5114 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005115 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005116#endif
5117 STORECHAR(ch);
5118 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005119
5120 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005121 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005122#undef STORECHAR
5123}
5124
Alexander Belopolsky40018472011-02-26 01:02:56 +00005125PyObject *
5126PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005127{
5128 if (!PyUnicode_Check(unicode)) {
5129 PyErr_BadArgument();
5130 return NULL;
5131 }
5132 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005133 PyUnicode_GET_SIZE(unicode),
5134 NULL,
5135 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005136}
5137
Guido van Rossumd57fd912000-03-10 22:53:23 +00005138/* --- UTF-16 Codec ------------------------------------------------------- */
5139
Tim Peters772747b2001-08-09 22:21:55 +00005140PyObject *
5141PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005142 Py_ssize_t size,
5143 const char *errors,
5144 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005145{
Walter Dörwald69652032004-09-07 20:24:22 +00005146 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5147}
5148
Antoine Pitrouab868312009-01-10 15:40:25 +00005149/* Two masks for fast checking of whether a C 'long' may contain
5150 UTF16-encoded surrogate characters. This is an efficient heuristic,
5151 assuming that non-surrogate characters with a code point >= 0x8000 are
5152 rare in most input.
5153 FAST_CHAR_MASK is used when the input is in native byte ordering,
5154 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005155*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005156#if (SIZEOF_LONG == 8)
5157# define FAST_CHAR_MASK 0x8000800080008000L
5158# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5159#elif (SIZEOF_LONG == 4)
5160# define FAST_CHAR_MASK 0x80008000L
5161# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5162#else
5163# error C 'long' size should be either 4 or 8!
5164#endif
5165
Walter Dörwald69652032004-09-07 20:24:22 +00005166PyObject *
5167PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005168 Py_ssize_t size,
5169 const char *errors,
5170 int *byteorder,
5171 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005172{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005173 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005174 Py_ssize_t startinpos;
5175 Py_ssize_t endinpos;
5176 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005177 PyObject *unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005178 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005179 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005180 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005181 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005182 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005183 /* Offsets from q for retrieving byte pairs in the right order. */
5184#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5185 int ihi = 1, ilo = 0;
5186#else
5187 int ihi = 0, ilo = 1;
5188#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005189 PyObject *errorHandler = NULL;
5190 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005191
5192 /* Note: size will always be longer than the resulting Unicode
5193 character count */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005194 unicode = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005195 if (!unicode)
5196 return NULL;
5197 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005198 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005199
5200 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005201 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005202 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005203 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005204
5205 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005206 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005207
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005208 /* Check for BOM marks (U+FEFF) in the input and adjust current
5209 byte order setting accordingly. In native mode, the leading BOM
5210 mark is skipped, in all other modes, it is copied to the output
5211 stream as-is (giving a ZWNBSP character). */
5212 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005213 if (size >= 2) {
5214 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005215#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005216 if (bom == 0xFEFF) {
5217 q += 2;
5218 bo = -1;
5219 }
5220 else if (bom == 0xFFFE) {
5221 q += 2;
5222 bo = 1;
5223 }
Tim Petersced69f82003-09-16 20:30:58 +00005224#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005225 if (bom == 0xFEFF) {
5226 q += 2;
5227 bo = 1;
5228 }
5229 else if (bom == 0xFFFE) {
5230 q += 2;
5231 bo = -1;
5232 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005233#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005234 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005235 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005236
Tim Peters772747b2001-08-09 22:21:55 +00005237 if (bo == -1) {
5238 /* force LE */
5239 ihi = 1;
5240 ilo = 0;
5241 }
5242 else if (bo == 1) {
5243 /* force BE */
5244 ihi = 0;
5245 ilo = 1;
5246 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005247#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5248 native_ordering = ilo < ihi;
5249#else
5250 native_ordering = ilo > ihi;
5251#endif
Tim Peters772747b2001-08-09 22:21:55 +00005252
Antoine Pitrouab868312009-01-10 15:40:25 +00005253 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005254 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005256 /* First check for possible aligned read of a C 'long'. Unaligned
5257 reads are more expensive, better to defer to another iteration. */
5258 if (!((size_t) q & LONG_PTR_MASK)) {
5259 /* Fast path for runs of non-surrogate chars. */
5260 register const unsigned char *_q = q;
5261 Py_UNICODE *_p = p;
5262 if (native_ordering) {
5263 /* Native ordering is simple: as long as the input cannot
5264 possibly contain a surrogate char, do an unrolled copy
5265 of several 16-bit code points to the target object.
5266 The non-surrogate check is done on several input bytes
5267 at a time (as many as a C 'long' can contain). */
5268 while (_q < aligned_end) {
5269 unsigned long data = * (unsigned long *) _q;
5270 if (data & FAST_CHAR_MASK)
5271 break;
5272 _p[0] = ((unsigned short *) _q)[0];
5273 _p[1] = ((unsigned short *) _q)[1];
5274#if (SIZEOF_LONG == 8)
5275 _p[2] = ((unsigned short *) _q)[2];
5276 _p[3] = ((unsigned short *) _q)[3];
5277#endif
5278 _q += SIZEOF_LONG;
5279 _p += SIZEOF_LONG / 2;
5280 }
5281 }
5282 else {
5283 /* Byteswapped ordering is similar, but we must decompose
5284 the copy bytewise, and take care of zero'ing out the
5285 upper bytes if the target object is in 32-bit units
5286 (that is, in UCS-4 builds). */
5287 while (_q < aligned_end) {
5288 unsigned long data = * (unsigned long *) _q;
5289 if (data & SWAPPED_FAST_CHAR_MASK)
5290 break;
5291 /* Zero upper bytes in UCS-4 builds */
5292#if (Py_UNICODE_SIZE > 2)
5293 _p[0] = 0;
5294 _p[1] = 0;
5295#if (SIZEOF_LONG == 8)
5296 _p[2] = 0;
5297 _p[3] = 0;
5298#endif
5299#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005300 /* Issue #4916; UCS-4 builds on big endian machines must
5301 fill the two last bytes of each 4-byte unit. */
5302#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5303# define OFF 2
5304#else
5305# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005306#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005307 ((unsigned char *) _p)[OFF + 1] = _q[0];
5308 ((unsigned char *) _p)[OFF + 0] = _q[1];
5309 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5310 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5311#if (SIZEOF_LONG == 8)
5312 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5313 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5314 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5315 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5316#endif
5317#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005318 _q += SIZEOF_LONG;
5319 _p += SIZEOF_LONG / 2;
5320 }
5321 }
5322 p = _p;
5323 q = _q;
5324 if (q >= e)
5325 break;
5326 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005327 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005328
Benjamin Peterson14339b62009-01-31 16:36:08 +00005329 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005330
5331 if (ch < 0xD800 || ch > 0xDFFF) {
5332 *p++ = ch;
5333 continue;
5334 }
5335
5336 /* UTF-16 code pair: */
5337 if (q > e) {
5338 errmsg = "unexpected end of data";
5339 startinpos = (((const char *)q) - 2) - starts;
5340 endinpos = ((const char *)e) + 1 - starts;
5341 goto utf16Error;
5342 }
5343 if (0xD800 <= ch && ch <= 0xDBFF) {
5344 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5345 q += 2;
5346 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005347#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 *p++ = ch;
5349 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005350#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005352#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 continue;
5354 }
5355 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005356 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005357 startinpos = (((const char *)q)-4)-starts;
5358 endinpos = startinpos+2;
5359 goto utf16Error;
5360 }
5361
Benjamin Peterson14339b62009-01-31 16:36:08 +00005362 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 errmsg = "illegal encoding";
5364 startinpos = (((const char *)q)-2)-starts;
5365 endinpos = startinpos+2;
5366 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005367
Benjamin Peterson29060642009-01-31 22:14:21 +00005368 utf16Error:
5369 outpos = p - PyUnicode_AS_UNICODE(unicode);
5370 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005371 errors,
5372 &errorHandler,
5373 "utf16", errmsg,
5374 &starts,
5375 (const char **)&e,
5376 &startinpos,
5377 &endinpos,
5378 &exc,
5379 (const char **)&q,
5380 &unicode,
5381 &outpos,
5382 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005383 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005384 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005385 /* remaining byte at the end? (size should be even) */
5386 if (e == q) {
5387 if (!consumed) {
5388 errmsg = "truncated data";
5389 startinpos = ((const char *)q) - starts;
5390 endinpos = ((const char *)e) + 1 - starts;
5391 outpos = p - PyUnicode_AS_UNICODE(unicode);
5392 if (unicode_decode_call_errorhandler(
5393 errors,
5394 &errorHandler,
5395 "utf16", errmsg,
5396 &starts,
5397 (const char **)&e,
5398 &startinpos,
5399 &endinpos,
5400 &exc,
5401 (const char **)&q,
5402 &unicode,
5403 &outpos,
5404 &p))
5405 goto onError;
5406 /* The remaining input chars are ignored if the callback
5407 chooses to skip the input */
5408 }
5409 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005410
5411 if (byteorder)
5412 *byteorder = bo;
5413
Walter Dörwald69652032004-09-07 20:24:22 +00005414 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005415 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005416
Guido van Rossumd57fd912000-03-10 22:53:23 +00005417 /* Adjust length */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005418 if (PyUnicode_Resize(&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419 goto onError;
5420
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005421 Py_XDECREF(errorHandler);
5422 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005423#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005424 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005425 Py_DECREF(unicode);
5426 return NULL;
5427 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005428#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005429 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005430 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431
Benjamin Peterson29060642009-01-31 22:14:21 +00005432 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005433 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005434 Py_XDECREF(errorHandler);
5435 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005436 return NULL;
5437}
5438
Antoine Pitrouab868312009-01-10 15:40:25 +00005439#undef FAST_CHAR_MASK
5440#undef SWAPPED_FAST_CHAR_MASK
5441
Tim Peters772747b2001-08-09 22:21:55 +00005442PyObject *
5443PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005444 Py_ssize_t size,
5445 const char *errors,
5446 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005447{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005448 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005449 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005450 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005451#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005452 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005453#else
5454 const int pairs = 0;
5455#endif
Tim Peters772747b2001-08-09 22:21:55 +00005456 /* Offsets from p for storing byte pairs in the right order. */
5457#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5458 int ihi = 1, ilo = 0;
5459#else
5460 int ihi = 0, ilo = 1;
5461#endif
5462
Benjamin Peterson29060642009-01-31 22:14:21 +00005463#define STORECHAR(CH) \
5464 do { \
5465 p[ihi] = ((CH) >> 8) & 0xff; \
5466 p[ilo] = (CH) & 0xff; \
5467 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005468 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005469
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005470#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005471 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005472 if (s[i] >= 0x10000)
5473 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005474#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005475 /* 2 * (size + pairs + (byteorder == 0)) */
5476 if (size > PY_SSIZE_T_MAX ||
5477 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005478 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005479 nsize = size + pairs + (byteorder == 0);
5480 bytesize = nsize * 2;
5481 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005482 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005483 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005484 if (v == NULL)
5485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005486
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005487 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005488 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005490 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005491 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005492
5493 if (byteorder == -1) {
5494 /* force LE */
5495 ihi = 1;
5496 ilo = 0;
5497 }
5498 else if (byteorder == 1) {
5499 /* force BE */
5500 ihi = 0;
5501 ilo = 1;
5502 }
5503
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005504 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005505 Py_UNICODE ch = *s++;
5506 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005507#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005508 if (ch >= 0x10000) {
5509 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5510 ch = 0xD800 | ((ch-0x10000) >> 10);
5511 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005512#endif
Tim Peters772747b2001-08-09 22:21:55 +00005513 STORECHAR(ch);
5514 if (ch2)
5515 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005516 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005517
5518 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005519 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005520#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005521}
5522
Alexander Belopolsky40018472011-02-26 01:02:56 +00005523PyObject *
5524PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005525{
5526 if (!PyUnicode_Check(unicode)) {
5527 PyErr_BadArgument();
5528 return NULL;
5529 }
5530 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005531 PyUnicode_GET_SIZE(unicode),
5532 NULL,
5533 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005534}
5535
5536/* --- Unicode Escape Codec ----------------------------------------------- */
5537
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005538/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5539 if all the escapes in the string make it still a valid ASCII string.
5540 Returns -1 if any escapes were found which cause the string to
5541 pop out of ASCII range. Otherwise returns the length of the
5542 required buffer to hold the string.
5543 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005544static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005545length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5546{
5547 const unsigned char *p = (const unsigned char *)s;
5548 const unsigned char *end = p + size;
5549 Py_ssize_t length = 0;
5550
5551 if (size < 0)
5552 return -1;
5553
5554 for (; p < end; ++p) {
5555 if (*p > 127) {
5556 /* Non-ASCII */
5557 return -1;
5558 }
5559 else if (*p != '\\') {
5560 /* Normal character */
5561 ++length;
5562 }
5563 else {
5564 /* Backslash-escape, check next char */
5565 ++p;
5566 /* Escape sequence reaches till end of string or
5567 non-ASCII follow-up. */
5568 if (p >= end || *p > 127)
5569 return -1;
5570 switch (*p) {
5571 case '\n':
5572 /* backslash + \n result in zero characters */
5573 break;
5574 case '\\': case '\'': case '\"':
5575 case 'b': case 'f': case 't':
5576 case 'n': case 'r': case 'v': case 'a':
5577 ++length;
5578 break;
5579 case '0': case '1': case '2': case '3':
5580 case '4': case '5': case '6': case '7':
5581 case 'x': case 'u': case 'U': case 'N':
5582 /* these do not guarantee ASCII characters */
5583 return -1;
5584 default:
5585 /* count the backslash + the other character */
5586 length += 2;
5587 }
5588 }
5589 }
5590 return length;
5591}
5592
5593/* Similar to PyUnicode_WRITE but either write into wstr field
5594 or treat string as ASCII. */
5595#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5596 do { \
5597 if ((kind) != PyUnicode_WCHAR_KIND) \
5598 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5599 else \
5600 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5601 } while (0)
5602
5603#define WRITE_WSTR(buf, index, value) \
5604 assert(kind == PyUnicode_WCHAR_KIND), \
5605 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5606
5607
Fredrik Lundh06d12682001-01-24 07:59:11 +00005608static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005609
Alexander Belopolsky40018472011-02-26 01:02:56 +00005610PyObject *
5611PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005612 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005613 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005614{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005615 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005616 Py_ssize_t startinpos;
5617 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005618 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005619 PyObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005620 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005622 char* message;
5623 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624 PyObject *errorHandler = NULL;
5625 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005626 Py_ssize_t ascii_length;
5627 Py_ssize_t i;
5628 int kind;
5629 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005630
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005631 ascii_length = length_of_escaped_ascii_string(s, size);
5632
5633 /* After length_of_escaped_ascii_string() there are two alternatives,
5634 either the string is pure ASCII with named escapes like \n, etc.
5635 and we determined it's exact size (common case)
5636 or it contains \x, \u, ... escape sequences. then we create a
5637 legacy wchar string and resize it at the end of this function. */
5638 if (ascii_length >= 0) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01005639 v = PyUnicode_New(ascii_length, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005640 if (!v)
5641 goto onError;
5642 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5643 kind = PyUnicode_1BYTE_KIND;
5644 data = PyUnicode_DATA(v);
5645 }
5646 else {
5647 /* Escaped strings will always be longer than the resulting
5648 Unicode string, so we start with size here and then reduce the
5649 length after conversion to the true value.
5650 (but if the error callback returns a long replacement string
5651 we'll have to allocate more space) */
Victor Stinner7931d9a2011-11-04 00:22:48 +01005652 v = (PyObject*)_PyUnicode_New(size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005653 if (!v)
5654 goto onError;
5655 kind = PyUnicode_WCHAR_KIND;
5656 data = PyUnicode_AS_UNICODE(v);
5657 }
5658
Guido van Rossumd57fd912000-03-10 22:53:23 +00005659 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005660 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005661 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005662 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005663
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 while (s < end) {
5665 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005666 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005667 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005669 if (kind == PyUnicode_WCHAR_KIND) {
5670 assert(i < _PyUnicode_WSTR_LENGTH(v));
5671 }
5672 else {
5673 /* The only case in which i == ascii_length is a backslash
5674 followed by a newline. */
5675 assert(i <= ascii_length);
5676 }
5677
Guido van Rossumd57fd912000-03-10 22:53:23 +00005678 /* Non-escape characters are interpreted as Unicode ordinals */
5679 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005680 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005681 continue;
5682 }
5683
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005684 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005685 /* \ - Escapes */
5686 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005687 c = *s++;
5688 if (s > end)
5689 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005690
5691 if (kind == PyUnicode_WCHAR_KIND) {
5692 assert(i < _PyUnicode_WSTR_LENGTH(v));
5693 }
5694 else {
5695 /* The only case in which i == ascii_length is a backslash
5696 followed by a newline. */
5697 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5698 }
5699
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005700 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005701
Benjamin Peterson29060642009-01-31 22:14:21 +00005702 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005703 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005704 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5705 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5706 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5707 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5708 /* FF */
5709 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5710 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5711 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5712 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5713 /* VT */
5714 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5715 /* BEL, not classic C */
5716 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005717
Benjamin Peterson29060642009-01-31 22:14:21 +00005718 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005719 case '0': case '1': case '2': case '3':
5720 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005721 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005722 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005723 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005724 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005725 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005727 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728 break;
5729
Benjamin Peterson29060642009-01-31 22:14:21 +00005730 /* hex escapes */
5731 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005732 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005733 digits = 2;
5734 message = "truncated \\xXX escape";
5735 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005736
Benjamin Peterson29060642009-01-31 22:14:21 +00005737 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005738 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005739 digits = 4;
5740 message = "truncated \\uXXXX escape";
5741 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005742
Benjamin Peterson29060642009-01-31 22:14:21 +00005743 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005744 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005745 digits = 8;
5746 message = "truncated \\UXXXXXXXX escape";
5747 hexescape:
5748 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005749 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005750 if (s+digits>end) {
5751 endinpos = size;
5752 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005753 errors, &errorHandler,
5754 "unicodeescape", "end of string in escape sequence",
5755 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005756 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005757 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005758 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005759 goto nextByte;
5760 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005761 for (j = 0; j < digits; ++j) {
5762 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005763 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005764 endinpos = (s+j+1)-starts;
5765 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005766 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005767 errors, &errorHandler,
5768 "unicodeescape", message,
5769 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005770 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005771 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005772 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005773 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005774 }
5775 chr = (chr<<4) & ~0xF;
5776 if (c >= '0' && c <= '9')
5777 chr += c - '0';
5778 else if (c >= 'a' && c <= 'f')
5779 chr += 10 + c - 'a';
5780 else
5781 chr += 10 + c - 'A';
5782 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005783 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005784 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005785 /* _decoding_error will have already written into the
5786 target buffer. */
5787 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005788 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005789 /* when we get here, chr is a 32-bit unicode character */
5790 if (chr <= 0xffff)
5791 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005792 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005793 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005794 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005795 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005796#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005797 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005798#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005799 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005800 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5801 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005802#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005803 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005804 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005805 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005806 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005807 errors, &errorHandler,
5808 "unicodeescape", "illegal Unicode character",
5809 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005810 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005811 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005812 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005813 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005814 break;
5815
Benjamin Peterson29060642009-01-31 22:14:21 +00005816 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005817 case 'N':
5818 message = "malformed \\N character escape";
5819 if (ucnhash_CAPI == NULL) {
5820 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005821 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5822 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005823 if (ucnhash_CAPI == NULL)
5824 goto ucnhashError;
5825 }
5826 if (*s == '{') {
5827 const char *start = s+1;
5828 /* look for the closing brace */
5829 while (*s != '}' && s < end)
5830 s++;
5831 if (s > start && s < end && *s == '}') {
5832 /* found a name. look it up in the unicode database */
5833 message = "unknown Unicode character name";
5834 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005835 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005836 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005837 goto store;
5838 }
5839 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005840 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005841 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005842 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 errors, &errorHandler,
5844 "unicodeescape", message,
5845 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005847 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005848 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005849 break;
5850
5851 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005852 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005853 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005854 message = "\\ at end of string";
5855 s--;
5856 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005857 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005858 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005859 errors, &errorHandler,
5860 "unicodeescape", message,
5861 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005862 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005863 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005864 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005865 }
5866 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005867 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5868 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005869 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005870 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005871 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005872 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005873 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005874 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005875 /* Ensure the length prediction worked in case of ASCII strings */
5876 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5877
Victor Stinnerfe226c02011-10-03 03:52:20 +02005878 if (kind == PyUnicode_WCHAR_KIND)
5879 {
Victor Stinner7931d9a2011-11-04 00:22:48 +01005880 if (PyUnicode_Resize(&v, i) < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02005881 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005882 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005883 Py_XDECREF(errorHandler);
5884 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005885#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005886 if (_PyUnicode_READY_REPLACE(&v)) {
5887 Py_DECREF(v);
5888 return NULL;
5889 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005890#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005891 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005892 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005893
Benjamin Peterson29060642009-01-31 22:14:21 +00005894 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005895 PyErr_SetString(
5896 PyExc_UnicodeError,
5897 "\\N escapes not supported (can't load unicodedata module)"
5898 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005899 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005900 Py_XDECREF(errorHandler);
5901 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005902 return NULL;
5903
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005905 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005906 Py_XDECREF(errorHandler);
5907 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005908 return NULL;
5909}
5910
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005911#undef WRITE_ASCII_OR_WSTR
5912#undef WRITE_WSTR
5913
Guido van Rossumd57fd912000-03-10 22:53:23 +00005914/* Return a Unicode-Escape string version of the Unicode object.
5915
5916 If quotes is true, the string is enclosed in u"" or u'' quotes as
5917 appropriate.
5918
5919*/
5920
Alexander Belopolsky40018472011-02-26 01:02:56 +00005921PyObject *
5922PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005923 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005924{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005925 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005927
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005928#ifdef Py_UNICODE_WIDE
5929 const Py_ssize_t expandsize = 10;
5930#else
5931 const Py_ssize_t expandsize = 6;
5932#endif
5933
Thomas Wouters89f507f2006-12-13 04:49:30 +00005934 /* XXX(nnorwitz): rather than over-allocating, it would be
5935 better to choose a different scheme. Perhaps scan the
5936 first N-chars of the string and allocate based on that size.
5937 */
5938 /* Initial allocation is based on the longest-possible unichr
5939 escape.
5940
5941 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5942 unichr, so in this case it's the longest unichr escape. In
5943 narrow (UTF-16) builds this is five chars per source unichr
5944 since there are two unichrs in the surrogate pair, so in narrow
5945 (UTF-16) builds it's not the longest unichr escape.
5946
5947 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5948 so in the narrow (UTF-16) build case it's the longest unichr
5949 escape.
5950 */
5951
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005952 if (size == 0)
5953 return PyBytes_FromStringAndSize(NULL, 0);
5954
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005955 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005956 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005957
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005958 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005959 2
5960 + expandsize*size
5961 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962 if (repr == NULL)
5963 return NULL;
5964
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005965 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005966
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 while (size-- > 0) {
5968 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005969
Walter Dörwald79e913e2007-05-12 11:08:06 +00005970 /* Escape backslashes */
5971 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 *p++ = '\\';
5973 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005974 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005975 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005976
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005977#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005978 /* Map 21-bit characters to '\U00xxxxxx' */
5979 else if (ch >= 0x10000) {
5980 *p++ = '\\';
5981 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005982 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5983 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5984 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5985 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5986 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5987 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5988 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5989 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005990 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005991 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005992#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005993 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5994 else if (ch >= 0xD800 && ch < 0xDC00) {
5995 Py_UNICODE ch2;
5996 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005997
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 ch2 = *s++;
5999 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006000 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006001 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6002 *p++ = '\\';
6003 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006004 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
6005 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
6006 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
6007 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
6008 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
6009 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
6010 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
6011 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006012 continue;
6013 }
6014 /* Fall through: isolated surrogates are copied as-is */
6015 s--;
6016 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006017 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006018#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006019
Guido van Rossumd57fd912000-03-10 22:53:23 +00006020 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006021 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022 *p++ = '\\';
6023 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006024 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6025 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6026 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6027 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006028 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006029
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006030 /* Map special whitespace to '\t', \n', '\r' */
6031 else if (ch == '\t') {
6032 *p++ = '\\';
6033 *p++ = 't';
6034 }
6035 else if (ch == '\n') {
6036 *p++ = '\\';
6037 *p++ = 'n';
6038 }
6039 else if (ch == '\r') {
6040 *p++ = '\\';
6041 *p++ = 'r';
6042 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006043
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006044 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006045 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006046 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006047 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006048 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6049 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006050 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006051
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052 /* Copy everything else as-is */
6053 else
6054 *p++ = (char) ch;
6055 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006057 assert(p - PyBytes_AS_STRING(repr) > 0);
6058 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6059 return NULL;
6060 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061}
6062
Alexander Belopolsky40018472011-02-26 01:02:56 +00006063PyObject *
6064PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006065{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006066 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006067 if (!PyUnicode_Check(unicode)) {
6068 PyErr_BadArgument();
6069 return NULL;
6070 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006071 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6072 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006073 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006074}
6075
6076/* --- Raw Unicode Escape Codec ------------------------------------------- */
6077
Alexander Belopolsky40018472011-02-26 01:02:56 +00006078PyObject *
6079PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006080 Py_ssize_t size,
6081 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006082{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006083 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006084 Py_ssize_t startinpos;
6085 Py_ssize_t endinpos;
6086 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006087 PyObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006089 const char *end;
6090 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006091 PyObject *errorHandler = NULL;
6092 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006093
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094 /* Escaped strings will always be longer than the resulting
6095 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006096 length after conversion to the true value. (But decoding error
6097 handler might have to resize the string) */
Victor Stinner7931d9a2011-11-04 00:22:48 +01006098 v = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006099 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006100 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006101 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006102 return v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006103 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006104 end = s + size;
6105 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006106 unsigned char c;
6107 Py_UCS4 x;
6108 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006109 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006110
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 /* Non-escape characters are interpreted as Unicode ordinals */
6112 if (*s != '\\') {
6113 *p++ = (unsigned char)*s++;
6114 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006115 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 startinpos = s-starts;
6117
6118 /* \u-escapes are only interpreted iff the number of leading
6119 backslashes if odd */
6120 bs = s;
6121 for (;s < end;) {
6122 if (*s != '\\')
6123 break;
6124 *p++ = (unsigned char)*s++;
6125 }
6126 if (((s - bs) & 1) == 0 ||
6127 s >= end ||
6128 (*s != 'u' && *s != 'U')) {
6129 continue;
6130 }
6131 p--;
6132 count = *s=='u' ? 4 : 8;
6133 s++;
6134
6135 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6136 outpos = p-PyUnicode_AS_UNICODE(v);
6137 for (x = 0, i = 0; i < count; ++i, ++s) {
6138 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006139 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006140 endinpos = s-starts;
6141 if (unicode_decode_call_errorhandler(
6142 errors, &errorHandler,
6143 "rawunicodeescape", "truncated \\uXXXX",
6144 &starts, &end, &startinpos, &endinpos, &exc, &s,
6145 &v, &outpos, &p))
6146 goto onError;
6147 goto nextByte;
6148 }
6149 x = (x<<4) & ~0xF;
6150 if (c >= '0' && c <= '9')
6151 x += c - '0';
6152 else if (c >= 'a' && c <= 'f')
6153 x += 10 + c - 'a';
6154 else
6155 x += 10 + c - 'A';
6156 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006157 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006158 /* UCS-2 character */
6159 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006160 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006161 /* UCS-4 character. Either store directly, or as
6162 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006163#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006164 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006165#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 x -= 0x10000L;
6167 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6168 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006169#endif
6170 } else {
6171 endinpos = s-starts;
6172 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006173 if (unicode_decode_call_errorhandler(
6174 errors, &errorHandler,
6175 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006176 &starts, &end, &startinpos, &endinpos, &exc, &s,
6177 &v, &outpos, &p))
6178 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006179 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006180 nextByte:
6181 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006182 }
Victor Stinner7931d9a2011-11-04 00:22:48 +01006183 if (PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006184 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006185 Py_XDECREF(errorHandler);
6186 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006187#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006188 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006189 Py_DECREF(v);
6190 return NULL;
6191 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006192#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006193 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006194 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006195
Benjamin Peterson29060642009-01-31 22:14:21 +00006196 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006198 Py_XDECREF(errorHandler);
6199 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006200 return NULL;
6201}
6202
Alexander Belopolsky40018472011-02-26 01:02:56 +00006203PyObject *
6204PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006205 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006206{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006207 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006208 char *p;
6209 char *q;
6210
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006211#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006212 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006213#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006214 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006215#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006216
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006217 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006218 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006219
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006220 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006221 if (repr == NULL)
6222 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006223 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006224 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006225
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006226 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006227 while (size-- > 0) {
6228 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006229#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006230 /* Map 32-bit characters to '\Uxxxxxxxx' */
6231 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006232 *p++ = '\\';
6233 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006234 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6235 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6236 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6237 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6238 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6239 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6240 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6241 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006242 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006243 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006244#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006245 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6246 if (ch >= 0xD800 && ch < 0xDC00) {
6247 Py_UNICODE ch2;
6248 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006249
Benjamin Peterson29060642009-01-31 22:14:21 +00006250 ch2 = *s++;
6251 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006252 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006253 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6254 *p++ = '\\';
6255 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006256 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6257 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6258 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6259 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6260 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6261 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6262 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6263 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006264 continue;
6265 }
6266 /* Fall through: isolated surrogates are copied as-is */
6267 s--;
6268 size++;
6269 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006270#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006271 /* Map 16-bit characters to '\uxxxx' */
6272 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006273 *p++ = '\\';
6274 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006275 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6276 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6277 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6278 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006279 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006280 /* Copy everything else as-is */
6281 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006282 *p++ = (char) ch;
6283 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006284 size = p - q;
6285
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006286 assert(size > 0);
6287 if (_PyBytes_Resize(&repr, size) < 0)
6288 return NULL;
6289 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006290}
6291
Alexander Belopolsky40018472011-02-26 01:02:56 +00006292PyObject *
6293PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006295 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006296 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006297 PyErr_BadArgument();
6298 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006300 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6301 PyUnicode_GET_SIZE(unicode));
6302
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006303 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304}
6305
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006306/* --- Unicode Internal Codec ------------------------------------------- */
6307
Alexander Belopolsky40018472011-02-26 01:02:56 +00006308PyObject *
6309_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006310 Py_ssize_t size,
6311 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006312{
6313 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006314 Py_ssize_t startinpos;
6315 Py_ssize_t endinpos;
6316 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006317 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006318 Py_UNICODE *p;
6319 const char *end;
6320 const char *reason;
6321 PyObject *errorHandler = NULL;
6322 PyObject *exc = NULL;
6323
Neal Norwitzd43069c2006-01-08 01:12:10 +00006324#ifdef Py_UNICODE_WIDE
6325 Py_UNICODE unimax = PyUnicode_GetMax();
6326#endif
6327
Thomas Wouters89f507f2006-12-13 04:49:30 +00006328 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01006329 v = (PyObject*)_PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006330 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006331 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006332 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6333 as string was created with the old API. */
6334 if (PyUnicode_GET_SIZE(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006335 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006336 p = PyUnicode_AS_UNICODE(v);
6337 end = s + size;
6338
6339 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006340 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006341 /* We have to sanity check the raw data, otherwise doom looms for
6342 some malformed UCS-4 data. */
6343 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006344#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006345 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006346#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006347 end-s < Py_UNICODE_SIZE
6348 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006349 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006350 startinpos = s - starts;
6351 if (end-s < Py_UNICODE_SIZE) {
6352 endinpos = end-starts;
6353 reason = "truncated input";
6354 }
6355 else {
6356 endinpos = s - starts + Py_UNICODE_SIZE;
6357 reason = "illegal code point (> 0x10FFFF)";
6358 }
6359 outpos = p - PyUnicode_AS_UNICODE(v);
6360 if (unicode_decode_call_errorhandler(
6361 errors, &errorHandler,
6362 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006363 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006364 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006365 goto onError;
6366 }
6367 }
6368 else {
6369 p++;
6370 s += Py_UNICODE_SIZE;
6371 }
6372 }
6373
Victor Stinner7931d9a2011-11-04 00:22:48 +01006374 if (PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006375 goto onError;
6376 Py_XDECREF(errorHandler);
6377 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006378#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006379 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006380 Py_DECREF(v);
6381 return NULL;
6382 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006383#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006384 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006385 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006386
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006388 Py_XDECREF(v);
6389 Py_XDECREF(errorHandler);
6390 Py_XDECREF(exc);
6391 return NULL;
6392}
6393
Guido van Rossumd57fd912000-03-10 22:53:23 +00006394/* --- Latin-1 Codec ------------------------------------------------------ */
6395
Alexander Belopolsky40018472011-02-26 01:02:56 +00006396PyObject *
6397PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006398 Py_ssize_t size,
6399 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006400{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006401 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006402 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006403}
6404
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006406static void
6407make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006408 const char *encoding,
6409 const Py_UNICODE *unicode, Py_ssize_t size,
6410 Py_ssize_t startpos, Py_ssize_t endpos,
6411 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006412{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006413 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006414 *exceptionObject = PyUnicodeEncodeError_Create(
6415 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006416 }
6417 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006418 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6419 goto onError;
6420 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6421 goto onError;
6422 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6423 goto onError;
6424 return;
6425 onError:
6426 Py_DECREF(*exceptionObject);
6427 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006428 }
6429}
6430
Martin v. Löwis9e816682011-11-02 12:45:42 +01006431/* This is ultimately going t replace above function. */
6432static void
6433make_encode_exception_obj(PyObject **exceptionObject,
6434 const char *encoding,
6435 PyObject *unicode,
6436 Py_ssize_t startpos, Py_ssize_t endpos,
6437 const char *reason)
6438{
6439 if (*exceptionObject == NULL) {
6440 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006441 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006442 encoding, unicode, startpos, endpos, reason);
6443 }
6444 else {
6445 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6446 goto onError;
6447 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6448 goto onError;
6449 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6450 goto onError;
6451 return;
6452 onError:
6453 Py_DECREF(*exceptionObject);
6454 *exceptionObject = NULL;
6455 }
6456}
6457
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006458/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006459static void
6460raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006461 const char *encoding,
6462 const Py_UNICODE *unicode, Py_ssize_t size,
6463 Py_ssize_t startpos, Py_ssize_t endpos,
6464 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006465{
6466 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006467 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006468 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006469 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006470}
Martin v. Löwis9e816682011-11-02 12:45:42 +01006471/* This is ultimately going to replace above function. */
6472static void
6473raise_encode_exception_obj(PyObject **exceptionObject,
6474 const char *encoding,
6475 PyObject *unicode,
6476 Py_ssize_t startpos, Py_ssize_t endpos,
6477 const char *reason)
6478{
6479 make_encode_exception_obj(exceptionObject,
6480 encoding, unicode, startpos, endpos, reason);
6481 if (*exceptionObject != NULL)
6482 PyCodec_StrictErrors(*exceptionObject);
6483}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006484
6485/* error handling callback helper:
6486 build arguments, call the callback and check the arguments,
6487 put the result into newpos and return the replacement string, which
6488 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006489static PyObject *
6490unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006491 PyObject **errorHandler,
6492 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006493 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006494 Py_ssize_t startpos, Py_ssize_t endpos,
6495 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006496{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006497 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006498 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006499 PyObject *restuple;
6500 PyObject *resunicode;
6501
6502 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006504 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006506 }
6507
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 if (PyUnicode_READY(unicode) < 0)
6509 return NULL;
6510 len = PyUnicode_GET_LENGTH(unicode);
6511
6512 make_encode_exception_obj(exceptionObject,
6513 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006514 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006516
6517 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006518 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006519 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006521 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006522 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 Py_DECREF(restuple);
6524 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006525 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006526 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006527 &resunicode, newpos)) {
6528 Py_DECREF(restuple);
6529 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006530 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006531 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6532 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6533 Py_DECREF(restuple);
6534 return NULL;
6535 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006536 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006537 *newpos = len + *newpos;
6538 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006539 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6540 Py_DECREF(restuple);
6541 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006542 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006543 Py_INCREF(resunicode);
6544 Py_DECREF(restuple);
6545 return resunicode;
6546}
6547
Alexander Belopolsky40018472011-02-26 01:02:56 +00006548static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006550 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006551 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006552{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 /* input state */
6554 Py_ssize_t pos=0, size;
6555 int kind;
6556 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006557 /* output object */
6558 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006559 /* pointer into the output */
6560 char *str;
6561 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006562 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006563 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6564 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006565 PyObject *errorHandler = NULL;
6566 PyObject *exc = NULL;
6567 /* the following variable is used for caching string comparisons
6568 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6569 int known_errorHandler = -1;
6570
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006571 if (PyUnicode_READY(unicode) < 0)
6572 return NULL;
6573 size = PyUnicode_GET_LENGTH(unicode);
6574 kind = PyUnicode_KIND(unicode);
6575 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006576 /* allocate enough for a simple encoding without
6577 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006578 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006579 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006580 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006582 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006583 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006584 ressize = size;
6585
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006586 while (pos < size) {
6587 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006588
Benjamin Peterson29060642009-01-31 22:14:21 +00006589 /* can we encode this? */
6590 if (c<limit) {
6591 /* no overflow check, because we know that the space is enough */
6592 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006593 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006594 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006595 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006596 Py_ssize_t requiredsize;
6597 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006598 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006599 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006600 Py_ssize_t collstart = pos;
6601 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006603 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006604 ++collend;
6605 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6606 if (known_errorHandler==-1) {
6607 if ((errors==NULL) || (!strcmp(errors, "strict")))
6608 known_errorHandler = 1;
6609 else if (!strcmp(errors, "replace"))
6610 known_errorHandler = 2;
6611 else if (!strcmp(errors, "ignore"))
6612 known_errorHandler = 3;
6613 else if (!strcmp(errors, "xmlcharrefreplace"))
6614 known_errorHandler = 4;
6615 else
6616 known_errorHandler = 0;
6617 }
6618 switch (known_errorHandler) {
6619 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006620 raise_encode_exception_obj(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006621 goto onError;
6622 case 2: /* replace */
6623 while (collstart++<collend)
6624 *str++ = '?'; /* fall through */
6625 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006626 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006627 break;
6628 case 4: /* xmlcharrefreplace */
6629 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006630 /* determine replacement size */
6631 for (i = collstart, repsize = 0; i < collend; ++i) {
6632 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6633 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006634 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006635 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006636 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006637 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006638 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006639 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006640 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006641#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006642 else
6643 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006644#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006645 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006646 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006647 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006648 repsize += 2+6+1;
6649 else
6650 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006651#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006652 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006653 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 if (requiredsize > ressize) {
6655 if (requiredsize<2*ressize)
6656 requiredsize = 2*ressize;
6657 if (_PyBytes_Resize(&res, requiredsize))
6658 goto onError;
6659 str = PyBytes_AS_STRING(res) + respos;
6660 ressize = requiredsize;
6661 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006662 /* generate replacement */
6663 for (i = collstart; i < collend; ++i) {
6664 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006665 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006666 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006667 break;
6668 default:
6669 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006670 encoding, reason, unicode, &exc,
6671 collstart, collend, &newpos);
6672 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6673 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006674 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006675 if (PyBytes_Check(repunicode)) {
6676 /* Directly copy bytes result to output. */
6677 repsize = PyBytes_Size(repunicode);
6678 if (repsize > 1) {
6679 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006680 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006681 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6682 Py_DECREF(repunicode);
6683 goto onError;
6684 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006685 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006686 ressize += repsize-1;
6687 }
6688 memcpy(str, PyBytes_AsString(repunicode), repsize);
6689 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006690 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006691 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006692 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006693 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006694 /* need more space? (at least enough for what we
6695 have+the replacement+the rest of the string, so
6696 we won't have to check space for encodable characters) */
6697 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006698 repsize = PyUnicode_GET_LENGTH(repunicode);
6699 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006700 if (requiredsize > ressize) {
6701 if (requiredsize<2*ressize)
6702 requiredsize = 2*ressize;
6703 if (_PyBytes_Resize(&res, requiredsize)) {
6704 Py_DECREF(repunicode);
6705 goto onError;
6706 }
6707 str = PyBytes_AS_STRING(res) + respos;
6708 ressize = requiredsize;
6709 }
6710 /* check if there is anything unencodable in the replacement
6711 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006712 for (i = 0; repsize-->0; ++i, ++str) {
6713 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006714 if (c >= limit) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006715 raise_encode_exception_obj(&exc, encoding, unicode,
6716 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006717 Py_DECREF(repunicode);
6718 goto onError;
6719 }
6720 *str = (char)c;
6721 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006722 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006723 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006724 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006725 }
6726 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006727 /* Resize if we allocated to much */
6728 size = str - PyBytes_AS_STRING(res);
6729 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006730 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006731 if (_PyBytes_Resize(&res, size) < 0)
6732 goto onError;
6733 }
6734
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 Py_XDECREF(errorHandler);
6736 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006737 return res;
6738
6739 onError:
6740 Py_XDECREF(res);
6741 Py_XDECREF(errorHandler);
6742 Py_XDECREF(exc);
6743 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006744}
6745
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006746/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006747PyObject *
6748PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006749 Py_ssize_t size,
6750 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006751{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752 PyObject *result;
6753 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6754 if (unicode == NULL)
6755 return NULL;
6756 result = unicode_encode_ucs1(unicode, errors, 256);
6757 Py_DECREF(unicode);
6758 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759}
6760
Alexander Belopolsky40018472011-02-26 01:02:56 +00006761PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006762_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006763{
6764 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006765 PyErr_BadArgument();
6766 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006767 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006768 if (PyUnicode_READY(unicode) == -1)
6769 return NULL;
6770 /* Fast path: if it is a one-byte string, construct
6771 bytes object directly. */
6772 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6773 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6774 PyUnicode_GET_LENGTH(unicode));
6775 /* Non-Latin-1 characters present. Defer to above function to
6776 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006777 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006778}
6779
6780PyObject*
6781PyUnicode_AsLatin1String(PyObject *unicode)
6782{
6783 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006784}
6785
6786/* --- 7-bit ASCII Codec -------------------------------------------------- */
6787
Alexander Belopolsky40018472011-02-26 01:02:56 +00006788PyObject *
6789PyUnicode_DecodeASCII(const char *s,
6790 Py_ssize_t size,
6791 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006792{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006793 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006794 PyObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006795 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006796 Py_ssize_t startinpos;
6797 Py_ssize_t endinpos;
6798 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006799 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006800 int has_error;
6801 const unsigned char *p = (const unsigned char *)s;
6802 const unsigned char *end = p + size;
6803 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006804 PyObject *errorHandler = NULL;
6805 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006806
Guido van Rossumd57fd912000-03-10 22:53:23 +00006807 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006808 if (size == 1 && (unsigned char)s[0] < 128)
6809 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006810
Victor Stinner702c7342011-10-05 13:50:52 +02006811 has_error = 0;
6812 while (p < end && !has_error) {
6813 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6814 an explanation. */
6815 if (!((size_t) p & LONG_PTR_MASK)) {
6816 /* Help register allocation */
6817 register const unsigned char *_p = p;
6818 while (_p < aligned_end) {
6819 unsigned long value = *(unsigned long *) _p;
6820 if (value & ASCII_CHAR_MASK) {
6821 has_error = 1;
6822 break;
6823 }
6824 _p += SIZEOF_LONG;
6825 }
6826 if (_p == end)
6827 break;
6828 if (has_error)
6829 break;
6830 p = _p;
6831 }
6832 if (*p & 0x80) {
6833 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006834 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006835 }
6836 else {
6837 ++p;
6838 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006839 }
Victor Stinner702c7342011-10-05 13:50:52 +02006840 if (!has_error)
6841 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006842
Victor Stinner7931d9a2011-11-04 00:22:48 +01006843 v = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006844 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006845 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006846 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006847 return v;
Victor Stinner702c7342011-10-05 13:50:52 +02006848 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006849 e = s + size;
6850 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006851 register unsigned char c = (unsigned char)*s;
6852 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006853 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 ++s;
6855 }
6856 else {
6857 startinpos = s-starts;
6858 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006859 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006860 if (unicode_decode_call_errorhandler(
6861 errors, &errorHandler,
6862 "ascii", "ordinal not in range(128)",
6863 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006864 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006865 goto onError;
6866 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006867 }
Victor Stinner702c7342011-10-05 13:50:52 +02006868 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinner7931d9a2011-11-04 00:22:48 +01006869 if (PyUnicode_Resize(&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006870 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006871 Py_XDECREF(errorHandler);
6872 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006873#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006874 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006875 Py_DECREF(v);
6876 return NULL;
6877 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006878#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006879 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006880 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006881
Benjamin Peterson29060642009-01-31 22:14:21 +00006882 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006883 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006884 Py_XDECREF(errorHandler);
6885 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006886 return NULL;
6887}
6888
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006889/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006890PyObject *
6891PyUnicode_EncodeASCII(const Py_UNICODE *p,
6892 Py_ssize_t size,
6893 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006894{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006895 PyObject *result;
6896 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6897 if (unicode == NULL)
6898 return NULL;
6899 result = unicode_encode_ucs1(unicode, errors, 128);
6900 Py_DECREF(unicode);
6901 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006902}
6903
Alexander Belopolsky40018472011-02-26 01:02:56 +00006904PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006905_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006906{
6907 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006908 PyErr_BadArgument();
6909 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006911 if (PyUnicode_READY(unicode) == -1)
6912 return NULL;
6913 /* Fast path: if it is an ASCII-only string, construct bytes object
6914 directly. Else defer to above function to raise the exception. */
6915 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6916 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6917 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006918 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006919}
6920
6921PyObject *
6922PyUnicode_AsASCIIString(PyObject *unicode)
6923{
6924 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006925}
6926
Victor Stinner99b95382011-07-04 14:23:54 +02006927#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006928
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006929/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006930
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006931#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006932#define NEED_RETRY
6933#endif
6934
Victor Stinner3a50e702011-10-18 21:21:00 +02006935#ifndef WC_ERR_INVALID_CHARS
6936# define WC_ERR_INVALID_CHARS 0x0080
6937#endif
6938
6939static char*
6940code_page_name(UINT code_page, PyObject **obj)
6941{
6942 *obj = NULL;
6943 if (code_page == CP_ACP)
6944 return "mbcs";
6945 if (code_page == CP_UTF7)
6946 return "CP_UTF7";
6947 if (code_page == CP_UTF8)
6948 return "CP_UTF8";
6949
6950 *obj = PyBytes_FromFormat("cp%u", code_page);
6951 if (*obj == NULL)
6952 return NULL;
6953 return PyBytes_AS_STRING(*obj);
6954}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006955
Alexander Belopolsky40018472011-02-26 01:02:56 +00006956static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006957is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006958{
6959 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006960 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006961
Victor Stinner3a50e702011-10-18 21:21:00 +02006962 if (!IsDBCSLeadByteEx(code_page, *curr))
6963 return 0;
6964
6965 prev = CharPrevExA(code_page, s, curr, 0);
6966 if (prev == curr)
6967 return 1;
6968 /* FIXME: This code is limited to "true" double-byte encodings,
6969 as it assumes an incomplete character consists of a single
6970 byte. */
6971 if (curr - prev == 2)
6972 return 1;
6973 if (!IsDBCSLeadByteEx(code_page, *prev))
6974 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006975 return 0;
6976}
6977
Victor Stinner3a50e702011-10-18 21:21:00 +02006978static DWORD
6979decode_code_page_flags(UINT code_page)
6980{
6981 if (code_page == CP_UTF7) {
6982 /* The CP_UTF7 decoder only supports flags=0 */
6983 return 0;
6984 }
6985 else
6986 return MB_ERR_INVALID_CHARS;
6987}
6988
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006989/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006990 * Decode a byte string from a Windows code page into unicode object in strict
6991 * mode.
6992 *
6993 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6994 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006995 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006996static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006997decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006998 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006999 const char *in,
7000 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007001{
Victor Stinner3a50e702011-10-18 21:21:00 +02007002 const DWORD flags = decode_code_page_flags(code_page);
7003 Py_UNICODE *out;
7004 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007005
7006 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007007 assert(insize > 0);
7008 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
7009 if (outsize <= 0)
7010 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007011
7012 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007013 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01007014 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00007015 if (*v == NULL)
7016 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007018 }
7019 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007020 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007021 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01007022 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007023 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007024 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007025 }
7026
7027 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007028 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
7029 if (outsize <= 0)
7030 goto error;
7031 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007032
Victor Stinner3a50e702011-10-18 21:21:00 +02007033error:
7034 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7035 return -2;
7036 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007037 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007038}
7039
Victor Stinner3a50e702011-10-18 21:21:00 +02007040/*
7041 * Decode a byte string from a code page into unicode object with an error
7042 * handler.
7043 *
7044 * Returns consumed size if succeed, or raise a WindowsError or
7045 * UnicodeDecodeError exception and returns -1 on error.
7046 */
7047static int
7048decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007049 PyObject **v,
7050 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02007051 const char *errors)
7052{
7053 const char *startin = in;
7054 const char *endin = in + size;
7055 const DWORD flags = decode_code_page_flags(code_page);
7056 /* Ideally, we should get reason from FormatMessage. This is the Windows
7057 2000 English version of the message. */
7058 const char *reason = "No mapping for the Unicode character exists "
7059 "in the target code page.";
7060 /* each step cannot decode more than 1 character, but a character can be
7061 represented as a surrogate pair */
7062 wchar_t buffer[2], *startout, *out;
7063 int insize, outsize;
7064 PyObject *errorHandler = NULL;
7065 PyObject *exc = NULL;
7066 PyObject *encoding_obj = NULL;
7067 char *encoding;
7068 DWORD err;
7069 int ret = -1;
7070
7071 assert(size > 0);
7072
7073 encoding = code_page_name(code_page, &encoding_obj);
7074 if (encoding == NULL)
7075 return -1;
7076
7077 if (errors == NULL || strcmp(errors, "strict") == 0) {
7078 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7079 UnicodeDecodeError. */
7080 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7081 if (exc != NULL) {
7082 PyCodec_StrictErrors(exc);
7083 Py_CLEAR(exc);
7084 }
7085 goto error;
7086 }
7087
7088 if (*v == NULL) {
7089 /* Create unicode object */
7090 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7091 PyErr_NoMemory();
7092 goto error;
7093 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007094 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02007095 if (*v == NULL)
7096 goto error;
7097 startout = PyUnicode_AS_UNICODE(*v);
7098 }
7099 else {
7100 /* Extend unicode object */
7101 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7102 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7103 PyErr_NoMemory();
7104 goto error;
7105 }
Victor Stinner76a31a62011-11-04 00:05:13 +01007106 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007107 goto error;
7108 startout = PyUnicode_AS_UNICODE(*v) + n;
7109 }
7110
7111 /* Decode the byte string character per character */
7112 out = startout;
7113 while (in < endin)
7114 {
7115 /* Decode a character */
7116 insize = 1;
7117 do
7118 {
7119 outsize = MultiByteToWideChar(code_page, flags,
7120 in, insize,
7121 buffer, Py_ARRAY_LENGTH(buffer));
7122 if (outsize > 0)
7123 break;
7124 err = GetLastError();
7125 if (err != ERROR_NO_UNICODE_TRANSLATION
7126 && err != ERROR_INSUFFICIENT_BUFFER)
7127 {
7128 PyErr_SetFromWindowsErr(0);
7129 goto error;
7130 }
7131 insize++;
7132 }
7133 /* 4=maximum length of a UTF-8 sequence */
7134 while (insize <= 4 && (in + insize) <= endin);
7135
7136 if (outsize <= 0) {
7137 Py_ssize_t startinpos, endinpos, outpos;
7138
7139 startinpos = in - startin;
7140 endinpos = startinpos + 1;
7141 outpos = out - PyUnicode_AS_UNICODE(*v);
7142 if (unicode_decode_call_errorhandler(
7143 errors, &errorHandler,
7144 encoding, reason,
7145 &startin, &endin, &startinpos, &endinpos, &exc, &in,
7146 v, &outpos, &out))
7147 {
7148 goto error;
7149 }
7150 }
7151 else {
7152 in += insize;
7153 memcpy(out, buffer, outsize * sizeof(wchar_t));
7154 out += outsize;
7155 }
7156 }
7157
7158 /* write a NUL character at the end */
7159 *out = 0;
7160
7161 /* Extend unicode object */
7162 outsize = out - startout;
7163 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007164 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007165 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007166 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007167
7168error:
7169 Py_XDECREF(encoding_obj);
7170 Py_XDECREF(errorHandler);
7171 Py_XDECREF(exc);
7172 return ret;
7173}
7174
Victor Stinner3a50e702011-10-18 21:21:00 +02007175static PyObject *
7176decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007177 const char *s, Py_ssize_t size,
7178 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007179{
Victor Stinner76a31a62011-11-04 00:05:13 +01007180 PyObject *v = NULL;
7181 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007182
Victor Stinner3a50e702011-10-18 21:21:00 +02007183 if (code_page < 0) {
7184 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7185 return NULL;
7186 }
7187
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007188 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007189 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190
Victor Stinner76a31a62011-11-04 00:05:13 +01007191 do
7192 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007193#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007194 if (size > INT_MAX) {
7195 chunk_size = INT_MAX;
7196 final = 0;
7197 done = 0;
7198 }
7199 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007200#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007201 {
7202 chunk_size = (int)size;
7203 final = (consumed == NULL);
7204 done = 1;
7205 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007206
Victor Stinner76a31a62011-11-04 00:05:13 +01007207 /* Skip trailing lead-byte unless 'final' is set */
7208 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7209 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007210
Victor Stinner76a31a62011-11-04 00:05:13 +01007211 if (chunk_size == 0 && done) {
7212 if (v != NULL)
7213 break;
7214 Py_INCREF(unicode_empty);
7215 return unicode_empty;
7216 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007217
Victor Stinner76a31a62011-11-04 00:05:13 +01007218
7219 converted = decode_code_page_strict(code_page, &v,
7220 s, chunk_size);
7221 if (converted == -2)
7222 converted = decode_code_page_errors(code_page, &v,
7223 s, chunk_size,
7224 errors);
7225 assert(converted != 0);
7226
7227 if (converted < 0) {
7228 Py_XDECREF(v);
7229 return NULL;
7230 }
7231
7232 if (consumed)
7233 *consumed += converted;
7234
7235 s += converted;
7236 size -= converted;
7237 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007238
Victor Stinner17efeed2011-10-04 20:05:46 +02007239#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007240 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007241 Py_DECREF(v);
7242 return NULL;
7243 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007244#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007245 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007246 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007247}
7248
Alexander Belopolsky40018472011-02-26 01:02:56 +00007249PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007250PyUnicode_DecodeCodePageStateful(int code_page,
7251 const char *s,
7252 Py_ssize_t size,
7253 const char *errors,
7254 Py_ssize_t *consumed)
7255{
7256 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7257}
7258
7259PyObject *
7260PyUnicode_DecodeMBCSStateful(const char *s,
7261 Py_ssize_t size,
7262 const char *errors,
7263 Py_ssize_t *consumed)
7264{
7265 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7266}
7267
7268PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007269PyUnicode_DecodeMBCS(const char *s,
7270 Py_ssize_t size,
7271 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007272{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007273 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7274}
7275
Victor Stinner3a50e702011-10-18 21:21:00 +02007276static DWORD
7277encode_code_page_flags(UINT code_page, const char *errors)
7278{
7279 if (code_page == CP_UTF8) {
7280 if (winver.dwMajorVersion >= 6)
7281 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7282 and later */
7283 return WC_ERR_INVALID_CHARS;
7284 else
7285 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7286 return 0;
7287 }
7288 else if (code_page == CP_UTF7) {
7289 /* CP_UTF7 only supports flags=0 */
7290 return 0;
7291 }
7292 else {
7293 if (errors != NULL && strcmp(errors, "replace") == 0)
7294 return 0;
7295 else
7296 return WC_NO_BEST_FIT_CHARS;
7297 }
7298}
7299
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007300/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 * Encode a Unicode string to a Windows code page into a byte string in strict
7302 * mode.
7303 *
7304 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7305 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007306 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007307static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007308encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007309 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007310 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007311{
Victor Stinner554f3f02010-06-16 23:33:54 +00007312 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007313 BOOL *pusedDefaultChar = &usedDefaultChar;
7314 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007315 PyObject *exc = NULL;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007316 Py_UNICODE *p;
7317 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007318 const DWORD flags = encode_code_page_flags(code_page, NULL);
7319 char *out;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007320 /* Create a substring so that we can get the UTF-16 representation
7321 of just the slice under consideration. */
7322 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007323
Martin v. Löwis3d325192011-11-04 18:23:06 +01007324 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007325
Victor Stinner3a50e702011-10-18 21:21:00 +02007326 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007327 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007328 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007329 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007330
Martin v. Löwis3d325192011-11-04 18:23:06 +01007331 substring = PyUnicode_Substring(unicode, offset, offset+len);
7332 if (substring == NULL)
7333 return -1;
7334 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7335 if (p == NULL) {
7336 Py_DECREF(substring);
7337 return -1;
7338 }
7339
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007340 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007341 outsize = WideCharToMultiByte(code_page, flags,
7342 p, size,
7343 NULL, 0,
7344 NULL, pusedDefaultChar);
7345 if (outsize <= 0)
7346 goto error;
7347 /* If we used a default char, then we failed! */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007348 if (pusedDefaultChar && *pusedDefaultChar) {
7349 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007350 return -2;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007352
Victor Stinner3a50e702011-10-18 21:21:00 +02007353 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007354 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007355 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007356 if (*outbytes == NULL) {
7357 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007358 return -1;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007360 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007361 }
7362 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007363 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007364 const Py_ssize_t n = PyBytes_Size(*outbytes);
7365 if (outsize > PY_SSIZE_T_MAX - n) {
7366 PyErr_NoMemory();
Martin v. Löwis3d325192011-11-04 18:23:06 +01007367 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007368 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007369 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007370 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7371 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007372 return -1;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007373 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007374 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007375 }
7376
7377 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 outsize = WideCharToMultiByte(code_page, flags,
7379 p, size,
7380 out, outsize,
7381 NULL, pusedDefaultChar);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007382 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007383 if (outsize <= 0)
7384 goto error;
7385 if (pusedDefaultChar && *pusedDefaultChar)
7386 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007387 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007388
Victor Stinner3a50e702011-10-18 21:21:00 +02007389error:
Martin v. Löwis3d325192011-11-04 18:23:06 +01007390 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007391 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7392 return -2;
7393 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007394 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007395}
7396
Victor Stinner3a50e702011-10-18 21:21:00 +02007397/*
7398 * Encode a Unicode string to a Windows code page into a byte string using a
7399 * error handler.
7400 *
7401 * Returns consumed characters if succeed, or raise a WindowsError and returns
7402 * -1 on other error.
7403 */
7404static int
7405encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007406 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007407 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007408{
Victor Stinner3a50e702011-10-18 21:21:00 +02007409 const DWORD flags = encode_code_page_flags(code_page, errors);
Martin v. Löwis3d325192011-11-04 18:23:06 +01007410 Py_ssize_t pos = unicode_offset;
7411 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007412 /* Ideally, we should get reason from FormatMessage. This is the Windows
7413 2000 English version of the message. */
7414 const char *reason = "invalid character";
7415 /* 4=maximum length of a UTF-8 sequence */
7416 char buffer[4];
7417 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7418 Py_ssize_t outsize;
7419 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 PyObject *errorHandler = NULL;
7421 PyObject *exc = NULL;
7422 PyObject *encoding_obj = NULL;
7423 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007424 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 PyObject *rep;
7426 int ret = -1;
7427
7428 assert(insize > 0);
7429
7430 encoding = code_page_name(code_page, &encoding_obj);
7431 if (encoding == NULL)
7432 return -1;
7433
7434 if (errors == NULL || strcmp(errors, "strict") == 0) {
7435 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7436 then we raise a UnicodeEncodeError. */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007437 make_encode_exception_obj(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007438 if (exc != NULL) {
7439 PyCodec_StrictErrors(exc);
7440 Py_DECREF(exc);
7441 }
7442 Py_XDECREF(encoding_obj);
7443 return -1;
7444 }
7445
7446 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7447 pusedDefaultChar = &usedDefaultChar;
7448 else
7449 pusedDefaultChar = NULL;
7450
7451 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7452 PyErr_NoMemory();
7453 goto error;
7454 }
7455 outsize = insize * Py_ARRAY_LENGTH(buffer);
7456
7457 if (*outbytes == NULL) {
7458 /* Create string object */
7459 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7460 if (*outbytes == NULL)
7461 goto error;
7462 out = PyBytes_AS_STRING(*outbytes);
7463 }
7464 else {
7465 /* Extend string object */
7466 Py_ssize_t n = PyBytes_Size(*outbytes);
7467 if (n > PY_SSIZE_T_MAX - outsize) {
7468 PyErr_NoMemory();
7469 goto error;
7470 }
7471 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7472 goto error;
7473 out = PyBytes_AS_STRING(*outbytes) + n;
7474 }
7475
7476 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007477 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007478 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007479 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7480 wchar_t chars[2];
7481 int charsize;
7482 if (ch < 0x10000) {
7483 chars[0] = (wchar_t)ch;
7484 charsize = 1;
7485 }
7486 else {
7487 ch -= 0x10000;
7488 chars[0] = 0xd800 + (ch >> 10);
7489 chars[1] = 0xdc00 + (ch & 0x3ff);
7490 charsize = 2;
7491 }
7492
Victor Stinner3a50e702011-10-18 21:21:00 +02007493 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007494 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007495 buffer, Py_ARRAY_LENGTH(buffer),
7496 NULL, pusedDefaultChar);
7497 if (outsize > 0) {
7498 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7499 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007500 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007501 memcpy(out, buffer, outsize);
7502 out += outsize;
7503 continue;
7504 }
7505 }
7506 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7507 PyErr_SetFromWindowsErr(0);
7508 goto error;
7509 }
7510
Victor Stinner3a50e702011-10-18 21:21:00 +02007511 rep = unicode_encode_call_errorhandler(
7512 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007513 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007514 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007515 if (rep == NULL)
7516 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007517 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007518
7519 if (PyBytes_Check(rep)) {
7520 outsize = PyBytes_GET_SIZE(rep);
7521 if (outsize != 1) {
7522 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7523 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7524 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7525 Py_DECREF(rep);
7526 goto error;
7527 }
7528 out = PyBytes_AS_STRING(*outbytes) + offset;
7529 }
7530 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7531 out += outsize;
7532 }
7533 else {
7534 Py_ssize_t i;
7535 enum PyUnicode_Kind kind;
7536 void *data;
7537
7538 if (PyUnicode_READY(rep) < 0) {
7539 Py_DECREF(rep);
7540 goto error;
7541 }
7542
7543 outsize = PyUnicode_GET_LENGTH(rep);
7544 if (outsize != 1) {
7545 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7546 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7547 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7548 Py_DECREF(rep);
7549 goto error;
7550 }
7551 out = PyBytes_AS_STRING(*outbytes) + offset;
7552 }
7553 kind = PyUnicode_KIND(rep);
7554 data = PyUnicode_DATA(rep);
7555 for (i=0; i < outsize; i++) {
7556 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7557 if (ch > 127) {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007558 raise_encode_exception_obj(&exc,
7559 encoding, unicode,
7560 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007561 "unable to encode error handler result to ASCII");
7562 Py_DECREF(rep);
7563 goto error;
7564 }
7565 *out = (unsigned char)ch;
7566 out++;
7567 }
7568 }
7569 Py_DECREF(rep);
7570 }
7571 /* write a NUL byte */
7572 *out = 0;
7573 outsize = out - PyBytes_AS_STRING(*outbytes);
7574 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7575 if (_PyBytes_Resize(outbytes, outsize) < 0)
7576 goto error;
7577 ret = 0;
7578
7579error:
7580 Py_XDECREF(encoding_obj);
7581 Py_XDECREF(errorHandler);
7582 Py_XDECREF(exc);
7583 return ret;
7584}
7585
Victor Stinner3a50e702011-10-18 21:21:00 +02007586static PyObject *
7587encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007588 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007589 const char *errors)
7590{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007591 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007592 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007593 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007594 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007595
Martin v. Löwis3d325192011-11-04 18:23:06 +01007596 if (PyUnicode_READY(unicode) < 0)
7597 return NULL;
7598 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007599
Victor Stinner3a50e702011-10-18 21:21:00 +02007600 if (code_page < 0) {
7601 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7602 return NULL;
7603 }
7604
Martin v. Löwis3d325192011-11-04 18:23:06 +01007605 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007606 return PyBytes_FromStringAndSize(NULL, 0);
7607
Victor Stinner7581cef2011-11-03 22:32:33 +01007608 offset = 0;
7609 do
7610 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007611#ifdef NEED_RETRY
Martin v. Löwis3d325192011-11-04 18:23:06 +01007612 /* UTF-16 encoding may double the size, so use only INT_MAX/2
7613 chunks. */
7614 if (len > INT_MAX/2) {
7615 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007616 done = 0;
7617 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007618 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007619#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007620 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007621 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007622 done = 1;
7623 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007624
Victor Stinner76a31a62011-11-04 00:05:13 +01007625 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007626 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007627 errors);
7628 if (ret == -2)
7629 ret = encode_code_page_errors(code_page, &outbytes,
7630 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007631 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007632 if (ret < 0) {
7633 Py_XDECREF(outbytes);
7634 return NULL;
7635 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007636
Victor Stinner7581cef2011-11-03 22:32:33 +01007637 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007638 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007639 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007640
Victor Stinner3a50e702011-10-18 21:21:00 +02007641 return outbytes;
7642}
7643
7644PyObject *
7645PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7646 Py_ssize_t size,
7647 const char *errors)
7648{
Victor Stinner7581cef2011-11-03 22:32:33 +01007649 PyObject *unicode, *res;
7650 unicode = PyUnicode_FromUnicode(p, size);
7651 if (unicode == NULL)
7652 return NULL;
7653 res = encode_code_page(CP_ACP, unicode, errors);
7654 Py_DECREF(unicode);
7655 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007656}
7657
7658PyObject *
7659PyUnicode_EncodeCodePage(int code_page,
7660 PyObject *unicode,
7661 const char *errors)
7662{
Victor Stinner7581cef2011-11-03 22:32:33 +01007663 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007664}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007665
Alexander Belopolsky40018472011-02-26 01:02:56 +00007666PyObject *
7667PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007668{
7669 if (!PyUnicode_Check(unicode)) {
7670 PyErr_BadArgument();
7671 return NULL;
7672 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007673 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007674}
7675
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007676#undef NEED_RETRY
7677
Victor Stinner99b95382011-07-04 14:23:54 +02007678#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007679
Guido van Rossumd57fd912000-03-10 22:53:23 +00007680/* --- Character Mapping Codec -------------------------------------------- */
7681
Alexander Belopolsky40018472011-02-26 01:02:56 +00007682PyObject *
7683PyUnicode_DecodeCharmap(const char *s,
7684 Py_ssize_t size,
7685 PyObject *mapping,
7686 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007687{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007688 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007689 Py_ssize_t startinpos;
7690 Py_ssize_t endinpos;
7691 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007692 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007693 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007694 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007695 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007696 PyObject *errorHandler = NULL;
7697 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007698 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007699 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007700
Guido van Rossumd57fd912000-03-10 22:53:23 +00007701 /* Default to Latin-1 */
7702 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007703 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007704
Victor Stinner7931d9a2011-11-04 00:22:48 +01007705 v = (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007706 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007708 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007709 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007710 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007711 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007712 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007713 mapstring = PyUnicode_AS_UNICODE(mapping);
7714 maplen = PyUnicode_GET_SIZE(mapping);
7715 while (s < e) {
7716 unsigned char ch = *s;
7717 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007718
Benjamin Peterson29060642009-01-31 22:14:21 +00007719 if (ch < maplen)
7720 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007721
Benjamin Peterson29060642009-01-31 22:14:21 +00007722 if (x == 0xfffe) {
7723 /* undefined mapping */
7724 outpos = p-PyUnicode_AS_UNICODE(v);
7725 startinpos = s-starts;
7726 endinpos = startinpos+1;
7727 if (unicode_decode_call_errorhandler(
7728 errors, &errorHandler,
7729 "charmap", "character maps to <undefined>",
7730 &starts, &e, &startinpos, &endinpos, &exc, &s,
7731 &v, &outpos, &p)) {
7732 goto onError;
7733 }
7734 continue;
7735 }
7736 *p++ = x;
7737 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007738 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007739 }
7740 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 while (s < e) {
7742 unsigned char ch = *s;
7743 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007744
Benjamin Peterson29060642009-01-31 22:14:21 +00007745 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7746 w = PyLong_FromLong((long)ch);
7747 if (w == NULL)
7748 goto onError;
7749 x = PyObject_GetItem(mapping, w);
7750 Py_DECREF(w);
7751 if (x == NULL) {
7752 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7753 /* No mapping found means: mapping is undefined. */
7754 PyErr_Clear();
7755 x = Py_None;
7756 Py_INCREF(x);
7757 } else
7758 goto onError;
7759 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007760
Benjamin Peterson29060642009-01-31 22:14:21 +00007761 /* Apply mapping */
7762 if (PyLong_Check(x)) {
7763 long value = PyLong_AS_LONG(x);
7764 if (value < 0 || value > 65535) {
7765 PyErr_SetString(PyExc_TypeError,
7766 "character mapping must be in range(65536)");
7767 Py_DECREF(x);
7768 goto onError;
7769 }
7770 *p++ = (Py_UNICODE)value;
7771 }
7772 else if (x == Py_None) {
7773 /* undefined mapping */
7774 outpos = p-PyUnicode_AS_UNICODE(v);
7775 startinpos = s-starts;
7776 endinpos = startinpos+1;
7777 if (unicode_decode_call_errorhandler(
7778 errors, &errorHandler,
7779 "charmap", "character maps to <undefined>",
7780 &starts, &e, &startinpos, &endinpos, &exc, &s,
7781 &v, &outpos, &p)) {
7782 Py_DECREF(x);
7783 goto onError;
7784 }
7785 Py_DECREF(x);
7786 continue;
7787 }
7788 else if (PyUnicode_Check(x)) {
7789 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007790
Benjamin Peterson29060642009-01-31 22:14:21 +00007791 if (targetsize == 1)
7792 /* 1-1 mapping */
7793 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007794
Benjamin Peterson29060642009-01-31 22:14:21 +00007795 else if (targetsize > 1) {
7796 /* 1-n mapping */
7797 if (targetsize > extrachars) {
7798 /* resize first */
7799 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7800 Py_ssize_t needed = (targetsize - extrachars) + \
7801 (targetsize << 2);
7802 extrachars += needed;
7803 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007804 if (PyUnicode_Resize(&v,
7805 PyUnicode_GET_SIZE(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007806 Py_DECREF(x);
7807 goto onError;
7808 }
7809 p = PyUnicode_AS_UNICODE(v) + oldpos;
7810 }
7811 Py_UNICODE_COPY(p,
7812 PyUnicode_AS_UNICODE(x),
7813 targetsize);
7814 p += targetsize;
7815 extrachars -= targetsize;
7816 }
7817 /* 1-0 mapping: skip the character */
7818 }
7819 else {
7820 /* wrong return value */
7821 PyErr_SetString(PyExc_TypeError,
7822 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007823 Py_DECREF(x);
7824 goto onError;
7825 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007826 Py_DECREF(x);
7827 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007828 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007829 }
7830 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinner7931d9a2011-11-04 00:22:48 +01007831 if (PyUnicode_Resize(&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007832 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007833 Py_XDECREF(errorHandler);
7834 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007835#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007836 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007837 Py_DECREF(v);
7838 return NULL;
7839 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007840#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007841 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007842 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007843
Benjamin Peterson29060642009-01-31 22:14:21 +00007844 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007845 Py_XDECREF(errorHandler);
7846 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007847 Py_XDECREF(v);
7848 return NULL;
7849}
7850
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007851/* Charmap encoding: the lookup table */
7852
Alexander Belopolsky40018472011-02-26 01:02:56 +00007853struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007854 PyObject_HEAD
7855 unsigned char level1[32];
7856 int count2, count3;
7857 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007858};
7859
7860static PyObject*
7861encoding_map_size(PyObject *obj, PyObject* args)
7862{
7863 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007864 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007865 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007866}
7867
7868static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007869 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007870 PyDoc_STR("Return the size (in bytes) of this object") },
7871 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007872};
7873
7874static void
7875encoding_map_dealloc(PyObject* o)
7876{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007877 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007878}
7879
7880static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007881 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007882 "EncodingMap", /*tp_name*/
7883 sizeof(struct encoding_map), /*tp_basicsize*/
7884 0, /*tp_itemsize*/
7885 /* methods */
7886 encoding_map_dealloc, /*tp_dealloc*/
7887 0, /*tp_print*/
7888 0, /*tp_getattr*/
7889 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007890 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007891 0, /*tp_repr*/
7892 0, /*tp_as_number*/
7893 0, /*tp_as_sequence*/
7894 0, /*tp_as_mapping*/
7895 0, /*tp_hash*/
7896 0, /*tp_call*/
7897 0, /*tp_str*/
7898 0, /*tp_getattro*/
7899 0, /*tp_setattro*/
7900 0, /*tp_as_buffer*/
7901 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7902 0, /*tp_doc*/
7903 0, /*tp_traverse*/
7904 0, /*tp_clear*/
7905 0, /*tp_richcompare*/
7906 0, /*tp_weaklistoffset*/
7907 0, /*tp_iter*/
7908 0, /*tp_iternext*/
7909 encoding_map_methods, /*tp_methods*/
7910 0, /*tp_members*/
7911 0, /*tp_getset*/
7912 0, /*tp_base*/
7913 0, /*tp_dict*/
7914 0, /*tp_descr_get*/
7915 0, /*tp_descr_set*/
7916 0, /*tp_dictoffset*/
7917 0, /*tp_init*/
7918 0, /*tp_alloc*/
7919 0, /*tp_new*/
7920 0, /*tp_free*/
7921 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007922};
7923
7924PyObject*
7925PyUnicode_BuildEncodingMap(PyObject* string)
7926{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007927 PyObject *result;
7928 struct encoding_map *mresult;
7929 int i;
7930 int need_dict = 0;
7931 unsigned char level1[32];
7932 unsigned char level2[512];
7933 unsigned char *mlevel1, *mlevel2, *mlevel3;
7934 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007935 int kind;
7936 void *data;
7937 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007939 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007940 PyErr_BadArgument();
7941 return NULL;
7942 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007943 kind = PyUnicode_KIND(string);
7944 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007945 memset(level1, 0xFF, sizeof level1);
7946 memset(level2, 0xFF, sizeof level2);
7947
7948 /* If there isn't a one-to-one mapping of NULL to \0,
7949 or if there are non-BMP characters, we need to use
7950 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007951 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007952 need_dict = 1;
7953 for (i = 1; i < 256; i++) {
7954 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007955 ch = PyUnicode_READ(kind, data, i);
7956 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007957 need_dict = 1;
7958 break;
7959 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007960 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007961 /* unmapped character */
7962 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007963 l1 = ch >> 11;
7964 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 if (level1[l1] == 0xFF)
7966 level1[l1] = count2++;
7967 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007968 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007969 }
7970
7971 if (count2 >= 0xFF || count3 >= 0xFF)
7972 need_dict = 1;
7973
7974 if (need_dict) {
7975 PyObject *result = PyDict_New();
7976 PyObject *key, *value;
7977 if (!result)
7978 return NULL;
7979 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007980 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007981 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007982 if (!key || !value)
7983 goto failed1;
7984 if (PyDict_SetItem(result, key, value) == -1)
7985 goto failed1;
7986 Py_DECREF(key);
7987 Py_DECREF(value);
7988 }
7989 return result;
7990 failed1:
7991 Py_XDECREF(key);
7992 Py_XDECREF(value);
7993 Py_DECREF(result);
7994 return NULL;
7995 }
7996
7997 /* Create a three-level trie */
7998 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7999 16*count2 + 128*count3 - 1);
8000 if (!result)
8001 return PyErr_NoMemory();
8002 PyObject_Init(result, &EncodingMapType);
8003 mresult = (struct encoding_map*)result;
8004 mresult->count2 = count2;
8005 mresult->count3 = count3;
8006 mlevel1 = mresult->level1;
8007 mlevel2 = mresult->level23;
8008 mlevel3 = mresult->level23 + 16*count2;
8009 memcpy(mlevel1, level1, 32);
8010 memset(mlevel2, 0xFF, 16*count2);
8011 memset(mlevel3, 0, 128*count3);
8012 count3 = 0;
8013 for (i = 1; i < 256; i++) {
8014 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008015 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008016 /* unmapped character */
8017 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008018 o1 = PyUnicode_READ(kind, data, i)>>11;
8019 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008020 i2 = 16*mlevel1[o1] + o2;
8021 if (mlevel2[i2] == 0xFF)
8022 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008023 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008024 i3 = 128*mlevel2[i2] + o3;
8025 mlevel3[i3] = i;
8026 }
8027 return result;
8028}
8029
8030static int
8031encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
8032{
8033 struct encoding_map *map = (struct encoding_map*)mapping;
8034 int l1 = c>>11;
8035 int l2 = (c>>7) & 0xF;
8036 int l3 = c & 0x7F;
8037 int i;
8038
8039#ifdef Py_UNICODE_WIDE
8040 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008041 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008042 }
8043#endif
8044 if (c == 0)
8045 return 0;
8046 /* level 1*/
8047 i = map->level1[l1];
8048 if (i == 0xFF) {
8049 return -1;
8050 }
8051 /* level 2*/
8052 i = map->level23[16*i+l2];
8053 if (i == 0xFF) {
8054 return -1;
8055 }
8056 /* level 3 */
8057 i = map->level23[16*map->count2 + 128*i + l3];
8058 if (i == 0) {
8059 return -1;
8060 }
8061 return i;
8062}
8063
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008064/* Lookup the character ch in the mapping. If the character
8065 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008066 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008067static PyObject *
8068charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008069{
Christian Heimes217cfd12007-12-02 14:31:20 +00008070 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008071 PyObject *x;
8072
8073 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008074 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075 x = PyObject_GetItem(mapping, w);
8076 Py_DECREF(w);
8077 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008078 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8079 /* No mapping found means: mapping is undefined. */
8080 PyErr_Clear();
8081 x = Py_None;
8082 Py_INCREF(x);
8083 return x;
8084 } else
8085 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008086 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008087 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008088 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008089 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 long value = PyLong_AS_LONG(x);
8091 if (value < 0 || value > 255) {
8092 PyErr_SetString(PyExc_TypeError,
8093 "character mapping must be in range(256)");
8094 Py_DECREF(x);
8095 return NULL;
8096 }
8097 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008098 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008099 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008100 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008101 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 /* wrong return value */
8103 PyErr_Format(PyExc_TypeError,
8104 "character mapping must return integer, bytes or None, not %.400s",
8105 x->ob_type->tp_name);
8106 Py_DECREF(x);
8107 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008108 }
8109}
8110
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008111static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008112charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008113{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008114 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8115 /* exponentially overallocate to minimize reallocations */
8116 if (requiredsize < 2*outsize)
8117 requiredsize = 2*outsize;
8118 if (_PyBytes_Resize(outobj, requiredsize))
8119 return -1;
8120 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008121}
8122
Benjamin Peterson14339b62009-01-31 16:36:08 +00008123typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008124 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008125} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008126/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008127 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008128 space is available. Return a new reference to the object that
8129 was put in the output buffer, or Py_None, if the mapping was undefined
8130 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008131 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008132static charmapencode_result
8133charmapencode_output(Py_UNICODE c, PyObject *mapping,
8134 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008135{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008136 PyObject *rep;
8137 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008138 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008139
Christian Heimes90aa7642007-12-19 02:45:37 +00008140 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008141 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008142 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008143 if (res == -1)
8144 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 if (outsize<requiredsize)
8146 if (charmapencode_resize(outobj, outpos, requiredsize))
8147 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008148 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008149 outstart[(*outpos)++] = (char)res;
8150 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008151 }
8152
8153 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008155 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008156 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008157 Py_DECREF(rep);
8158 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008159 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008160 if (PyLong_Check(rep)) {
8161 Py_ssize_t requiredsize = *outpos+1;
8162 if (outsize<requiredsize)
8163 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8164 Py_DECREF(rep);
8165 return enc_EXCEPTION;
8166 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008167 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008168 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008169 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008170 else {
8171 const char *repchars = PyBytes_AS_STRING(rep);
8172 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8173 Py_ssize_t requiredsize = *outpos+repsize;
8174 if (outsize<requiredsize)
8175 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8176 Py_DECREF(rep);
8177 return enc_EXCEPTION;
8178 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008179 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008180 memcpy(outstart + *outpos, repchars, repsize);
8181 *outpos += repsize;
8182 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008183 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008184 Py_DECREF(rep);
8185 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008186}
8187
8188/* handle an error in PyUnicode_EncodeCharmap
8189 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008190static int
8191charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008192 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008193 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008194 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008195 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196{
8197 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008198 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008199 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008200 Py_UNICODE *uni2;
8201 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008202 Py_ssize_t collstartpos = *inpos;
8203 Py_ssize_t collendpos = *inpos+1;
8204 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008205 char *encoding = "charmap";
8206 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008207 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008208 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008209 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008210
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008211 if (PyUnicode_READY(unicode) < 0)
8212 return -1;
8213 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214 /* find all unencodable characters */
8215 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008216 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008217 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008218 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008219 val = encoding_map_lookup(ch, mapping);
8220 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008221 break;
8222 ++collendpos;
8223 continue;
8224 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008225
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008226 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8227 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008228 if (rep==NULL)
8229 return -1;
8230 else if (rep!=Py_None) {
8231 Py_DECREF(rep);
8232 break;
8233 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008234 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008236 }
8237 /* cache callback name lookup
8238 * (if not done yet, i.e. it's the first error) */
8239 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008240 if ((errors==NULL) || (!strcmp(errors, "strict")))
8241 *known_errorHandler = 1;
8242 else if (!strcmp(errors, "replace"))
8243 *known_errorHandler = 2;
8244 else if (!strcmp(errors, "ignore"))
8245 *known_errorHandler = 3;
8246 else if (!strcmp(errors, "xmlcharrefreplace"))
8247 *known_errorHandler = 4;
8248 else
8249 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008250 }
8251 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252 case 1: /* strict */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008253 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008254 return -1;
8255 case 2: /* replace */
8256 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008257 x = charmapencode_output('?', mapping, res, respos);
8258 if (x==enc_EXCEPTION) {
8259 return -1;
8260 }
8261 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008262 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008263 return -1;
8264 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008265 }
8266 /* fall through */
8267 case 3: /* ignore */
8268 *inpos = collendpos;
8269 break;
8270 case 4: /* xmlcharrefreplace */
8271 /* generate replacement (temporarily (mis)uses p) */
8272 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008273 char buffer[2+29+1+1];
8274 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008275 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008276 for (cp = buffer; *cp; ++cp) {
8277 x = charmapencode_output(*cp, mapping, res, respos);
8278 if (x==enc_EXCEPTION)
8279 return -1;
8280 else if (x==enc_FAILED) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008281 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008282 return -1;
8283 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008284 }
8285 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008286 *inpos = collendpos;
8287 break;
8288 default:
8289 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008290 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008291 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008292 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008294 if (PyBytes_Check(repunicode)) {
8295 /* Directly copy bytes result to output. */
8296 Py_ssize_t outsize = PyBytes_Size(*res);
8297 Py_ssize_t requiredsize;
8298 repsize = PyBytes_Size(repunicode);
8299 requiredsize = *respos + repsize;
8300 if (requiredsize > outsize)
8301 /* Make room for all additional bytes. */
8302 if (charmapencode_resize(res, respos, requiredsize)) {
8303 Py_DECREF(repunicode);
8304 return -1;
8305 }
8306 memcpy(PyBytes_AsString(*res) + *respos,
8307 PyBytes_AsString(repunicode), repsize);
8308 *respos += repsize;
8309 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008310 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008311 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008312 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008313 /* generate replacement */
8314 repsize = PyUnicode_GET_SIZE(repunicode);
8315 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008316 x = charmapencode_output(*uni2, mapping, res, respos);
8317 if (x==enc_EXCEPTION) {
8318 return -1;
8319 }
8320 else if (x==enc_FAILED) {
8321 Py_DECREF(repunicode);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008322 raise_encode_exception_obj(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 return -1;
8324 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008325 }
8326 *inpos = newpos;
8327 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008328 }
8329 return 0;
8330}
8331
Alexander Belopolsky40018472011-02-26 01:02:56 +00008332PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008333_PyUnicode_EncodeCharmap(PyObject *unicode,
8334 PyObject *mapping,
8335 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008336{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 /* output object */
8338 PyObject *res = NULL;
8339 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008340 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008341 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008343 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 PyObject *errorHandler = NULL;
8345 PyObject *exc = NULL;
8346 /* the following variable is used for caching string comparisons
8347 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8348 * 3=ignore, 4=xmlcharrefreplace */
8349 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008350
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008351 if (PyUnicode_READY(unicode) < 0)
8352 return NULL;
8353 size = PyUnicode_GET_LENGTH(unicode);
8354
Guido van Rossumd57fd912000-03-10 22:53:23 +00008355 /* Default to Latin-1 */
8356 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008357 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008358
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 /* allocate enough for a simple encoding without
8360 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008361 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 if (res == NULL)
8363 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008364 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008365 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008366
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008368 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008370 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008371 if (x==enc_EXCEPTION) /* error */
8372 goto onError;
8373 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008374 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008375 &exc,
8376 &known_errorHandler, &errorHandler, errors,
8377 &res, &respos)) {
8378 goto onError;
8379 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008380 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008381 else
8382 /* done with this character => adjust input position */
8383 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008384 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008385
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008387 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008388 if (_PyBytes_Resize(&res, respos) < 0)
8389 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008390
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008391 Py_XDECREF(exc);
8392 Py_XDECREF(errorHandler);
8393 return res;
8394
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008396 Py_XDECREF(res);
8397 Py_XDECREF(exc);
8398 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008399 return NULL;
8400}
8401
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008402/* Deprecated */
8403PyObject *
8404PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8405 Py_ssize_t size,
8406 PyObject *mapping,
8407 const char *errors)
8408{
8409 PyObject *result;
8410 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8411 if (unicode == NULL)
8412 return NULL;
8413 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8414 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008415 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008416}
8417
Alexander Belopolsky40018472011-02-26 01:02:56 +00008418PyObject *
8419PyUnicode_AsCharmapString(PyObject *unicode,
8420 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008421{
8422 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 PyErr_BadArgument();
8424 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008425 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008426 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008427}
8428
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008430static void
8431make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008433 Py_ssize_t startpos, Py_ssize_t endpos,
8434 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008435{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008436 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008437 *exceptionObject = _PyUnicodeTranslateError_Create(
8438 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008439 }
8440 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008441 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8442 goto onError;
8443 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8444 goto onError;
8445 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8446 goto onError;
8447 return;
8448 onError:
8449 Py_DECREF(*exceptionObject);
8450 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008451 }
8452}
8453
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008454/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008455static void
8456raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008457 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008458 Py_ssize_t startpos, Py_ssize_t endpos,
8459 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460{
8461 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008462 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008465}
8466
8467/* error handling callback helper:
8468 build arguments, call the callback and check the arguments,
8469 put the result into newpos and return the replacement string, which
8470 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008471static PyObject *
8472unicode_translate_call_errorhandler(const char *errors,
8473 PyObject **errorHandler,
8474 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008476 Py_ssize_t startpos, Py_ssize_t endpos,
8477 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008479 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008480
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008481 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008482 PyObject *restuple;
8483 PyObject *resunicode;
8484
8485 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008488 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008489 }
8490
8491 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008492 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008494 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008495
8496 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008498 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008499 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008501 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008502 Py_DECREF(restuple);
8503 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008504 }
8505 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 &resunicode, &i_newpos)) {
8507 Py_DECREF(restuple);
8508 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008509 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008510 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008511 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008512 else
8513 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008514 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008515 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8516 Py_DECREF(restuple);
8517 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008518 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008519 Py_INCREF(resunicode);
8520 Py_DECREF(restuple);
8521 return resunicode;
8522}
8523
8524/* Lookup the character ch in the mapping and put the result in result,
8525 which must be decrefed by the caller.
8526 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008527static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529{
Christian Heimes217cfd12007-12-02 14:31:20 +00008530 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008531 PyObject *x;
8532
8533 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008535 x = PyObject_GetItem(mapping, w);
8536 Py_DECREF(w);
8537 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8539 /* No mapping found means: use 1:1 mapping. */
8540 PyErr_Clear();
8541 *result = NULL;
8542 return 0;
8543 } else
8544 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008545 }
8546 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 *result = x;
8548 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008549 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008550 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008551 long value = PyLong_AS_LONG(x);
8552 long max = PyUnicode_GetMax();
8553 if (value < 0 || value > max) {
8554 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008555 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008556 Py_DECREF(x);
8557 return -1;
8558 }
8559 *result = x;
8560 return 0;
8561 }
8562 else if (PyUnicode_Check(x)) {
8563 *result = x;
8564 return 0;
8565 }
8566 else {
8567 /* wrong return value */
8568 PyErr_SetString(PyExc_TypeError,
8569 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008570 Py_DECREF(x);
8571 return -1;
8572 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008573}
8574/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 if not reallocate and adjust various state variables.
8576 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008577static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008578charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008582 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008583 /* exponentially overallocate to minimize reallocations */
8584 if (requiredsize < 2 * oldsize)
8585 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008586 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8587 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008590 }
8591 return 0;
8592}
8593/* lookup the character, put the result in the output string and adjust
8594 various state variables. Return a new reference to the object that
8595 was put in the output buffer in *result, or Py_None, if the mapping was
8596 undefined (in which case no character was written).
8597 The called must decref result.
8598 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008599static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8601 PyObject *mapping, Py_UCS4 **output,
8602 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008603 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008604{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008605 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8606 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008607 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008608 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008611 }
8612 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008614 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008615 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008617 }
8618 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 Py_ssize_t repsize;
8620 if (PyUnicode_READY(*res) == -1)
8621 return -1;
8622 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 if (repsize==1) {
8624 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 }
8627 else if (repsize!=0) {
8628 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 Py_ssize_t requiredsize = *opos +
8630 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 Py_ssize_t i;
8633 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008635 for(i = 0; i < repsize; i++)
8636 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008637 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008638 }
8639 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008641 return 0;
8642}
8643
Alexander Belopolsky40018472011-02-26 01:02:56 +00008644PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008645_PyUnicode_TranslateCharmap(PyObject *input,
8646 PyObject *mapping,
8647 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008648{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649 /* input object */
8650 char *idata;
8651 Py_ssize_t size, i;
8652 int kind;
8653 /* output buffer */
8654 Py_UCS4 *output = NULL;
8655 Py_ssize_t osize;
8656 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008657 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 char *reason = "character maps to <undefined>";
8660 PyObject *errorHandler = NULL;
8661 PyObject *exc = NULL;
8662 /* the following variable is used for caching string comparisons
8663 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8664 * 3=ignore, 4=xmlcharrefreplace */
8665 int known_errorHandler = -1;
8666
Guido van Rossumd57fd912000-03-10 22:53:23 +00008667 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 PyErr_BadArgument();
8669 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008670 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008672 if (PyUnicode_READY(input) == -1)
8673 return NULL;
8674 idata = (char*)PyUnicode_DATA(input);
8675 kind = PyUnicode_KIND(input);
8676 size = PyUnicode_GET_LENGTH(input);
8677 i = 0;
8678
8679 if (size == 0) {
8680 Py_INCREF(input);
8681 return input;
8682 }
8683
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008684 /* allocate enough for a simple 1:1 translation without
8685 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008686 osize = size;
8687 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8688 opos = 0;
8689 if (output == NULL) {
8690 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008692 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008693
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008694 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008695 /* try to encode it */
8696 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008697 if (charmaptranslate_output(input, i, mapping,
8698 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008699 Py_XDECREF(x);
8700 goto onError;
8701 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008702 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008703 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008705 else { /* untranslatable character */
8706 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8707 Py_ssize_t repsize;
8708 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008709 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008710 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008711 Py_ssize_t collstart = i;
8712 Py_ssize_t collend = i+1;
8713 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008714
Benjamin Peterson29060642009-01-31 22:14:21 +00008715 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008716 while (collend < size) {
8717 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008718 goto onError;
8719 Py_XDECREF(x);
8720 if (x!=Py_None)
8721 break;
8722 ++collend;
8723 }
8724 /* cache callback name lookup
8725 * (if not done yet, i.e. it's the first error) */
8726 if (known_errorHandler==-1) {
8727 if ((errors==NULL) || (!strcmp(errors, "strict")))
8728 known_errorHandler = 1;
8729 else if (!strcmp(errors, "replace"))
8730 known_errorHandler = 2;
8731 else if (!strcmp(errors, "ignore"))
8732 known_errorHandler = 3;
8733 else if (!strcmp(errors, "xmlcharrefreplace"))
8734 known_errorHandler = 4;
8735 else
8736 known_errorHandler = 0;
8737 }
8738 switch (known_errorHandler) {
8739 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008740 raise_translate_exception(&exc, input, collstart,
8741 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008742 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 case 2: /* replace */
8744 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008745 for (coll = collstart; coll<collend; coll++)
8746 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008747 /* fall through */
8748 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008749 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008750 break;
8751 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008752 /* generate replacement (temporarily (mis)uses i) */
8753 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008754 char buffer[2+29+1+1];
8755 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008756 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8757 if (charmaptranslate_makespace(&output, &osize,
8758 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008759 goto onError;
8760 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008761 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008762 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008763 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008764 break;
8765 default:
8766 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008767 reason, input, &exc,
8768 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008769 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008770 goto onError;
8771 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008772 repsize = PyUnicode_GET_LENGTH(repunicode);
8773 if (charmaptranslate_makespace(&output, &osize,
8774 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008775 Py_DECREF(repunicode);
8776 goto onError;
8777 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008778 for (uni2 = 0; repsize-->0; ++uni2)
8779 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8780 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008782 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008783 }
8784 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008785 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8786 if (!res)
8787 goto onError;
8788 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008789 Py_XDECREF(exc);
8790 Py_XDECREF(errorHandler);
8791 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008792
Benjamin Peterson29060642009-01-31 22:14:21 +00008793 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008794 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008795 Py_XDECREF(exc);
8796 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008797 return NULL;
8798}
8799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008800/* Deprecated. Use PyUnicode_Translate instead. */
8801PyObject *
8802PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8803 Py_ssize_t size,
8804 PyObject *mapping,
8805 const char *errors)
8806{
8807 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8808 if (!unicode)
8809 return NULL;
8810 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8811}
8812
Alexander Belopolsky40018472011-02-26 01:02:56 +00008813PyObject *
8814PyUnicode_Translate(PyObject *str,
8815 PyObject *mapping,
8816 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008817{
8818 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008819
Guido van Rossumd57fd912000-03-10 22:53:23 +00008820 str = PyUnicode_FromObject(str);
8821 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008823 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008824 Py_DECREF(str);
8825 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008826
Benjamin Peterson29060642009-01-31 22:14:21 +00008827 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008828 Py_XDECREF(str);
8829 return NULL;
8830}
Tim Petersced69f82003-09-16 20:30:58 +00008831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008832static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008833fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008834{
8835 /* No need to call PyUnicode_READY(self) because this function is only
8836 called as a callback from fixup() which does it already. */
8837 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8838 const int kind = PyUnicode_KIND(self);
8839 void *data = PyUnicode_DATA(self);
8840 Py_UCS4 maxchar = 0, ch, fixed;
8841 Py_ssize_t i;
8842
8843 for (i = 0; i < len; ++i) {
8844 ch = PyUnicode_READ(kind, data, i);
8845 fixed = 0;
8846 if (ch > 127) {
8847 if (Py_UNICODE_ISSPACE(ch))
8848 fixed = ' ';
8849 else {
8850 const int decimal = Py_UNICODE_TODECIMAL(ch);
8851 if (decimal >= 0)
8852 fixed = '0' + decimal;
8853 }
8854 if (fixed != 0) {
8855 if (fixed > maxchar)
8856 maxchar = fixed;
8857 PyUnicode_WRITE(kind, data, i, fixed);
8858 }
8859 else if (ch > maxchar)
8860 maxchar = ch;
8861 }
8862 else if (ch > maxchar)
8863 maxchar = ch;
8864 }
8865
8866 return maxchar;
8867}
8868
8869PyObject *
8870_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8871{
8872 if (!PyUnicode_Check(unicode)) {
8873 PyErr_BadInternalCall();
8874 return NULL;
8875 }
8876 if (PyUnicode_READY(unicode) == -1)
8877 return NULL;
8878 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8879 /* If the string is already ASCII, just return the same string */
8880 Py_INCREF(unicode);
8881 return unicode;
8882 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008883 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008884}
8885
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008886PyObject *
8887PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8888 Py_ssize_t length)
8889{
8890 PyObject *result;
8891 Py_UNICODE *p; /* write pointer into result */
8892 Py_ssize_t i;
8893 /* Copy to a new string */
8894 result = (PyObject *)_PyUnicode_New(length);
8895 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8896 if (result == NULL)
8897 return result;
8898 p = PyUnicode_AS_UNICODE(result);
8899 /* Iterate over code points */
8900 for (i = 0; i < length; i++) {
8901 Py_UNICODE ch =s[i];
8902 if (ch > 127) {
8903 int decimal = Py_UNICODE_TODECIMAL(ch);
8904 if (decimal >= 0)
8905 p[i] = '0' + decimal;
8906 }
8907 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008908#ifndef DONT_MAKE_RESULT_READY
8909 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008910 Py_DECREF(result);
8911 return NULL;
8912 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008913#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008914 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008915 return result;
8916}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008917/* --- Decimal Encoder ---------------------------------------------------- */
8918
Alexander Belopolsky40018472011-02-26 01:02:56 +00008919int
8920PyUnicode_EncodeDecimal(Py_UNICODE *s,
8921 Py_ssize_t length,
8922 char *output,
8923 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008924{
8925 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008926 PyObject *errorHandler = NULL;
8927 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008928 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008929 const char *encoding = "decimal";
8930 const char *reason = "invalid decimal Unicode string";
8931 /* the following variable is used for caching string comparisons
8932 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8933 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008934
8935 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008936 PyErr_BadArgument();
8937 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008938 }
8939
8940 p = s;
8941 end = s + length;
8942 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008943 register Py_UNICODE ch = *p;
8944 int decimal;
8945 PyObject *repunicode;
8946 Py_ssize_t repsize;
8947 Py_ssize_t newpos;
8948 Py_UNICODE *uni2;
8949 Py_UNICODE *collstart;
8950 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008951
Benjamin Peterson29060642009-01-31 22:14:21 +00008952 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008953 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008954 ++p;
8955 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008956 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008957 decimal = Py_UNICODE_TODECIMAL(ch);
8958 if (decimal >= 0) {
8959 *output++ = '0' + decimal;
8960 ++p;
8961 continue;
8962 }
8963 if (0 < ch && ch < 256) {
8964 *output++ = (char)ch;
8965 ++p;
8966 continue;
8967 }
8968 /* All other characters are considered unencodable */
8969 collstart = p;
8970 collend = p+1;
8971 while (collend < end) {
8972 if ((0 < *collend && *collend < 256) ||
8973 !Py_UNICODE_ISSPACE(*collend) ||
8974 Py_UNICODE_TODECIMAL(*collend))
8975 break;
8976 }
8977 /* cache callback name lookup
8978 * (if not done yet, i.e. it's the first error) */
8979 if (known_errorHandler==-1) {
8980 if ((errors==NULL) || (!strcmp(errors, "strict")))
8981 known_errorHandler = 1;
8982 else if (!strcmp(errors, "replace"))
8983 known_errorHandler = 2;
8984 else if (!strcmp(errors, "ignore"))
8985 known_errorHandler = 3;
8986 else if (!strcmp(errors, "xmlcharrefreplace"))
8987 known_errorHandler = 4;
8988 else
8989 known_errorHandler = 0;
8990 }
8991 switch (known_errorHandler) {
8992 case 1: /* strict */
8993 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8994 goto onError;
8995 case 2: /* replace */
8996 for (p = collstart; p < collend; ++p)
8997 *output++ = '?';
8998 /* fall through */
8999 case 3: /* ignore */
9000 p = collend;
9001 break;
9002 case 4: /* xmlcharrefreplace */
9003 /* generate replacement (temporarily (mis)uses p) */
9004 for (p = collstart; p < collend; ++p)
9005 output += sprintf(output, "&#%d;", (int)*p);
9006 p = collend;
9007 break;
9008 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009009 unicode = PyUnicode_FromUnicode(s, length);
9010 if (unicode == NULL)
9011 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00009012 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009013 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00009014 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01009015 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00009016 if (repunicode == NULL)
9017 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009018 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00009019 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00009020 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
9021 Py_DECREF(repunicode);
9022 goto onError;
9023 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009024 /* generate replacement */
9025 repsize = PyUnicode_GET_SIZE(repunicode);
9026 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
9027 Py_UNICODE ch = *uni2;
9028 if (Py_UNICODE_ISSPACE(ch))
9029 *output++ = ' ';
9030 else {
9031 decimal = Py_UNICODE_TODECIMAL(ch);
9032 if (decimal >= 0)
9033 *output++ = '0' + decimal;
9034 else if (0 < ch && ch < 256)
9035 *output++ = (char)ch;
9036 else {
9037 Py_DECREF(repunicode);
9038 raise_encode_exception(&exc, encoding,
9039 s, length, collstart-s, collend-s, reason);
9040 goto onError;
9041 }
9042 }
9043 }
9044 p = s + newpos;
9045 Py_DECREF(repunicode);
9046 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00009047 }
9048 /* 0-terminate the output string */
9049 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009050 Py_XDECREF(exc);
9051 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009052 return 0;
9053
Benjamin Peterson29060642009-01-31 22:14:21 +00009054 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00009055 Py_XDECREF(exc);
9056 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00009057 return -1;
9058}
9059
Guido van Rossumd57fd912000-03-10 22:53:23 +00009060/* --- Helpers ------------------------------------------------------------ */
9061
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009062static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02009063any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009064 Py_ssize_t start,
9065 Py_ssize_t end)
9066{
9067 int kind1, kind2, kind;
9068 void *buf1, *buf2;
9069 Py_ssize_t len1, len2, result;
9070
9071 kind1 = PyUnicode_KIND(s1);
9072 kind2 = PyUnicode_KIND(s2);
9073 kind = kind1 > kind2 ? kind1 : kind2;
9074 buf1 = PyUnicode_DATA(s1);
9075 buf2 = PyUnicode_DATA(s2);
9076 if (kind1 != kind)
9077 buf1 = _PyUnicode_AsKind(s1, kind);
9078 if (!buf1)
9079 return -2;
9080 if (kind2 != kind)
9081 buf2 = _PyUnicode_AsKind(s2, kind);
9082 if (!buf2) {
9083 if (kind1 != kind) PyMem_Free(buf1);
9084 return -2;
9085 }
9086 len1 = PyUnicode_GET_LENGTH(s1);
9087 len2 = PyUnicode_GET_LENGTH(s2);
9088
Victor Stinner794d5672011-10-10 03:21:36 +02009089 if (direction > 0) {
9090 switch(kind) {
9091 case PyUnicode_1BYTE_KIND:
9092 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9093 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9094 else
9095 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9096 break;
9097 case PyUnicode_2BYTE_KIND:
9098 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9099 break;
9100 case PyUnicode_4BYTE_KIND:
9101 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9102 break;
9103 default:
9104 assert(0); result = -2;
9105 }
9106 }
9107 else {
9108 switch(kind) {
9109 case PyUnicode_1BYTE_KIND:
9110 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9111 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9112 else
9113 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9114 break;
9115 case PyUnicode_2BYTE_KIND:
9116 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9117 break;
9118 case PyUnicode_4BYTE_KIND:
9119 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9120 break;
9121 default:
9122 assert(0); result = -2;
9123 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009124 }
9125
9126 if (kind1 != kind)
9127 PyMem_Free(buf1);
9128 if (kind2 != kind)
9129 PyMem_Free(buf2);
9130
9131 return result;
9132}
9133
9134Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009135_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136 Py_ssize_t n_buffer,
9137 void *digits, Py_ssize_t n_digits,
9138 Py_ssize_t min_width,
9139 const char *grouping,
9140 const char *thousands_sep)
9141{
9142 switch(kind) {
9143 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009144 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9145 return _PyUnicode_ascii_InsertThousandsGrouping(
9146 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9147 min_width, grouping, thousands_sep);
9148 else
9149 return _PyUnicode_ucs1_InsertThousandsGrouping(
9150 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9151 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 case PyUnicode_2BYTE_KIND:
9153 return _PyUnicode_ucs2_InsertThousandsGrouping(
9154 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9155 min_width, grouping, thousands_sep);
9156 case PyUnicode_4BYTE_KIND:
9157 return _PyUnicode_ucs4_InsertThousandsGrouping(
9158 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9159 min_width, grouping, thousands_sep);
9160 }
9161 assert(0);
9162 return -1;
9163}
9164
9165
Thomas Wouters477c8d52006-05-27 19:21:47 +00009166/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009167#define ADJUST_INDICES(start, end, len) \
9168 if (end > len) \
9169 end = len; \
9170 else if (end < 0) { \
9171 end += len; \
9172 if (end < 0) \
9173 end = 0; \
9174 } \
9175 if (start < 0) { \
9176 start += len; \
9177 if (start < 0) \
9178 start = 0; \
9179 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009180
Alexander Belopolsky40018472011-02-26 01:02:56 +00009181Py_ssize_t
9182PyUnicode_Count(PyObject *str,
9183 PyObject *substr,
9184 Py_ssize_t start,
9185 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009186{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009187 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009188 PyObject* str_obj;
9189 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 int kind1, kind2, kind;
9191 void *buf1 = NULL, *buf2 = NULL;
9192 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009193
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009194 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009195 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009196 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009197 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009198 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009199 Py_DECREF(str_obj);
9200 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009201 }
Tim Petersced69f82003-09-16 20:30:58 +00009202
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 kind1 = PyUnicode_KIND(str_obj);
9204 kind2 = PyUnicode_KIND(sub_obj);
9205 kind = kind1 > kind2 ? kind1 : kind2;
9206 buf1 = PyUnicode_DATA(str_obj);
9207 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009208 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009209 if (!buf1)
9210 goto onError;
9211 buf2 = PyUnicode_DATA(sub_obj);
9212 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009213 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009214 if (!buf2)
9215 goto onError;
9216 len1 = PyUnicode_GET_LENGTH(str_obj);
9217 len2 = PyUnicode_GET_LENGTH(sub_obj);
9218
9219 ADJUST_INDICES(start, end, len1);
9220 switch(kind) {
9221 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009222 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9223 result = asciilib_count(
9224 ((Py_UCS1*)buf1) + start, end - start,
9225 buf2, len2, PY_SSIZE_T_MAX
9226 );
9227 else
9228 result = ucs1lib_count(
9229 ((Py_UCS1*)buf1) + start, end - start,
9230 buf2, len2, PY_SSIZE_T_MAX
9231 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 break;
9233 case PyUnicode_2BYTE_KIND:
9234 result = ucs2lib_count(
9235 ((Py_UCS2*)buf1) + start, end - start,
9236 buf2, len2, PY_SSIZE_T_MAX
9237 );
9238 break;
9239 case PyUnicode_4BYTE_KIND:
9240 result = ucs4lib_count(
9241 ((Py_UCS4*)buf1) + start, end - start,
9242 buf2, len2, PY_SSIZE_T_MAX
9243 );
9244 break;
9245 default:
9246 assert(0); result = 0;
9247 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009248
9249 Py_DECREF(sub_obj);
9250 Py_DECREF(str_obj);
9251
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009252 if (kind1 != kind)
9253 PyMem_Free(buf1);
9254 if (kind2 != kind)
9255 PyMem_Free(buf2);
9256
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 onError:
9259 Py_DECREF(sub_obj);
9260 Py_DECREF(str_obj);
9261 if (kind1 != kind && buf1)
9262 PyMem_Free(buf1);
9263 if (kind2 != kind && buf2)
9264 PyMem_Free(buf2);
9265 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009266}
9267
Alexander Belopolsky40018472011-02-26 01:02:56 +00009268Py_ssize_t
9269PyUnicode_Find(PyObject *str,
9270 PyObject *sub,
9271 Py_ssize_t start,
9272 Py_ssize_t end,
9273 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009274{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009275 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009276
Guido van Rossumd57fd912000-03-10 22:53:23 +00009277 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009278 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009279 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009280 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009281 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009282 Py_DECREF(str);
9283 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009284 }
Tim Petersced69f82003-09-16 20:30:58 +00009285
Victor Stinner794d5672011-10-10 03:21:36 +02009286 result = any_find_slice(direction,
9287 str, sub, start, end
9288 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009289
Guido van Rossumd57fd912000-03-10 22:53:23 +00009290 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009291 Py_DECREF(sub);
9292
Guido van Rossumd57fd912000-03-10 22:53:23 +00009293 return result;
9294}
9295
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009296Py_ssize_t
9297PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9298 Py_ssize_t start, Py_ssize_t end,
9299 int direction)
9300{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009302 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009303 if (PyUnicode_READY(str) == -1)
9304 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009305 if (start < 0 || end < 0) {
9306 PyErr_SetString(PyExc_IndexError, "string index out of range");
9307 return -2;
9308 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009309 if (end > PyUnicode_GET_LENGTH(str))
9310 end = PyUnicode_GET_LENGTH(str);
9311 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009312 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9313 kind, end-start, ch, direction);
9314 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009315 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009316 else
9317 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009318}
9319
Alexander Belopolsky40018472011-02-26 01:02:56 +00009320static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009321tailmatch(PyObject *self,
9322 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009323 Py_ssize_t start,
9324 Py_ssize_t end,
9325 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 int kind_self;
9328 int kind_sub;
9329 void *data_self;
9330 void *data_sub;
9331 Py_ssize_t offset;
9332 Py_ssize_t i;
9333 Py_ssize_t end_sub;
9334
9335 if (PyUnicode_READY(self) == -1 ||
9336 PyUnicode_READY(substring) == -1)
9337 return 0;
9338
9339 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009340 return 1;
9341
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009342 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9343 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009344 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009345 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009346
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009347 kind_self = PyUnicode_KIND(self);
9348 data_self = PyUnicode_DATA(self);
9349 kind_sub = PyUnicode_KIND(substring);
9350 data_sub = PyUnicode_DATA(substring);
9351 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9352
9353 if (direction > 0)
9354 offset = end;
9355 else
9356 offset = start;
9357
9358 if (PyUnicode_READ(kind_self, data_self, offset) ==
9359 PyUnicode_READ(kind_sub, data_sub, 0) &&
9360 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9361 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9362 /* If both are of the same kind, memcmp is sufficient */
9363 if (kind_self == kind_sub) {
9364 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009365 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366 data_sub,
9367 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009368 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009369 }
9370 /* otherwise we have to compare each character by first accesing it */
9371 else {
9372 /* We do not need to compare 0 and len(substring)-1 because
9373 the if statement above ensured already that they are equal
9374 when we end up here. */
9375 // TODO: honor direction and do a forward or backwards search
9376 for (i = 1; i < end_sub; ++i) {
9377 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9378 PyUnicode_READ(kind_sub, data_sub, i))
9379 return 0;
9380 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009381 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383 }
9384
9385 return 0;
9386}
9387
Alexander Belopolsky40018472011-02-26 01:02:56 +00009388Py_ssize_t
9389PyUnicode_Tailmatch(PyObject *str,
9390 PyObject *substr,
9391 Py_ssize_t start,
9392 Py_ssize_t end,
9393 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009394{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009395 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009396
Guido van Rossumd57fd912000-03-10 22:53:23 +00009397 str = PyUnicode_FromObject(str);
9398 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009399 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009400 substr = PyUnicode_FromObject(substr);
9401 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009402 Py_DECREF(str);
9403 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404 }
Tim Petersced69f82003-09-16 20:30:58 +00009405
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009406 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009407 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009408 Py_DECREF(str);
9409 Py_DECREF(substr);
9410 return result;
9411}
9412
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413/* Apply fixfct filter to the Unicode object self and return a
9414 reference to the modified object */
9415
Alexander Belopolsky40018472011-02-26 01:02:56 +00009416static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009417fixup(PyObject *self,
9418 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009419{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 PyObject *u;
9421 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009422
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009423 if (PyUnicode_READY(self) == -1)
9424 return NULL;
9425 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9426 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9427 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009429 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009431 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009432 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009433
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009434 /* fix functions return the new maximum character in a string,
9435 if the kind of the resulting unicode object does not change,
9436 everything is fine. Otherwise we need to change the string kind
9437 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009438 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 if (maxchar_new == 0)
9440 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9441 else if (maxchar_new <= 127)
9442 maxchar_new = 127;
9443 else if (maxchar_new <= 255)
9444 maxchar_new = 255;
9445 else if (maxchar_new <= 65535)
9446 maxchar_new = 65535;
9447 else
9448 maxchar_new = 1114111; /* 0x10ffff */
9449
9450 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009451 /* fixfct should return TRUE if it modified the buffer. If
9452 FALSE, return a reference to the original buffer instead
9453 (to save space, not time) */
9454 Py_INCREF(self);
9455 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009456 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009458 else if (maxchar_new == maxchar_old) {
9459 return u;
9460 }
9461 else {
9462 /* In case the maximum character changed, we need to
9463 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009464 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 if (v == NULL) {
9466 Py_DECREF(u);
9467 return NULL;
9468 }
9469 if (maxchar_new > maxchar_old) {
9470 /* If the maxchar increased so that the kind changed, not all
9471 characters are representable anymore and we need to fix the
9472 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009473 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009474 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9476 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009477 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009478 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009479 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009480
9481 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009482 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 return v;
9484 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009485}
9486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009487static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009488fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 /* No need to call PyUnicode_READY(self) because this function is only
9491 called as a callback from fixup() which does it already. */
9492 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9493 const int kind = PyUnicode_KIND(self);
9494 void *data = PyUnicode_DATA(self);
9495 int touched = 0;
9496 Py_UCS4 maxchar = 0;
9497 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009498
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009499 for (i = 0; i < len; ++i) {
9500 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9501 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9502 if (up != ch) {
9503 if (up > maxchar)
9504 maxchar = up;
9505 PyUnicode_WRITE(kind, data, i, up);
9506 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009507 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009508 else if (ch > maxchar)
9509 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510 }
9511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009512 if (touched)
9513 return maxchar;
9514 else
9515 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009516}
9517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009519fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009520{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009521 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9522 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9523 const int kind = PyUnicode_KIND(self);
9524 void *data = PyUnicode_DATA(self);
9525 int touched = 0;
9526 Py_UCS4 maxchar = 0;
9527 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009528
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009529 for(i = 0; i < len; ++i) {
9530 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9531 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9532 if (lo != ch) {
9533 if (lo > maxchar)
9534 maxchar = lo;
9535 PyUnicode_WRITE(kind, data, i, lo);
9536 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009538 else if (ch > maxchar)
9539 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540 }
9541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542 if (touched)
9543 return maxchar;
9544 else
9545 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009546}
9547
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009548static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009549fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009550{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009551 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9552 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9553 const int kind = PyUnicode_KIND(self);
9554 void *data = PyUnicode_DATA(self);
9555 int touched = 0;
9556 Py_UCS4 maxchar = 0;
9557 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 for(i = 0; i < len; ++i) {
9560 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9561 Py_UCS4 nu = 0;
9562
9563 if (Py_UNICODE_ISUPPER(ch))
9564 nu = Py_UNICODE_TOLOWER(ch);
9565 else if (Py_UNICODE_ISLOWER(ch))
9566 nu = Py_UNICODE_TOUPPER(ch);
9567
9568 if (nu != 0) {
9569 if (nu > maxchar)
9570 maxchar = nu;
9571 PyUnicode_WRITE(kind, data, i, nu);
9572 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009573 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009574 else if (ch > maxchar)
9575 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576 }
9577
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009578 if (touched)
9579 return maxchar;
9580 else
9581 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009582}
9583
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009584static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009585fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009586{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009587 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9588 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9589 const int kind = PyUnicode_KIND(self);
9590 void *data = PyUnicode_DATA(self);
9591 int touched = 0;
9592 Py_UCS4 maxchar = 0;
9593 Py_ssize_t i = 0;
9594 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009595
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009596 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009597 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598
9599 ch = PyUnicode_READ(kind, data, i);
9600 if (!Py_UNICODE_ISUPPER(ch)) {
9601 maxchar = Py_UNICODE_TOUPPER(ch);
9602 PyUnicode_WRITE(kind, data, i, maxchar);
9603 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009605 ++i;
9606 for(; i < len; ++i) {
9607 ch = PyUnicode_READ(kind, data, i);
9608 if (!Py_UNICODE_ISLOWER(ch)) {
9609 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9610 if (lo > maxchar)
9611 maxchar = lo;
9612 PyUnicode_WRITE(kind, data, i, lo);
9613 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009614 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009615 else if (ch > maxchar)
9616 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009618
9619 if (touched)
9620 return maxchar;
9621 else
9622 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009623}
9624
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009625static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009626fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009627{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009628 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9629 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9630 const int kind = PyUnicode_KIND(self);
9631 void *data = PyUnicode_DATA(self);
9632 Py_UCS4 maxchar = 0;
9633 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009634 int previous_is_cased;
9635
9636 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009637 if (len == 1) {
9638 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9639 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9640 if (ti != ch) {
9641 PyUnicode_WRITE(kind, data, i, ti);
9642 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009643 }
9644 else
9645 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009646 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009647 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009648 for(; i < len; ++i) {
9649 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9650 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009651
Benjamin Peterson29060642009-01-31 22:14:21 +00009652 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009654 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009655 nu = Py_UNICODE_TOTITLE(ch);
9656
9657 if (nu > maxchar)
9658 maxchar = nu;
9659 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009660
Benjamin Peterson29060642009-01-31 22:14:21 +00009661 if (Py_UNICODE_ISLOWER(ch) ||
9662 Py_UNICODE_ISUPPER(ch) ||
9663 Py_UNICODE_ISTITLE(ch))
9664 previous_is_cased = 1;
9665 else
9666 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009667 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009669}
9670
Tim Peters8ce9f162004-08-27 01:49:32 +00009671PyObject *
9672PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009673{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009674 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009675 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009676 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009677 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009678 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9679 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009680 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009681 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009682 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009683 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009684 int use_memcpy;
9685 unsigned char *res_data = NULL, *sep_data = NULL;
9686 PyObject *last_obj;
9687 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009688
Tim Peters05eba1f2004-08-27 21:32:02 +00009689 fseq = PySequence_Fast(seq, "");
9690 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009691 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009692 }
9693
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009694 /* NOTE: the following code can't call back into Python code,
9695 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009696 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009697
Tim Peters05eba1f2004-08-27 21:32:02 +00009698 seqlen = PySequence_Fast_GET_SIZE(fseq);
9699 /* If empty sequence, return u"". */
9700 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009701 Py_DECREF(fseq);
9702 Py_INCREF(unicode_empty);
9703 res = unicode_empty;
9704 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009705 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009706
Tim Peters05eba1f2004-08-27 21:32:02 +00009707 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009708 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009709 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009710 if (seqlen == 1) {
9711 if (PyUnicode_CheckExact(items[0])) {
9712 res = items[0];
9713 Py_INCREF(res);
9714 Py_DECREF(fseq);
9715 return res;
9716 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009717 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009718 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009719 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009720 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009721 /* Set up sep and seplen */
9722 if (separator == NULL) {
9723 /* fall back to a blank space separator */
9724 sep = PyUnicode_FromOrdinal(' ');
9725 if (!sep)
9726 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009728 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009729 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009730 else {
9731 if (!PyUnicode_Check(separator)) {
9732 PyErr_Format(PyExc_TypeError,
9733 "separator: expected str instance,"
9734 " %.80s found",
9735 Py_TYPE(separator)->tp_name);
9736 goto onError;
9737 }
9738 if (PyUnicode_READY(separator))
9739 goto onError;
9740 sep = separator;
9741 seplen = PyUnicode_GET_LENGTH(separator);
9742 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9743 /* inc refcount to keep this code path symmetric with the
9744 above case of a blank separator */
9745 Py_INCREF(sep);
9746 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009747 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009748 }
9749
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009750 /* There are at least two things to join, or else we have a subclass
9751 * of str in the sequence.
9752 * Do a pre-pass to figure out the total amount of space we'll
9753 * need (sz), and see whether all argument are strings.
9754 */
9755 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009756#ifdef Py_DEBUG
9757 use_memcpy = 0;
9758#else
9759 use_memcpy = 1;
9760#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009761 for (i = 0; i < seqlen; i++) {
9762 const Py_ssize_t old_sz = sz;
9763 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009764 if (!PyUnicode_Check(item)) {
9765 PyErr_Format(PyExc_TypeError,
9766 "sequence item %zd: expected str instance,"
9767 " %.80s found",
9768 i, Py_TYPE(item)->tp_name);
9769 goto onError;
9770 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009771 if (PyUnicode_READY(item) == -1)
9772 goto onError;
9773 sz += PyUnicode_GET_LENGTH(item);
9774 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009775 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009776 if (i != 0)
9777 sz += seplen;
9778 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9779 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009780 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009781 goto onError;
9782 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009783 if (use_memcpy && last_obj != NULL) {
9784 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9785 use_memcpy = 0;
9786 }
9787 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009788 }
Tim Petersced69f82003-09-16 20:30:58 +00009789
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009791 if (res == NULL)
9792 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009793
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009794 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009795#ifdef Py_DEBUG
9796 use_memcpy = 0;
9797#else
9798 if (use_memcpy) {
9799 res_data = PyUnicode_1BYTE_DATA(res);
9800 kind = PyUnicode_KIND(res);
9801 if (seplen != 0)
9802 sep_data = PyUnicode_1BYTE_DATA(sep);
9803 }
9804#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009805 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009806 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009807 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009808 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009809 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009810 if (use_memcpy) {
9811 Py_MEMCPY(res_data,
9812 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009813 kind * seplen);
9814 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009815 }
9816 else {
9817 copy_characters(res, res_offset, sep, 0, seplen);
9818 res_offset += seplen;
9819 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009820 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009821 itemlen = PyUnicode_GET_LENGTH(item);
9822 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009823 if (use_memcpy) {
9824 Py_MEMCPY(res_data,
9825 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009826 kind * itemlen);
9827 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009828 }
9829 else {
9830 copy_characters(res, res_offset, item, 0, itemlen);
9831 res_offset += itemlen;
9832 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009833 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009834 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009835 if (use_memcpy)
9836 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009837 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009838 else
9839 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009840
Tim Peters05eba1f2004-08-27 21:32:02 +00009841 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009842 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009843 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009845
Benjamin Peterson29060642009-01-31 22:14:21 +00009846 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009847 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009848 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009849 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009850 return NULL;
9851}
9852
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853#define FILL(kind, data, value, start, length) \
9854 do { \
9855 Py_ssize_t i_ = 0; \
9856 assert(kind != PyUnicode_WCHAR_KIND); \
9857 switch ((kind)) { \
9858 case PyUnicode_1BYTE_KIND: { \
9859 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9860 memset(to_, (unsigned char)value, length); \
9861 break; \
9862 } \
9863 case PyUnicode_2BYTE_KIND: { \
9864 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9865 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9866 break; \
9867 } \
9868 default: { \
9869 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9870 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9871 break; \
9872 } \
9873 } \
9874 } while (0)
9875
Victor Stinner9310abb2011-10-05 00:59:23 +02009876static PyObject *
9877pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009878 Py_ssize_t left,
9879 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009880 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009881{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009882 PyObject *u;
9883 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009884 int kind;
9885 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886
9887 if (left < 0)
9888 left = 0;
9889 if (right < 0)
9890 right = 0;
9891
Tim Peters7a29bd52001-09-12 03:03:31 +00009892 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009893 Py_INCREF(self);
9894 return self;
9895 }
9896
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009897 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9898 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009899 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9900 return NULL;
9901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009902 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9903 if (fill > maxchar)
9904 maxchar = fill;
9905 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009906 if (!u)
9907 return NULL;
9908
9909 kind = PyUnicode_KIND(u);
9910 data = PyUnicode_DATA(u);
9911 if (left)
9912 FILL(kind, data, fill, 0, left);
9913 if (right)
9914 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009915 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009916 assert(_PyUnicode_CheckConsistency(u, 1));
9917 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009918}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009920
Alexander Belopolsky40018472011-02-26 01:02:56 +00009921PyObject *
9922PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009923{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009924 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009925
9926 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009927 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009928 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 switch(PyUnicode_KIND(string)) {
9931 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009932 if (PyUnicode_IS_ASCII(string))
9933 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009934 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009935 PyUnicode_GET_LENGTH(string), keepends);
9936 else
9937 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009938 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009939 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009940 break;
9941 case PyUnicode_2BYTE_KIND:
9942 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009943 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009944 PyUnicode_GET_LENGTH(string), keepends);
9945 break;
9946 case PyUnicode_4BYTE_KIND:
9947 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009948 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 PyUnicode_GET_LENGTH(string), keepends);
9950 break;
9951 default:
9952 assert(0);
9953 list = 0;
9954 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009955 Py_DECREF(string);
9956 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009957}
9958
Alexander Belopolsky40018472011-02-26 01:02:56 +00009959static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009960split(PyObject *self,
9961 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009962 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009963{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009964 int kind1, kind2, kind;
9965 void *buf1, *buf2;
9966 Py_ssize_t len1, len2;
9967 PyObject* out;
9968
Guido van Rossumd57fd912000-03-10 22:53:23 +00009969 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009970 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009971
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 if (PyUnicode_READY(self) == -1)
9973 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009975 if (substring == NULL)
9976 switch(PyUnicode_KIND(self)) {
9977 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009978 if (PyUnicode_IS_ASCII(self))
9979 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009980 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009981 PyUnicode_GET_LENGTH(self), maxcount
9982 );
9983 else
9984 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009985 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009986 PyUnicode_GET_LENGTH(self), maxcount
9987 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009988 case PyUnicode_2BYTE_KIND:
9989 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009990 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 PyUnicode_GET_LENGTH(self), maxcount
9992 );
9993 case PyUnicode_4BYTE_KIND:
9994 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009995 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009996 PyUnicode_GET_LENGTH(self), maxcount
9997 );
9998 default:
9999 assert(0);
10000 return NULL;
10001 }
10002
10003 if (PyUnicode_READY(substring) == -1)
10004 return NULL;
10005
10006 kind1 = PyUnicode_KIND(self);
10007 kind2 = PyUnicode_KIND(substring);
10008 kind = kind1 > kind2 ? kind1 : kind2;
10009 buf1 = PyUnicode_DATA(self);
10010 buf2 = PyUnicode_DATA(substring);
10011 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010012 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010013 if (!buf1)
10014 return NULL;
10015 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010016 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010017 if (!buf2) {
10018 if (kind1 != kind) PyMem_Free(buf1);
10019 return NULL;
10020 }
10021 len1 = PyUnicode_GET_LENGTH(self);
10022 len2 = PyUnicode_GET_LENGTH(substring);
10023
10024 switch(kind) {
10025 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10027 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010028 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010029 else
10030 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010031 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010032 break;
10033 case PyUnicode_2BYTE_KIND:
10034 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010035 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010036 break;
10037 case PyUnicode_4BYTE_KIND:
10038 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010039 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010040 break;
10041 default:
10042 out = NULL;
10043 }
10044 if (kind1 != kind)
10045 PyMem_Free(buf1);
10046 if (kind2 != kind)
10047 PyMem_Free(buf2);
10048 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010049}
10050
Alexander Belopolsky40018472011-02-26 01:02:56 +000010051static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010052rsplit(PyObject *self,
10053 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +000010054 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010055{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010056 int kind1, kind2, kind;
10057 void *buf1, *buf2;
10058 Py_ssize_t len1, len2;
10059 PyObject* out;
10060
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010061 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010062 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010063
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 if (PyUnicode_READY(self) == -1)
10065 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010066
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 if (substring == NULL)
10068 switch(PyUnicode_KIND(self)) {
10069 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010070 if (PyUnicode_IS_ASCII(self))
10071 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010072 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010073 PyUnicode_GET_LENGTH(self), maxcount
10074 );
10075 else
10076 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010077 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +020010078 PyUnicode_GET_LENGTH(self), maxcount
10079 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 case PyUnicode_2BYTE_KIND:
10081 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010082 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 PyUnicode_GET_LENGTH(self), maxcount
10084 );
10085 case PyUnicode_4BYTE_KIND:
10086 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010087 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010088 PyUnicode_GET_LENGTH(self), maxcount
10089 );
10090 default:
10091 assert(0);
10092 return NULL;
10093 }
10094
10095 if (PyUnicode_READY(substring) == -1)
10096 return NULL;
10097
10098 kind1 = PyUnicode_KIND(self);
10099 kind2 = PyUnicode_KIND(substring);
10100 kind = kind1 > kind2 ? kind1 : kind2;
10101 buf1 = PyUnicode_DATA(self);
10102 buf2 = PyUnicode_DATA(substring);
10103 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010104 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 if (!buf1)
10106 return NULL;
10107 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010108 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 if (!buf2) {
10110 if (kind1 != kind) PyMem_Free(buf1);
10111 return NULL;
10112 }
10113 len1 = PyUnicode_GET_LENGTH(self);
10114 len2 = PyUnicode_GET_LENGTH(substring);
10115
10116 switch(kind) {
10117 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010118 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10119 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010120 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010121 else
10122 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010123 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010124 break;
10125 case PyUnicode_2BYTE_KIND:
10126 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010127 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 break;
10129 case PyUnicode_4BYTE_KIND:
10130 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010131 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 break;
10133 default:
10134 out = NULL;
10135 }
10136 if (kind1 != kind)
10137 PyMem_Free(buf1);
10138 if (kind2 != kind)
10139 PyMem_Free(buf2);
10140 return out;
10141}
10142
10143static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010144anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10145 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010146{
10147 switch(kind) {
10148 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010149 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10150 return asciilib_find(buf1, len1, buf2, len2, offset);
10151 else
10152 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 case PyUnicode_2BYTE_KIND:
10154 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10155 case PyUnicode_4BYTE_KIND:
10156 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10157 }
10158 assert(0);
10159 return -1;
10160}
10161
10162static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010163anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10164 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010165{
10166 switch(kind) {
10167 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010168 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10169 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10170 else
10171 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 case PyUnicode_2BYTE_KIND:
10173 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10174 case PyUnicode_4BYTE_KIND:
10175 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10176 }
10177 assert(0);
10178 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010179}
10180
Alexander Belopolsky40018472011-02-26 01:02:56 +000010181static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182replace(PyObject *self, PyObject *str1,
10183 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010184{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 PyObject *u;
10186 char *sbuf = PyUnicode_DATA(self);
10187 char *buf1 = PyUnicode_DATA(str1);
10188 char *buf2 = PyUnicode_DATA(str2);
10189 int srelease = 0, release1 = 0, release2 = 0;
10190 int skind = PyUnicode_KIND(self);
10191 int kind1 = PyUnicode_KIND(str1);
10192 int kind2 = PyUnicode_KIND(str2);
10193 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10194 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10195 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010196 int mayshrink;
10197 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010198
10199 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010200 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010202 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010203
Victor Stinner59de0ee2011-10-07 10:01:28 +020010204 if (str1 == str2)
10205 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 if (skind < kind1)
10207 /* substring too wide to be present */
10208 goto nothing;
10209
Victor Stinner49a0a212011-10-12 23:46:10 +020010210 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10211 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10212 /* Replacing str1 with str2 may cause a maxchar reduction in the
10213 result string. */
10214 mayshrink = (maxchar_str2 < maxchar);
10215 maxchar = Py_MAX(maxchar, maxchar_str2);
10216
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010218 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010219 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010220 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010221 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010223 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010224 Py_UCS4 u1, u2;
10225 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010226 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010227 if (findchar(sbuf, PyUnicode_KIND(self),
10228 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010232 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010234 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 rkind = PyUnicode_KIND(u);
10236 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10237 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010238 if (--maxcount < 0)
10239 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010241 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010242 }
10243 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010244 int rkind = skind;
10245 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010246
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 if (kind1 < rkind) {
10248 /* widen substring */
10249 buf1 = _PyUnicode_AsKind(str1, rkind);
10250 if (!buf1) goto error;
10251 release1 = 1;
10252 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010253 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010254 if (i < 0)
10255 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 if (rkind > kind2) {
10257 /* widen replacement */
10258 buf2 = _PyUnicode_AsKind(str2, rkind);
10259 if (!buf2) goto error;
10260 release2 = 1;
10261 }
10262 else if (rkind < kind2) {
10263 /* widen self and buf1 */
10264 rkind = kind2;
10265 if (release1) PyMem_Free(buf1);
10266 sbuf = _PyUnicode_AsKind(self, rkind);
10267 if (!sbuf) goto error;
10268 srelease = 1;
10269 buf1 = _PyUnicode_AsKind(str1, rkind);
10270 if (!buf1) goto error;
10271 release1 = 1;
10272 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010273 u = PyUnicode_New(slen, maxchar);
10274 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010275 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010276 assert(PyUnicode_KIND(u) == rkind);
10277 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010278
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010279 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010280 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010281 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010282 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010283 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010285
10286 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010287 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010288 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010289 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010290 if (i == -1)
10291 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010292 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010294 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010296 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010297 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010298 }
10299 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010300 Py_ssize_t n, i, j, ires;
10301 Py_ssize_t product, new_size;
10302 int rkind = skind;
10303 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010304
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010305 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010306 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 buf1 = _PyUnicode_AsKind(str1, rkind);
10308 if (!buf1) goto error;
10309 release1 = 1;
10310 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010311 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010312 if (n == 0)
10313 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010315 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010316 buf2 = _PyUnicode_AsKind(str2, rkind);
10317 if (!buf2) goto error;
10318 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010319 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010320 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010321 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010322 rkind = kind2;
10323 sbuf = _PyUnicode_AsKind(self, rkind);
10324 if (!sbuf) goto error;
10325 srelease = 1;
10326 if (release1) PyMem_Free(buf1);
10327 buf1 = _PyUnicode_AsKind(str1, rkind);
10328 if (!buf1) goto error;
10329 release1 = 1;
10330 }
10331 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10332 PyUnicode_GET_LENGTH(str1))); */
10333 product = n * (len2-len1);
10334 if ((product / (len2-len1)) != n) {
10335 PyErr_SetString(PyExc_OverflowError,
10336 "replace string is too long");
10337 goto error;
10338 }
10339 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010340 if (new_size == 0) {
10341 Py_INCREF(unicode_empty);
10342 u = unicode_empty;
10343 goto done;
10344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010345 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10346 PyErr_SetString(PyExc_OverflowError,
10347 "replace string is too long");
10348 goto error;
10349 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010350 u = PyUnicode_New(new_size, maxchar);
10351 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010353 assert(PyUnicode_KIND(u) == rkind);
10354 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010355 ires = i = 0;
10356 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010357 while (n-- > 0) {
10358 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010359 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010360 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010361 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010362 if (j == -1)
10363 break;
10364 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010365 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010366 memcpy(res + rkind * ires,
10367 sbuf + rkind * i,
10368 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010369 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010370 }
10371 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010372 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010373 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010374 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010375 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010376 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010377 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010379 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010380 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010381 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010382 memcpy(res + rkind * ires,
10383 sbuf + rkind * i,
10384 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010385 }
10386 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010387 /* interleave */
10388 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010389 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010390 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010391 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010392 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010393 if (--n <= 0)
10394 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010395 memcpy(res + rkind * ires,
10396 sbuf + rkind * i,
10397 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010398 ires++;
10399 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010400 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010401 memcpy(res + rkind * ires,
10402 sbuf + rkind * i,
10403 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010404 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010405 }
10406
10407 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010408 unicode_adjust_maxchar(&u);
10409 if (u == NULL)
10410 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010411 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010412
10413 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010414 if (srelease)
10415 PyMem_FREE(sbuf);
10416 if (release1)
10417 PyMem_FREE(buf1);
10418 if (release2)
10419 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010420 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010421 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010422
Benjamin Peterson29060642009-01-31 22:14:21 +000010423 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010424 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010425 if (srelease)
10426 PyMem_FREE(sbuf);
10427 if (release1)
10428 PyMem_FREE(buf1);
10429 if (release2)
10430 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010431 if (PyUnicode_CheckExact(self)) {
10432 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010433 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010434 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010435 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010436 error:
10437 if (srelease && sbuf)
10438 PyMem_FREE(sbuf);
10439 if (release1 && buf1)
10440 PyMem_FREE(buf1);
10441 if (release2 && buf2)
10442 PyMem_FREE(buf2);
10443 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010444}
10445
10446/* --- Unicode Object Methods --------------------------------------------- */
10447
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010448PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010449 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010450\n\
10451Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010452characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010453
10454static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010455unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010456{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010457 return fixup(self, fixtitle);
10458}
10459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010460PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010461 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010462\n\
10463Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010464have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010465
10466static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010467unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010468{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469 return fixup(self, fixcapitalize);
10470}
10471
10472#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010473PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010474 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010475\n\
10476Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010477normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010478
10479static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010480unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010481{
10482 PyObject *list;
10483 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010484 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010485
Guido van Rossumd57fd912000-03-10 22:53:23 +000010486 /* Split into words */
10487 list = split(self, NULL, -1);
10488 if (!list)
10489 return NULL;
10490
10491 /* Capitalize each word */
10492 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010493 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010494 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010495 if (item == NULL)
10496 goto onError;
10497 Py_DECREF(PyList_GET_ITEM(list, i));
10498 PyList_SET_ITEM(list, i, item);
10499 }
10500
10501 /* Join the words to form a new string */
10502 item = PyUnicode_Join(NULL, list);
10503
Benjamin Peterson29060642009-01-31 22:14:21 +000010504 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010505 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010506 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010507}
10508#endif
10509
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010510/* Argument converter. Coerces to a single unicode character */
10511
10512static int
10513convert_uc(PyObject *obj, void *addr)
10514{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010515 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010516 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010517
Benjamin Peterson14339b62009-01-31 16:36:08 +000010518 uniobj = PyUnicode_FromObject(obj);
10519 if (uniobj == NULL) {
10520 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010521 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010522 return 0;
10523 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010525 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010526 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010527 Py_DECREF(uniobj);
10528 return 0;
10529 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010531 Py_DECREF(uniobj);
10532 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010533}
10534
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010535PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010536 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010537\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010538Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010539done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010540
10541static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010542unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010543{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010544 Py_ssize_t marg, left;
10545 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 Py_UCS4 fillchar = ' ';
10547
Victor Stinnere9a29352011-10-01 02:14:59 +020010548 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010549 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010550
Victor Stinnere9a29352011-10-01 02:14:59 +020010551 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010552 return NULL;
10553
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010554 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010555 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010556 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010557 }
10558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010560 left = marg / 2 + (marg & width & 1);
10561
Victor Stinner9310abb2011-10-05 00:59:23 +020010562 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010563}
10564
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010565/* This function assumes that str1 and str2 are readied by the caller. */
10566
Marc-André Lemburge5034372000-08-08 08:04:29 +000010567static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010568unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010570 int kind1, kind2;
10571 void *data1, *data2;
10572 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010574 kind1 = PyUnicode_KIND(str1);
10575 kind2 = PyUnicode_KIND(str2);
10576 data1 = PyUnicode_DATA(str1);
10577 data2 = PyUnicode_DATA(str2);
10578 len1 = PyUnicode_GET_LENGTH(str1);
10579 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010580
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010581 for (i = 0; i < len1 && i < len2; ++i) {
10582 Py_UCS4 c1, c2;
10583 c1 = PyUnicode_READ(kind1, data1, i);
10584 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010585
10586 if (c1 != c2)
10587 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010588 }
10589
10590 return (len1 < len2) ? -1 : (len1 != len2);
10591}
10592
Alexander Belopolsky40018472011-02-26 01:02:56 +000010593int
10594PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010595{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010596 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10597 if (PyUnicode_READY(left) == -1 ||
10598 PyUnicode_READY(right) == -1)
10599 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010600 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010602 PyErr_Format(PyExc_TypeError,
10603 "Can't compare %.100s and %.100s",
10604 left->ob_type->tp_name,
10605 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606 return -1;
10607}
10608
Martin v. Löwis5b222132007-06-10 09:51:05 +000010609int
10610PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10611{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010612 Py_ssize_t i;
10613 int kind;
10614 void *data;
10615 Py_UCS4 chr;
10616
Victor Stinner910337b2011-10-03 03:20:16 +020010617 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 if (PyUnicode_READY(uni) == -1)
10619 return -1;
10620 kind = PyUnicode_KIND(uni);
10621 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010622 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10624 if (chr != str[i])
10625 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010626 /* This check keeps Python strings that end in '\0' from comparing equal
10627 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010628 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010629 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010630 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010631 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010632 return 0;
10633}
10634
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010635
Benjamin Peterson29060642009-01-31 22:14:21 +000010636#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010637 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010638
Alexander Belopolsky40018472011-02-26 01:02:56 +000010639PyObject *
10640PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010641{
10642 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010643
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010644 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10645 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010646 if (PyUnicode_READY(left) == -1 ||
10647 PyUnicode_READY(right) == -1)
10648 return NULL;
10649 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10650 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010651 if (op == Py_EQ) {
10652 Py_INCREF(Py_False);
10653 return Py_False;
10654 }
10655 if (op == Py_NE) {
10656 Py_INCREF(Py_True);
10657 return Py_True;
10658 }
10659 }
10660 if (left == right)
10661 result = 0;
10662 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010663 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010664
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010665 /* Convert the return value to a Boolean */
10666 switch (op) {
10667 case Py_EQ:
10668 v = TEST_COND(result == 0);
10669 break;
10670 case Py_NE:
10671 v = TEST_COND(result != 0);
10672 break;
10673 case Py_LE:
10674 v = TEST_COND(result <= 0);
10675 break;
10676 case Py_GE:
10677 v = TEST_COND(result >= 0);
10678 break;
10679 case Py_LT:
10680 v = TEST_COND(result == -1);
10681 break;
10682 case Py_GT:
10683 v = TEST_COND(result == 1);
10684 break;
10685 default:
10686 PyErr_BadArgument();
10687 return NULL;
10688 }
10689 Py_INCREF(v);
10690 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010691 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010692
Brian Curtindfc80e32011-08-10 20:28:54 -050010693 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010694}
10695
Alexander Belopolsky40018472011-02-26 01:02:56 +000010696int
10697PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010698{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010699 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 int kind1, kind2, kind;
10701 void *buf1, *buf2;
10702 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010703 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010704
10705 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010706 sub = PyUnicode_FromObject(element);
10707 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010708 PyErr_Format(PyExc_TypeError,
10709 "'in <string>' requires string as left operand, not %s",
10710 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010711 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010712 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010713 if (PyUnicode_READY(sub) == -1)
10714 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010715
Thomas Wouters477c8d52006-05-27 19:21:47 +000010716 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010717 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010718 Py_DECREF(sub);
10719 return -1;
10720 }
10721
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010722 kind1 = PyUnicode_KIND(str);
10723 kind2 = PyUnicode_KIND(sub);
10724 kind = kind1 > kind2 ? kind1 : kind2;
10725 buf1 = PyUnicode_DATA(str);
10726 buf2 = PyUnicode_DATA(sub);
10727 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010728 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010729 if (!buf1) {
10730 Py_DECREF(sub);
10731 return -1;
10732 }
10733 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010734 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010735 if (!buf2) {
10736 Py_DECREF(sub);
10737 if (kind1 != kind) PyMem_Free(buf1);
10738 return -1;
10739 }
10740 len1 = PyUnicode_GET_LENGTH(str);
10741 len2 = PyUnicode_GET_LENGTH(sub);
10742
10743 switch(kind) {
10744 case PyUnicode_1BYTE_KIND:
10745 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10746 break;
10747 case PyUnicode_2BYTE_KIND:
10748 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10749 break;
10750 case PyUnicode_4BYTE_KIND:
10751 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10752 break;
10753 default:
10754 result = -1;
10755 assert(0);
10756 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010757
10758 Py_DECREF(str);
10759 Py_DECREF(sub);
10760
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010761 if (kind1 != kind)
10762 PyMem_Free(buf1);
10763 if (kind2 != kind)
10764 PyMem_Free(buf2);
10765
Guido van Rossum403d68b2000-03-13 15:55:09 +000010766 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010767}
10768
Guido van Rossumd57fd912000-03-10 22:53:23 +000010769/* Concat to string or Unicode object giving a new Unicode object. */
10770
Alexander Belopolsky40018472011-02-26 01:02:56 +000010771PyObject *
10772PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010773{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010774 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010775 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010776
10777 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010778 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010779 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010780 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010781 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010783 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010784
10785 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010786 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010787 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010788 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010790 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010791 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010792 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010793 }
10794
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010795 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010796 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10797 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010798
Guido van Rossumd57fd912000-03-10 22:53:23 +000010799 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010800 w = PyUnicode_New(
10801 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10802 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010803 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010804 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010805 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10806 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807 Py_DECREF(u);
10808 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010809 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010810 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
Benjamin Peterson29060642009-01-31 22:14:21 +000010812 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010813 Py_XDECREF(u);
10814 Py_XDECREF(v);
10815 return NULL;
10816}
10817
Victor Stinnerb0923652011-10-04 01:17:31 +020010818static void
10819unicode_append_inplace(PyObject **p_left, PyObject *right)
10820{
10821 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010822
10823 assert(PyUnicode_IS_READY(*p_left));
10824 assert(PyUnicode_IS_READY(right));
10825
10826 left_len = PyUnicode_GET_LENGTH(*p_left);
10827 right_len = PyUnicode_GET_LENGTH(right);
10828 if (left_len > PY_SSIZE_T_MAX - right_len) {
10829 PyErr_SetString(PyExc_OverflowError,
10830 "strings are too large to concat");
10831 goto error;
10832 }
10833 new_len = left_len + right_len;
10834
10835 /* Now we own the last reference to 'left', so we can resize it
10836 * in-place.
10837 */
10838 if (unicode_resize(p_left, new_len) != 0) {
10839 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10840 * deallocated so it cannot be put back into
10841 * 'variable'. The MemoryError is raised when there
10842 * is no value in 'variable', which might (very
10843 * remotely) be a cause of incompatibilities.
10844 */
10845 goto error;
10846 }
10847 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010848 copy_characters(*p_left, left_len, right, 0, right_len);
10849 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010850 return;
10851
10852error:
10853 Py_DECREF(*p_left);
10854 *p_left = NULL;
10855}
10856
Walter Dörwald1ab83302007-05-18 17:15:44 +000010857void
Victor Stinner23e56682011-10-03 03:54:37 +020010858PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010859{
Victor Stinner23e56682011-10-03 03:54:37 +020010860 PyObject *left, *res;
10861
10862 if (p_left == NULL) {
10863 if (!PyErr_Occurred())
10864 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010865 return;
10866 }
Victor Stinner23e56682011-10-03 03:54:37 +020010867 left = *p_left;
10868 if (right == NULL || !PyUnicode_Check(left)) {
10869 if (!PyErr_Occurred())
10870 PyErr_BadInternalCall();
10871 goto error;
10872 }
10873
Victor Stinnere1335c72011-10-04 20:53:03 +020010874 if (PyUnicode_READY(left))
10875 goto error;
10876 if (PyUnicode_READY(right))
10877 goto error;
10878
Victor Stinner23e56682011-10-03 03:54:37 +020010879 if (PyUnicode_CheckExact(left) && left != unicode_empty
10880 && PyUnicode_CheckExact(right) && right != unicode_empty
10881 && unicode_resizable(left)
10882 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10883 || _PyUnicode_WSTR(left) != NULL))
10884 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010885 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10886 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010887 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010888 not so different than duplicating the string. */
10889 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010890 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010891 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010892 if (p_left != NULL)
10893 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010894 return;
10895 }
10896 }
10897
10898 res = PyUnicode_Concat(left, right);
10899 if (res == NULL)
10900 goto error;
10901 Py_DECREF(left);
10902 *p_left = res;
10903 return;
10904
10905error:
10906 Py_DECREF(*p_left);
10907 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010908}
10909
10910void
10911PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10912{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010913 PyUnicode_Append(pleft, right);
10914 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010915}
10916
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010917PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010918 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010919\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010920Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010921string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010922interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923
10924static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010925unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010927 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010928 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010929 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010930 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010931 int kind1, kind2, kind;
10932 void *buf1, *buf2;
10933 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934
Jesus Ceaac451502011-04-20 17:09:23 +020010935 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10936 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010937 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010938
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010939 kind1 = PyUnicode_KIND(self);
10940 kind2 = PyUnicode_KIND(substring);
10941 kind = kind1 > kind2 ? kind1 : kind2;
10942 buf1 = PyUnicode_DATA(self);
10943 buf2 = PyUnicode_DATA(substring);
10944 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010945 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010946 if (!buf1) {
10947 Py_DECREF(substring);
10948 return NULL;
10949 }
10950 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010951 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010952 if (!buf2) {
10953 Py_DECREF(substring);
10954 if (kind1 != kind) PyMem_Free(buf1);
10955 return NULL;
10956 }
10957 len1 = PyUnicode_GET_LENGTH(self);
10958 len2 = PyUnicode_GET_LENGTH(substring);
10959
10960 ADJUST_INDICES(start, end, len1);
10961 switch(kind) {
10962 case PyUnicode_1BYTE_KIND:
10963 iresult = ucs1lib_count(
10964 ((Py_UCS1*)buf1) + start, end - start,
10965 buf2, len2, PY_SSIZE_T_MAX
10966 );
10967 break;
10968 case PyUnicode_2BYTE_KIND:
10969 iresult = ucs2lib_count(
10970 ((Py_UCS2*)buf1) + start, end - start,
10971 buf2, len2, PY_SSIZE_T_MAX
10972 );
10973 break;
10974 case PyUnicode_4BYTE_KIND:
10975 iresult = ucs4lib_count(
10976 ((Py_UCS4*)buf1) + start, end - start,
10977 buf2, len2, PY_SSIZE_T_MAX
10978 );
10979 break;
10980 default:
10981 assert(0); iresult = 0;
10982 }
10983
10984 result = PyLong_FromSsize_t(iresult);
10985
10986 if (kind1 != kind)
10987 PyMem_Free(buf1);
10988 if (kind2 != kind)
10989 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010990
10991 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010992
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993 return result;
10994}
10995
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010996PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010997 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010999Encode S using the codec registered for encoding. Default encoding\n\
11000is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000011001handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000011002a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
11003'xmlcharrefreplace' as well as any other name registered with\n\
11004codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011005
11006static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011007unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011008{
Benjamin Peterson308d6372009-09-18 21:42:35 +000011009 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010 char *encoding = NULL;
11011 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000011012
Benjamin Peterson308d6372009-09-18 21:42:35 +000011013 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
11014 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011016 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000011017}
11018
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011019PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011020 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021\n\
11022Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011023If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024
11025static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011026unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011027{
Antoine Pitroue71d5742011-10-04 15:55:09 +020011028 Py_ssize_t i, j, line_pos, src_len, incr;
11029 Py_UCS4 ch;
11030 PyObject *u;
11031 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011033 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011034 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011035
11036 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038
Antoine Pitrou22425222011-10-04 19:10:51 +020011039 if (PyUnicode_READY(self) == -1)
11040 return NULL;
11041
Thomas Wouters7e474022000-07-16 12:04:32 +000011042 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011043 src_len = PyUnicode_GET_LENGTH(self);
11044 i = j = line_pos = 0;
11045 kind = PyUnicode_KIND(self);
11046 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020011047 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011048 for (; i < src_len; i++) {
11049 ch = PyUnicode_READ(kind, src_data, i);
11050 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020011051 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000011052 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011053 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000011054 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011055 goto overflow;
11056 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000011057 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011058 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011059 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000011061 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020011062 goto overflow;
11063 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011065 if (ch == '\n' || ch == '\r')
11066 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011067 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011068 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020011069 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010011070 Py_INCREF(self);
11071 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020011072 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000011073
Guido van Rossumd57fd912000-03-10 22:53:23 +000011074 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020011075 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076 if (!u)
11077 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011078 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011079
Antoine Pitroue71d5742011-10-04 15:55:09 +020011080 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081
Antoine Pitroue71d5742011-10-04 15:55:09 +020011082 for (; i < src_len; i++) {
11083 ch = PyUnicode_READ(kind, src_data, i);
11084 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011085 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011086 incr = tabsize - (line_pos % tabsize);
11087 line_pos += incr;
11088 while (incr--) {
11089 PyUnicode_WRITE(kind, dest_data, j, ' ');
11090 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011091 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011092 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011093 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011094 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011095 line_pos++;
11096 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011097 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011098 if (ch == '\n' || ch == '\r')
11099 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011100 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011101 }
11102 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011103#ifndef DONT_MAKE_RESULT_READY
11104 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105 Py_DECREF(u);
11106 return NULL;
11107 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011108#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011109 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010011110 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011111
Antoine Pitroue71d5742011-10-04 15:55:09 +020011112 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011113 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11114 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115}
11116
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011117PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011118 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011119\n\
11120Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011121such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122arguments start and end are interpreted as in slice notation.\n\
11123\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011124Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011125
11126static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011129 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011130 Py_ssize_t start;
11131 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011132 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011133
Jesus Ceaac451502011-04-20 17:09:23 +020011134 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11135 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011137
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138 if (PyUnicode_READY(self) == -1)
11139 return NULL;
11140 if (PyUnicode_READY(substring) == -1)
11141 return NULL;
11142
Victor Stinner7931d9a2011-11-04 00:22:48 +010011143 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
11145 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (result == -2)
11148 return NULL;
11149
Christian Heimes217cfd12007-12-02 14:31:20 +000011150 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011151}
11152
11153static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011154unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011156 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11157 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011158 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011159 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160}
11161
Guido van Rossumc2504932007-09-18 19:42:40 +000011162/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011163 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011164static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011165unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011166{
Guido van Rossumc2504932007-09-18 19:42:40 +000011167 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011168 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011170 if (_PyUnicode_HASH(self) != -1)
11171 return _PyUnicode_HASH(self);
11172 if (PyUnicode_READY(self) == -1)
11173 return -1;
11174 len = PyUnicode_GET_LENGTH(self);
11175
11176 /* The hash function as a macro, gets expanded three times below. */
11177#define HASH(P) \
11178 x = (Py_uhash_t)*P << 7; \
11179 while (--len >= 0) \
11180 x = (1000003*x) ^ (Py_uhash_t)*P++;
11181
11182 switch (PyUnicode_KIND(self)) {
11183 case PyUnicode_1BYTE_KIND: {
11184 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11185 HASH(c);
11186 break;
11187 }
11188 case PyUnicode_2BYTE_KIND: {
11189 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11190 HASH(s);
11191 break;
11192 }
11193 default: {
11194 Py_UCS4 *l;
11195 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11196 "Impossible switch case in unicode_hash");
11197 l = PyUnicode_4BYTE_DATA(self);
11198 HASH(l);
11199 break;
11200 }
11201 }
11202 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11203
Guido van Rossumc2504932007-09-18 19:42:40 +000011204 if (x == -1)
11205 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011206 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011207 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011211PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011212 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011213\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011214Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215
11216static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011217unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011219 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011220 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011221 Py_ssize_t start;
11222 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011223
Jesus Ceaac451502011-04-20 17:09:23 +020011224 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11225 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011227
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 if (PyUnicode_READY(self) == -1)
11229 return NULL;
11230 if (PyUnicode_READY(substring) == -1)
11231 return NULL;
11232
Victor Stinner7931d9a2011-11-04 00:22:48 +010011233 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011234
11235 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011237 if (result == -2)
11238 return NULL;
11239
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240 if (result < 0) {
11241 PyErr_SetString(PyExc_ValueError, "substring not found");
11242 return NULL;
11243 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011244
Christian Heimes217cfd12007-12-02 14:31:20 +000011245 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246}
11247
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011248PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011250\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011251Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011252at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011253
11254static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011255unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011256{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011257 Py_ssize_t i, length;
11258 int kind;
11259 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260 int cased;
11261
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011262 if (PyUnicode_READY(self) == -1)
11263 return NULL;
11264 length = PyUnicode_GET_LENGTH(self);
11265 kind = PyUnicode_KIND(self);
11266 data = PyUnicode_DATA(self);
11267
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 if (length == 1)
11270 return PyBool_FromLong(
11271 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011273 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011276
Guido van Rossumd57fd912000-03-10 22:53:23 +000011277 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011278 for (i = 0; i < length; i++) {
11279 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011280
Benjamin Peterson29060642009-01-31 22:14:21 +000011281 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11282 return PyBool_FromLong(0);
11283 else if (!cased && Py_UNICODE_ISLOWER(ch))
11284 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011285 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011286 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287}
11288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011289PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011291\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011292Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011293at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011294
11295static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011296unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011298 Py_ssize_t i, length;
11299 int kind;
11300 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011301 int cased;
11302
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303 if (PyUnicode_READY(self) == -1)
11304 return NULL;
11305 length = PyUnicode_GET_LENGTH(self);
11306 kind = PyUnicode_KIND(self);
11307 data = PyUnicode_DATA(self);
11308
Guido van Rossumd57fd912000-03-10 22:53:23 +000011309 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310 if (length == 1)
11311 return PyBool_FromLong(
11312 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011313
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011314 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011316 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011317
Guido van Rossumd57fd912000-03-10 22:53:23 +000011318 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 for (i = 0; i < length; i++) {
11320 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011321
Benjamin Peterson29060642009-01-31 22:14:21 +000011322 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11323 return PyBool_FromLong(0);
11324 else if (!cased && Py_UNICODE_ISUPPER(ch))
11325 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011326 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011327 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328}
11329
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011330PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011331 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011333Return True if S is a titlecased string and there is at least one\n\
11334character in S, i.e. upper- and titlecase characters may only\n\
11335follow uncased characters and lowercase characters only cased ones.\n\
11336Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337
11338static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011339unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011341 Py_ssize_t i, length;
11342 int kind;
11343 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011344 int cased, previous_is_cased;
11345
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011346 if (PyUnicode_READY(self) == -1)
11347 return NULL;
11348 length = PyUnicode_GET_LENGTH(self);
11349 kind = PyUnicode_KIND(self);
11350 data = PyUnicode_DATA(self);
11351
Guido van Rossumd57fd912000-03-10 22:53:23 +000011352 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011353 if (length == 1) {
11354 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11355 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11356 (Py_UNICODE_ISUPPER(ch) != 0));
11357 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011358
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011359 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011361 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011362
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 cased = 0;
11364 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 for (i = 0; i < length; i++) {
11366 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011367
Benjamin Peterson29060642009-01-31 22:14:21 +000011368 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11369 if (previous_is_cased)
11370 return PyBool_FromLong(0);
11371 previous_is_cased = 1;
11372 cased = 1;
11373 }
11374 else if (Py_UNICODE_ISLOWER(ch)) {
11375 if (!previous_is_cased)
11376 return PyBool_FromLong(0);
11377 previous_is_cased = 1;
11378 cased = 1;
11379 }
11380 else
11381 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011382 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011383 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011384}
11385
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011386PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011387 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011389Return True if all characters in S are whitespace\n\
11390and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391
11392static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011393unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011394{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011395 Py_ssize_t i, length;
11396 int kind;
11397 void *data;
11398
11399 if (PyUnicode_READY(self) == -1)
11400 return NULL;
11401 length = PyUnicode_GET_LENGTH(self);
11402 kind = PyUnicode_KIND(self);
11403 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011406 if (length == 1)
11407 return PyBool_FromLong(
11408 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011409
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011410 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011412 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011413
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011414 for (i = 0; i < length; i++) {
11415 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011416 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011417 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011418 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011419 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420}
11421
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011422PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011423 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011424\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011425Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011426and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011427
11428static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011429unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011430{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 Py_ssize_t i, length;
11432 int kind;
11433 void *data;
11434
11435 if (PyUnicode_READY(self) == -1)
11436 return NULL;
11437 length = PyUnicode_GET_LENGTH(self);
11438 kind = PyUnicode_KIND(self);
11439 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011440
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011441 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011442 if (length == 1)
11443 return PyBool_FromLong(
11444 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011445
11446 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011449
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011450 for (i = 0; i < length; i++) {
11451 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011452 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011453 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011454 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011455}
11456
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011457PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011458 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011459\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011460Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011461and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011462
11463static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011464unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011465{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011466 int kind;
11467 void *data;
11468 Py_ssize_t len, i;
11469
11470 if (PyUnicode_READY(self) == -1)
11471 return NULL;
11472
11473 kind = PyUnicode_KIND(self);
11474 data = PyUnicode_DATA(self);
11475 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011476
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011477 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011478 if (len == 1) {
11479 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11480 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11481 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011482
11483 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011484 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011485 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 for (i = 0; i < len; i++) {
11488 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011489 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011491 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011492 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011493}
11494
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011495PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011496 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011498Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011499False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011500
11501static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011502unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011504 Py_ssize_t i, length;
11505 int kind;
11506 void *data;
11507
11508 if (PyUnicode_READY(self) == -1)
11509 return NULL;
11510 length = PyUnicode_GET_LENGTH(self);
11511 kind = PyUnicode_KIND(self);
11512 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011513
Guido van Rossumd57fd912000-03-10 22:53:23 +000011514 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011515 if (length == 1)
11516 return PyBool_FromLong(
11517 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011518
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011519 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011520 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011521 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011523 for (i = 0; i < length; i++) {
11524 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011525 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011526 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011527 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011528}
11529
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011530PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011531 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011532\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011533Return True if all characters in S are digits\n\
11534and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011535
11536static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011537unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011538{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011539 Py_ssize_t i, length;
11540 int kind;
11541 void *data;
11542
11543 if (PyUnicode_READY(self) == -1)
11544 return NULL;
11545 length = PyUnicode_GET_LENGTH(self);
11546 kind = PyUnicode_KIND(self);
11547 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011548
Guido van Rossumd57fd912000-03-10 22:53:23 +000011549 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011550 if (length == 1) {
11551 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11552 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11553 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011554
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011555 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011559 for (i = 0; i < length; i++) {
11560 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011561 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011563 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011564}
11565
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011566PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011567 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011569Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011570False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011571
11572static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011573unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 Py_ssize_t i, length;
11576 int kind;
11577 void *data;
11578
11579 if (PyUnicode_READY(self) == -1)
11580 return NULL;
11581 length = PyUnicode_GET_LENGTH(self);
11582 kind = PyUnicode_KIND(self);
11583 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011586 if (length == 1)
11587 return PyBool_FromLong(
11588 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011590 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011591 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 for (i = 0; i < length; i++) {
11595 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011596 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011597 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011598 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599}
11600
Martin v. Löwis47383402007-08-15 07:32:56 +000011601int
11602PyUnicode_IsIdentifier(PyObject *self)
11603{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011604 int kind;
11605 void *data;
11606 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011607 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011608
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011609 if (PyUnicode_READY(self) == -1) {
11610 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011611 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011612 }
11613
11614 /* Special case for empty strings */
11615 if (PyUnicode_GET_LENGTH(self) == 0)
11616 return 0;
11617 kind = PyUnicode_KIND(self);
11618 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011619
11620 /* PEP 3131 says that the first character must be in
11621 XID_Start and subsequent characters in XID_Continue,
11622 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011623 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011624 letters, digits, underscore). However, given the current
11625 definition of XID_Start and XID_Continue, it is sufficient
11626 to check just for these, except that _ must be allowed
11627 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011628 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011629 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011630 return 0;
11631
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011632 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011633 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011635 return 1;
11636}
11637
11638PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011639 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011640\n\
11641Return True if S is a valid identifier according\n\
11642to the language definition.");
11643
11644static PyObject*
11645unicode_isidentifier(PyObject *self)
11646{
11647 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11648}
11649
Georg Brandl559e5d72008-06-11 18:37:52 +000011650PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011651 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011652\n\
11653Return True if all characters in S are considered\n\
11654printable in repr() or S is empty, False otherwise.");
11655
11656static PyObject*
11657unicode_isprintable(PyObject *self)
11658{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011659 Py_ssize_t i, length;
11660 int kind;
11661 void *data;
11662
11663 if (PyUnicode_READY(self) == -1)
11664 return NULL;
11665 length = PyUnicode_GET_LENGTH(self);
11666 kind = PyUnicode_KIND(self);
11667 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011668
11669 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 if (length == 1)
11671 return PyBool_FromLong(
11672 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011674 for (i = 0; i < length; i++) {
11675 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011676 Py_RETURN_FALSE;
11677 }
11678 }
11679 Py_RETURN_TRUE;
11680}
11681
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011682PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011683 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011684\n\
11685Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011686iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011687
11688static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011689unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011690{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011691 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011692}
11693
Martin v. Löwis18e16552006-02-15 17:27:45 +000011694static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011695unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011696{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011697 if (PyUnicode_READY(self) == -1)
11698 return -1;
11699 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011700}
11701
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011702PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011703 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011704\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011705Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011706done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011707
11708static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011709unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011710{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011711 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011712 Py_UCS4 fillchar = ' ';
11713
11714 if (PyUnicode_READY(self) == -1)
11715 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011716
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011717 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011718 return NULL;
11719
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011721 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011722 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011723 }
11724
Victor Stinner7931d9a2011-11-04 00:22:48 +010011725 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011726}
11727
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011728PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011729 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011730\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011731Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011732
11733static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011734unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011735{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011736 return fixup(self, fixlower);
11737}
11738
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739#define LEFTSTRIP 0
11740#define RIGHTSTRIP 1
11741#define BOTHSTRIP 2
11742
11743/* Arrays indexed by above */
11744static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11745
11746#define STRIPNAME(i) (stripformat[i]+3)
11747
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011748/* externally visible for str.strip(unicode) */
11749PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011750_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011751{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011752 void *data;
11753 int kind;
11754 Py_ssize_t i, j, len;
11755 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011757 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11758 return NULL;
11759
11760 kind = PyUnicode_KIND(self);
11761 data = PyUnicode_DATA(self);
11762 len = PyUnicode_GET_LENGTH(self);
11763 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11764 PyUnicode_DATA(sepobj),
11765 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011766
Benjamin Peterson14339b62009-01-31 16:36:08 +000011767 i = 0;
11768 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011769 while (i < len &&
11770 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011771 i++;
11772 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011773 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011774
Benjamin Peterson14339b62009-01-31 16:36:08 +000011775 j = len;
11776 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 do {
11778 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011779 } while (j >= i &&
11780 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011781 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011782 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783
Victor Stinner7931d9a2011-11-04 00:22:48 +010011784 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011785}
11786
11787PyObject*
11788PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11789{
11790 unsigned char *data;
11791 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011792 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011793
Victor Stinnerde636f32011-10-01 03:55:54 +020011794 if (PyUnicode_READY(self) == -1)
11795 return NULL;
11796
11797 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11798
Victor Stinner12bab6d2011-10-01 01:53:49 +020011799 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011800 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011801 if (PyUnicode_CheckExact(self)) {
11802 Py_INCREF(self);
11803 return self;
11804 }
11805 else
11806 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011807 }
11808
Victor Stinner12bab6d2011-10-01 01:53:49 +020011809 length = end - start;
11810 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011811 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011812
Victor Stinnerde636f32011-10-01 03:55:54 +020011813 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011814 PyErr_SetString(PyExc_IndexError, "string index out of range");
11815 return NULL;
11816 }
11817
Victor Stinnerb9275c12011-10-05 14:01:42 +020011818 if (PyUnicode_IS_ASCII(self)) {
11819 kind = PyUnicode_KIND(self);
11820 data = PyUnicode_1BYTE_DATA(self);
11821 return unicode_fromascii(data + start, length);
11822 }
11823 else {
11824 kind = PyUnicode_KIND(self);
11825 data = PyUnicode_1BYTE_DATA(self);
11826 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011827 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011828 length);
11829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011830}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831
11832static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011833do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011834{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011835 int kind;
11836 void *data;
11837 Py_ssize_t len, i, j;
11838
11839 if (PyUnicode_READY(self) == -1)
11840 return NULL;
11841
11842 kind = PyUnicode_KIND(self);
11843 data = PyUnicode_DATA(self);
11844 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011845
Benjamin Peterson14339b62009-01-31 16:36:08 +000011846 i = 0;
11847 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011848 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011849 i++;
11850 }
11851 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011852
Benjamin Peterson14339b62009-01-31 16:36:08 +000011853 j = len;
11854 if (striptype != LEFTSTRIP) {
11855 do {
11856 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011858 j++;
11859 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011860
Victor Stinner7931d9a2011-11-04 00:22:48 +010011861 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862}
11863
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011864
11865static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011866do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011867{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011868 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011869
Benjamin Peterson14339b62009-01-31 16:36:08 +000011870 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11871 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011872
Benjamin Peterson14339b62009-01-31 16:36:08 +000011873 if (sep != NULL && sep != Py_None) {
11874 if (PyUnicode_Check(sep))
11875 return _PyUnicode_XStrip(self, striptype, sep);
11876 else {
11877 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011878 "%s arg must be None or str",
11879 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011880 return NULL;
11881 }
11882 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011883
Benjamin Peterson14339b62009-01-31 16:36:08 +000011884 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011885}
11886
11887
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011888PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011889 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011890\n\
11891Return a copy of the string S with leading and trailing\n\
11892whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011893If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011894
11895static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011896unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011897{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011898 if (PyTuple_GET_SIZE(args) == 0)
11899 return do_strip(self, BOTHSTRIP); /* Common case */
11900 else
11901 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011902}
11903
11904
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011905PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011906 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011907\n\
11908Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011909If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011910
11911static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011912unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011913{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011914 if (PyTuple_GET_SIZE(args) == 0)
11915 return do_strip(self, LEFTSTRIP); /* Common case */
11916 else
11917 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011918}
11919
11920
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011921PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011922 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011923\n\
11924Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011925If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011926
11927static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011928unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011929{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011930 if (PyTuple_GET_SIZE(args) == 0)
11931 return do_strip(self, RIGHTSTRIP); /* Common case */
11932 else
11933 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011934}
11935
11936
Guido van Rossumd57fd912000-03-10 22:53:23 +000011937static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011938unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011940 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011942
Georg Brandl222de0f2009-04-12 12:01:50 +000011943 if (len < 1) {
11944 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011945 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011946 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947
Tim Peters7a29bd52001-09-12 03:03:31 +000011948 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011949 /* no repeat, return original string */
11950 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011951 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011952 }
Tim Peters8f422462000-09-09 06:13:41 +000011953
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011954 if (PyUnicode_READY(str) == -1)
11955 return NULL;
11956
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011957 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011958 PyErr_SetString(PyExc_OverflowError,
11959 "repeated string is too long");
11960 return NULL;
11961 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011962 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011963
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011964 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011965 if (!u)
11966 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011967 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 if (PyUnicode_GET_LENGTH(str) == 1) {
11970 const int kind = PyUnicode_KIND(str);
11971 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11972 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011973 if (kind == PyUnicode_1BYTE_KIND)
11974 memset(to, (unsigned char)fill_char, len);
11975 else {
11976 for (n = 0; n < len; ++n)
11977 PyUnicode_WRITE(kind, to, n, fill_char);
11978 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011979 }
11980 else {
11981 /* number of characters copied this far */
11982 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011983 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011984 char *to = (char *) PyUnicode_DATA(u);
11985 Py_MEMCPY(to, PyUnicode_DATA(str),
11986 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011987 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011988 n = (done <= nchars-done) ? done : nchars-done;
11989 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011990 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011991 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011992 }
11993
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011994 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011995 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011996}
11997
Alexander Belopolsky40018472011-02-26 01:02:56 +000011998PyObject *
11999PyUnicode_Replace(PyObject *obj,
12000 PyObject *subobj,
12001 PyObject *replobj,
12002 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012003{
12004 PyObject *self;
12005 PyObject *str1;
12006 PyObject *str2;
12007 PyObject *result;
12008
12009 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012010 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012011 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012012 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012013 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012014 Py_DECREF(self);
12015 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012016 }
12017 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020012018 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012019 Py_DECREF(self);
12020 Py_DECREF(str1);
12021 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012022 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012023 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012024 Py_DECREF(self);
12025 Py_DECREF(str1);
12026 Py_DECREF(str2);
12027 return result;
12028}
12029
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012030PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000012031 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012032\n\
12033Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000012034old replaced by new. If the optional argument count is\n\
12035given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012036
12037static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012038unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012039{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 PyObject *str1;
12041 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012042 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012043 PyObject *result;
12044
Martin v. Löwis18e16552006-02-15 17:27:45 +000012045 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012046 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012047 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012048 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012049 str1 = PyUnicode_FromObject(str1);
12050 if (str1 == NULL || PyUnicode_READY(str1) == -1)
12051 return NULL;
12052 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020012053 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000012054 Py_DECREF(str1);
12055 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000012056 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012057
12058 result = replace(self, str1, str2, maxcount);
12059
12060 Py_DECREF(str1);
12061 Py_DECREF(str2);
12062 return result;
12063}
12064
Alexander Belopolsky40018472011-02-26 01:02:56 +000012065static PyObject *
12066unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012067{
Walter Dörwald79e913e2007-05-12 11:08:06 +000012068 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012069 Py_ssize_t isize;
12070 Py_ssize_t osize, squote, dquote, i, o;
12071 Py_UCS4 max, quote;
12072 int ikind, okind;
12073 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000012074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000012076 return NULL;
12077
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012078 isize = PyUnicode_GET_LENGTH(unicode);
12079 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 /* Compute length of output, quote characters, and
12082 maximum character */
12083 osize = 2; /* quotes */
12084 max = 127;
12085 squote = dquote = 0;
12086 ikind = PyUnicode_KIND(unicode);
12087 for (i = 0; i < isize; i++) {
12088 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12089 switch (ch) {
12090 case '\'': squote++; osize++; break;
12091 case '"': dquote++; osize++; break;
12092 case '\\': case '\t': case '\r': case '\n':
12093 osize += 2; break;
12094 default:
12095 /* Fast-path ASCII */
12096 if (ch < ' ' || ch == 0x7f)
12097 osize += 4; /* \xHH */
12098 else if (ch < 0x7f)
12099 osize++;
12100 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12101 osize++;
12102 max = ch > max ? ch : max;
12103 }
12104 else if (ch < 0x100)
12105 osize += 4; /* \xHH */
12106 else if (ch < 0x10000)
12107 osize += 6; /* \uHHHH */
12108 else
12109 osize += 10; /* \uHHHHHHHH */
12110 }
12111 }
12112
12113 quote = '\'';
12114 if (squote) {
12115 if (dquote)
12116 /* Both squote and dquote present. Use squote,
12117 and escape them */
12118 osize += squote;
12119 else
12120 quote = '"';
12121 }
12122
12123 repr = PyUnicode_New(osize, max);
12124 if (repr == NULL)
12125 return NULL;
12126 okind = PyUnicode_KIND(repr);
12127 odata = PyUnicode_DATA(repr);
12128
12129 PyUnicode_WRITE(okind, odata, 0, quote);
12130 PyUnicode_WRITE(okind, odata, osize-1, quote);
12131
12132 for (i = 0, o = 1; i < isize; i++) {
12133 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012134
12135 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136 if ((ch == quote) || (ch == '\\')) {
12137 PyUnicode_WRITE(okind, odata, o++, '\\');
12138 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012139 continue;
12140 }
12141
Benjamin Peterson29060642009-01-31 22:14:21 +000012142 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012143 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 PyUnicode_WRITE(okind, odata, o++, '\\');
12145 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012146 }
12147 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148 PyUnicode_WRITE(okind, odata, o++, '\\');
12149 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012150 }
12151 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012152 PyUnicode_WRITE(okind, odata, o++, '\\');
12153 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012154 }
12155
12156 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012157 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012158 PyUnicode_WRITE(okind, odata, o++, '\\');
12159 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012160 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12161 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012162 }
12163
Georg Brandl559e5d72008-06-11 18:37:52 +000012164 /* Copy ASCII characters as-is */
12165 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012167 }
12168
Benjamin Peterson29060642009-01-31 22:14:21 +000012169 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012170 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012171 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012172 (categories Z* and C* except ASCII space)
12173 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012174 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012175 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012176 if (ch <= 0xff) {
12177 PyUnicode_WRITE(okind, odata, o++, '\\');
12178 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012179 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12180 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012181 }
12182 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183 else if (ch >= 0x10000) {
12184 PyUnicode_WRITE(okind, odata, o++, '\\');
12185 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012186 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12187 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12188 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12189 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12190 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12191 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12192 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12193 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012194 }
12195 /* Map 16-bit characters to '\uxxxx' */
12196 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012197 PyUnicode_WRITE(okind, odata, o++, '\\');
12198 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012199 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12200 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12201 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12202 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012203 }
12204 }
12205 /* Copy characters as-is */
12206 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012208 }
12209 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012210 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012211 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012212 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012213 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214}
12215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012216PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012217 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218\n\
12219Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012220such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221arguments start and end are interpreted as in slice notation.\n\
12222\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012223Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224
12225static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012228 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012229 Py_ssize_t start;
12230 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012231 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232
Jesus Ceaac451502011-04-20 17:09:23 +020012233 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12234 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012235 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012237 if (PyUnicode_READY(self) == -1)
12238 return NULL;
12239 if (PyUnicode_READY(substring) == -1)
12240 return NULL;
12241
Victor Stinner7931d9a2011-11-04 00:22:48 +010012242 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012243
12244 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012245
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012246 if (result == -2)
12247 return NULL;
12248
Christian Heimes217cfd12007-12-02 14:31:20 +000012249 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250}
12251
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012252PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012253 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012254\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012255Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256
12257static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012260 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012261 Py_ssize_t start;
12262 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012263 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012264
Jesus Ceaac451502011-04-20 17:09:23 +020012265 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12266 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012267 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012269 if (PyUnicode_READY(self) == -1)
12270 return NULL;
12271 if (PyUnicode_READY(substring) == -1)
12272 return NULL;
12273
Victor Stinner7931d9a2011-11-04 00:22:48 +010012274 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012275
12276 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012277
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 if (result == -2)
12279 return NULL;
12280
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 if (result < 0) {
12282 PyErr_SetString(PyExc_ValueError, "substring not found");
12283 return NULL;
12284 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012285
Christian Heimes217cfd12007-12-02 14:31:20 +000012286 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287}
12288
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012289PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012290 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012291\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012292Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012293done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012294
12295static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012296unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012297{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012298 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012299 Py_UCS4 fillchar = ' ';
12300
Victor Stinnere9a29352011-10-01 02:14:59 +020012301 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012302 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012303
Victor Stinnere9a29352011-10-01 02:14:59 +020012304 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012305 return NULL;
12306
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012308 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012309 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012310 }
12311
Victor Stinner7931d9a2011-11-04 00:22:48 +010012312 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012313}
12314
Alexander Belopolsky40018472011-02-26 01:02:56 +000012315PyObject *
12316PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012317{
12318 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012319
Guido van Rossumd57fd912000-03-10 22:53:23 +000012320 s = PyUnicode_FromObject(s);
12321 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012322 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012323 if (sep != NULL) {
12324 sep = PyUnicode_FromObject(sep);
12325 if (sep == NULL) {
12326 Py_DECREF(s);
12327 return NULL;
12328 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012329 }
12330
Victor Stinner9310abb2011-10-05 00:59:23 +020012331 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012332
12333 Py_DECREF(s);
12334 Py_XDECREF(sep);
12335 return result;
12336}
12337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012338PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012339 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012340\n\
12341Return a list of the words in S, using sep as the\n\
12342delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012343splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012344whitespace string is a separator and empty strings are\n\
12345removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012346
12347static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012348unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012349{
12350 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012351 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012352
Martin v. Löwis18e16552006-02-15 17:27:45 +000012353 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012354 return NULL;
12355
12356 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012357 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012358 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012359 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012360 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012361 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012362}
12363
Thomas Wouters477c8d52006-05-27 19:21:47 +000012364PyObject *
12365PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12366{
12367 PyObject* str_obj;
12368 PyObject* sep_obj;
12369 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012370 int kind1, kind2, kind;
12371 void *buf1 = NULL, *buf2 = NULL;
12372 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373
12374 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012375 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012376 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012377 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012378 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012379 Py_DECREF(str_obj);
12380 return NULL;
12381 }
12382
Victor Stinner14f8f022011-10-05 20:58:25 +020012383 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012384 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012385 kind = Py_MAX(kind1, kind2);
12386 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012387 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012388 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012389 if (!buf1)
12390 goto onError;
12391 buf2 = PyUnicode_DATA(sep_obj);
12392 if (kind2 != kind)
12393 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12394 if (!buf2)
12395 goto onError;
12396 len1 = PyUnicode_GET_LENGTH(str_obj);
12397 len2 = PyUnicode_GET_LENGTH(sep_obj);
12398
Victor Stinner14f8f022011-10-05 20:58:25 +020012399 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012400 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012401 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12402 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12403 else
12404 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012405 break;
12406 case PyUnicode_2BYTE_KIND:
12407 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12408 break;
12409 case PyUnicode_4BYTE_KIND:
12410 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12411 break;
12412 default:
12413 assert(0);
12414 out = 0;
12415 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012416
12417 Py_DECREF(sep_obj);
12418 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012419 if (kind1 != kind)
12420 PyMem_Free(buf1);
12421 if (kind2 != kind)
12422 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012423
12424 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012425 onError:
12426 Py_DECREF(sep_obj);
12427 Py_DECREF(str_obj);
12428 if (kind1 != kind && buf1)
12429 PyMem_Free(buf1);
12430 if (kind2 != kind && buf2)
12431 PyMem_Free(buf2);
12432 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012433}
12434
12435
12436PyObject *
12437PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12438{
12439 PyObject* str_obj;
12440 PyObject* sep_obj;
12441 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012442 int kind1, kind2, kind;
12443 void *buf1 = NULL, *buf2 = NULL;
12444 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012445
12446 str_obj = PyUnicode_FromObject(str_in);
12447 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012448 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012449 sep_obj = PyUnicode_FromObject(sep_in);
12450 if (!sep_obj) {
12451 Py_DECREF(str_obj);
12452 return NULL;
12453 }
12454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012455 kind1 = PyUnicode_KIND(str_in);
12456 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012457 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012458 buf1 = PyUnicode_DATA(str_in);
12459 if (kind1 != kind)
12460 buf1 = _PyUnicode_AsKind(str_in, kind);
12461 if (!buf1)
12462 goto onError;
12463 buf2 = PyUnicode_DATA(sep_obj);
12464 if (kind2 != kind)
12465 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12466 if (!buf2)
12467 goto onError;
12468 len1 = PyUnicode_GET_LENGTH(str_obj);
12469 len2 = PyUnicode_GET_LENGTH(sep_obj);
12470
12471 switch(PyUnicode_KIND(str_in)) {
12472 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012473 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12474 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12475 else
12476 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012477 break;
12478 case PyUnicode_2BYTE_KIND:
12479 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12480 break;
12481 case PyUnicode_4BYTE_KIND:
12482 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12483 break;
12484 default:
12485 assert(0);
12486 out = 0;
12487 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012488
12489 Py_DECREF(sep_obj);
12490 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012491 if (kind1 != kind)
12492 PyMem_Free(buf1);
12493 if (kind2 != kind)
12494 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012495
12496 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 onError:
12498 Py_DECREF(sep_obj);
12499 Py_DECREF(str_obj);
12500 if (kind1 != kind && buf1)
12501 PyMem_Free(buf1);
12502 if (kind2 != kind && buf2)
12503 PyMem_Free(buf2);
12504 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012505}
12506
12507PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012508 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012509\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012510Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012511the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012512found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012513
12514static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012515unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012516{
Victor Stinner9310abb2011-10-05 00:59:23 +020012517 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012518}
12519
12520PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012521 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012522\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012523Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012524the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012525separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012526
12527static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012528unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012529{
Victor Stinner9310abb2011-10-05 00:59:23 +020012530 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012531}
12532
Alexander Belopolsky40018472011-02-26 01:02:56 +000012533PyObject *
12534PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012535{
12536 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012537
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012538 s = PyUnicode_FromObject(s);
12539 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012540 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012541 if (sep != NULL) {
12542 sep = PyUnicode_FromObject(sep);
12543 if (sep == NULL) {
12544 Py_DECREF(s);
12545 return NULL;
12546 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012547 }
12548
Victor Stinner9310abb2011-10-05 00:59:23 +020012549 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012550
12551 Py_DECREF(s);
12552 Py_XDECREF(sep);
12553 return result;
12554}
12555
12556PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012557 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012558\n\
12559Return a list of the words in S, using sep as the\n\
12560delimiter string, starting at the end of the string and\n\
12561working to the front. If maxsplit is given, at most maxsplit\n\
12562splits are done. If sep is not specified, any whitespace string\n\
12563is a separator.");
12564
12565static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012566unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012567{
12568 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012569 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012570
Martin v. Löwis18e16552006-02-15 17:27:45 +000012571 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012572 return NULL;
12573
12574 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012575 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012576 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012577 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012578 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012579 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012580}
12581
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012582PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012583 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012584\n\
12585Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012586Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012587is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012588
12589static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012590unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012592 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012593 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012594
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012595 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12596 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597 return NULL;
12598
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012599 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600}
12601
12602static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012603PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012604{
Walter Dörwald346737f2007-05-31 10:44:43 +000012605 if (PyUnicode_CheckExact(self)) {
12606 Py_INCREF(self);
12607 return self;
12608 } else
12609 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012610 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012611}
12612
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012613PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012614 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615\n\
12616Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012617and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012618
12619static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012620unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012622 return fixup(self, fixswapcase);
12623}
12624
Georg Brandlceee0772007-11-27 23:48:05 +000012625PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012626 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012627\n\
12628Return a translation table usable for str.translate().\n\
12629If there is only one argument, it must be a dictionary mapping Unicode\n\
12630ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012631Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012632If there are two arguments, they must be strings of equal length, and\n\
12633in the resulting dictionary, each character in x will be mapped to the\n\
12634character at the same position in y. If there is a third argument, it\n\
12635must be a string, whose characters will be mapped to None in the result.");
12636
12637static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012638unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012639{
12640 PyObject *x, *y = NULL, *z = NULL;
12641 PyObject *new = NULL, *key, *value;
12642 Py_ssize_t i = 0;
12643 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012644
Georg Brandlceee0772007-11-27 23:48:05 +000012645 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12646 return NULL;
12647 new = PyDict_New();
12648 if (!new)
12649 return NULL;
12650 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012651 int x_kind, y_kind, z_kind;
12652 void *x_data, *y_data, *z_data;
12653
Georg Brandlceee0772007-11-27 23:48:05 +000012654 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012655 if (!PyUnicode_Check(x)) {
12656 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12657 "be a string if there is a second argument");
12658 goto err;
12659 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012661 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12662 "arguments must have equal length");
12663 goto err;
12664 }
12665 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012666 x_kind = PyUnicode_KIND(x);
12667 y_kind = PyUnicode_KIND(y);
12668 x_data = PyUnicode_DATA(x);
12669 y_data = PyUnicode_DATA(y);
12670 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12671 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12672 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012673 if (!key || !value)
12674 goto err;
12675 res = PyDict_SetItem(new, key, value);
12676 Py_DECREF(key);
12677 Py_DECREF(value);
12678 if (res < 0)
12679 goto err;
12680 }
12681 /* create entries for deleting chars in z */
12682 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012683 z_kind = PyUnicode_KIND(z);
12684 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012685 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012687 if (!key)
12688 goto err;
12689 res = PyDict_SetItem(new, key, Py_None);
12690 Py_DECREF(key);
12691 if (res < 0)
12692 goto err;
12693 }
12694 }
12695 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012696 int kind;
12697 void *data;
12698
Georg Brandlceee0772007-11-27 23:48:05 +000012699 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012700 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012701 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12702 "to maketrans it must be a dict");
12703 goto err;
12704 }
12705 /* copy entries into the new dict, converting string keys to int keys */
12706 while (PyDict_Next(x, &i, &key, &value)) {
12707 if (PyUnicode_Check(key)) {
12708 /* convert string keys to integer keys */
12709 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012710 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012711 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12712 "table must be of length 1");
12713 goto err;
12714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012715 kind = PyUnicode_KIND(key);
12716 data = PyUnicode_DATA(key);
12717 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012718 if (!newkey)
12719 goto err;
12720 res = PyDict_SetItem(new, newkey, value);
12721 Py_DECREF(newkey);
12722 if (res < 0)
12723 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012724 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012725 /* just keep integer keys */
12726 if (PyDict_SetItem(new, key, value) < 0)
12727 goto err;
12728 } else {
12729 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12730 "be strings or integers");
12731 goto err;
12732 }
12733 }
12734 }
12735 return new;
12736 err:
12737 Py_DECREF(new);
12738 return NULL;
12739}
12740
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012741PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012742 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743\n\
12744Return a copy of the string S, where all characters have been mapped\n\
12745through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012746Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012747Unmapped characters are left untouched. Characters mapped to None\n\
12748are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749
12750static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012751unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012753 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012754}
12755
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012756PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012759Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760
12761static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012762unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012763{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764 return fixup(self, fixupper);
12765}
12766
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012767PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012768 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012769\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012770Pad a numeric string S with zeros on the left, to fill a field\n\
12771of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012772
12773static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012774unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012775{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012776 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012777 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012778 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012779 int kind;
12780 void *data;
12781 Py_UCS4 chr;
12782
12783 if (PyUnicode_READY(self) == -1)
12784 return NULL;
12785
Martin v. Löwis18e16552006-02-15 17:27:45 +000012786 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012787 return NULL;
12788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012789 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012790 if (PyUnicode_CheckExact(self)) {
12791 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012792 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012793 }
12794 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012795 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796 }
12797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012798 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012799
12800 u = pad(self, fill, 0, '0');
12801
Walter Dörwald068325e2002-04-15 13:36:47 +000012802 if (u == NULL)
12803 return NULL;
12804
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012805 kind = PyUnicode_KIND(u);
12806 data = PyUnicode_DATA(u);
12807 chr = PyUnicode_READ(kind, data, fill);
12808
12809 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012811 PyUnicode_WRITE(kind, data, 0, chr);
12812 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012813 }
12814
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012815 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012816 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012817}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012818
12819#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012820static PyObject *
12821unicode__decimal2ascii(PyObject *self)
12822{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012823 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012824}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012825#endif
12826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012827PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012829\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012830Return True if S starts with the specified prefix, False otherwise.\n\
12831With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012832With optional end, stop comparing S at that position.\n\
12833prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012834
12835static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012836unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012837 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012838{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012839 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012840 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012841 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012842 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012843 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012844
Jesus Ceaac451502011-04-20 17:09:23 +020012845 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012846 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012847 if (PyTuple_Check(subobj)) {
12848 Py_ssize_t i;
12849 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012850 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012851 if (substring == NULL)
12852 return NULL;
12853 result = tailmatch(self, substring, start, end, -1);
12854 Py_DECREF(substring);
12855 if (result) {
12856 Py_RETURN_TRUE;
12857 }
12858 }
12859 /* nothing matched */
12860 Py_RETURN_FALSE;
12861 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012862 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012863 if (substring == NULL) {
12864 if (PyErr_ExceptionMatches(PyExc_TypeError))
12865 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12866 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012867 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012868 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012869 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012870 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012871 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012872}
12873
12874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012875PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012876 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012877\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012878Return True if S ends with the specified suffix, False otherwise.\n\
12879With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012880With optional end, stop comparing S at that position.\n\
12881suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012882
12883static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012884unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012885 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012887 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012888 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012889 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012890 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012891 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012892
Jesus Ceaac451502011-04-20 17:09:23 +020012893 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012894 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012895 if (PyTuple_Check(subobj)) {
12896 Py_ssize_t i;
12897 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012898 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012899 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012900 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012901 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012902 result = tailmatch(self, substring, start, end, +1);
12903 Py_DECREF(substring);
12904 if (result) {
12905 Py_RETURN_TRUE;
12906 }
12907 }
12908 Py_RETURN_FALSE;
12909 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012910 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012911 if (substring == NULL) {
12912 if (PyErr_ExceptionMatches(PyExc_TypeError))
12913 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12914 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012915 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012916 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012917 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012918 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012919 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920}
12921
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012922#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012923
12924PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012925 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012926\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012927Return a formatted version of S, using substitutions from args and kwargs.\n\
12928The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012929
Eric Smith27bbca62010-11-04 17:06:58 +000012930PyDoc_STRVAR(format_map__doc__,
12931 "S.format_map(mapping) -> str\n\
12932\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012933Return a formatted version of S, using substitutions from mapping.\n\
12934The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012935
Eric Smith4a7d76d2008-05-30 18:10:19 +000012936static PyObject *
12937unicode__format__(PyObject* self, PyObject* args)
12938{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012939 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012940
12941 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12942 return NULL;
12943
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012944 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012945 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012946 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012947}
12948
Eric Smith8c663262007-08-25 02:26:07 +000012949PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012950 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012951\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012952Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012953
12954static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012955unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012956{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012957 Py_ssize_t size;
12958
12959 /* If it's a compact object, account for base structure +
12960 character data. */
12961 if (PyUnicode_IS_COMPACT_ASCII(v))
12962 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12963 else if (PyUnicode_IS_COMPACT(v))
12964 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012965 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012966 else {
12967 /* If it is a two-block object, account for base object, and
12968 for character block if present. */
12969 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012970 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012971 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012972 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012973 }
12974 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012975 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012976 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012978 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012979 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012980
12981 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012982}
12983
12984PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012985 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012986
12987static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012988unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012989{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012990 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012991 if (!copy)
12992 return NULL;
12993 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012994}
12995
Guido van Rossumd57fd912000-03-10 22:53:23 +000012996static PyMethodDef unicode_methods[] = {
12997
12998 /* Order is according to common usage: often used methods should
12999 appear first, since lookup is done sequentially. */
13000
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000013001 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013002 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
13003 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000013004 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013005 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
13006 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
13007 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
13008 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
13009 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
13010 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
13011 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013012 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013013 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
13014 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
13015 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013016 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013017 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
13018 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
13019 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013020 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000013021 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010013022 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000013023 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013024 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
13025 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
13026 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
13027 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
13028 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
13029 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
13030 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
13031 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
13032 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
13033 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
13034 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
13035 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
13036 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
13037 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000013038 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000013039 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013040 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000013041 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000013042 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000013043 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000013044 {"maketrans", (PyCFunction) unicode_maketrans,
13045 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013046 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000013047#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000013048 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013049#endif
13050
13051#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013052 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000013053 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054#endif
13055
Benjamin Peterson14339b62009-01-31 16:36:08 +000013056 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057 {NULL, NULL}
13058};
13059
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013060static PyObject *
13061unicode_mod(PyObject *v, PyObject *w)
13062{
Brian Curtindfc80e32011-08-10 20:28:54 -050013063 if (!PyUnicode_Check(v))
13064 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000013065 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013066}
13067
13068static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013069 0, /*nb_add*/
13070 0, /*nb_subtract*/
13071 0, /*nb_multiply*/
13072 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013073};
13074
Guido van Rossumd57fd912000-03-10 22:53:23 +000013075static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013076 (lenfunc) unicode_length, /* sq_length */
13077 PyUnicode_Concat, /* sq_concat */
13078 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13079 (ssizeargfunc) unicode_getitem, /* sq_item */
13080 0, /* sq_slice */
13081 0, /* sq_ass_item */
13082 0, /* sq_ass_slice */
13083 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013084};
13085
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013086static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013087unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013088{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013089 if (PyUnicode_READY(self) == -1)
13090 return NULL;
13091
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013092 if (PyIndex_Check(item)) {
13093 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013094 if (i == -1 && PyErr_Occurred())
13095 return NULL;
13096 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013097 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013098 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013099 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013100 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013101 PyObject *result;
13102 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013103 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013104 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013106 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013108 return NULL;
13109 }
13110
13111 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013112 return PyUnicode_New(0, 0);
13113 } else if (start == 0 && step == 1 &&
13114 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013115 PyUnicode_CheckExact(self)) {
13116 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013117 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013118 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013119 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013120 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013121 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013122 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013123 src_kind = PyUnicode_KIND(self);
13124 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013125 if (!PyUnicode_IS_ASCII(self)) {
13126 kind_limit = kind_maxchar_limit(src_kind);
13127 max_char = 0;
13128 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13129 ch = PyUnicode_READ(src_kind, src_data, cur);
13130 if (ch > max_char) {
13131 max_char = ch;
13132 if (max_char >= kind_limit)
13133 break;
13134 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013135 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013136 }
Victor Stinner55c99112011-10-13 01:17:06 +020013137 else
13138 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013139 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013140 if (result == NULL)
13141 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013142 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013143 dest_data = PyUnicode_DATA(result);
13144
13145 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013146 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13147 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013148 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013149 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013150 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013151 } else {
13152 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13153 return NULL;
13154 }
13155}
13156
13157static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013158 (lenfunc)unicode_length, /* mp_length */
13159 (binaryfunc)unicode_subscript, /* mp_subscript */
13160 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013161};
13162
Guido van Rossumd57fd912000-03-10 22:53:23 +000013163
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164/* Helpers for PyUnicode_Format() */
13165
13166static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013167getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013169 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013170 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013171 (*p_argidx)++;
13172 if (arglen < 0)
13173 return args;
13174 else
13175 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176 }
13177 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013178 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013179 return NULL;
13180}
13181
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013182/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013184static PyObject *
13185formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013187 char *p;
13188 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013189 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013190
Guido van Rossumd57fd912000-03-10 22:53:23 +000013191 x = PyFloat_AsDouble(v);
13192 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013193 return NULL;
13194
Guido van Rossumd57fd912000-03-10 22:53:23 +000013195 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013196 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013197
Eric Smith0923d1d2009-04-16 20:16:10 +000013198 p = PyOS_double_to_string(x, type, prec,
13199 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013200 if (p == NULL)
13201 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013202 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013203 PyMem_Free(p);
13204 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205}
13206
Tim Peters38fd5b62000-09-21 05:43:11 +000013207static PyObject*
13208formatlong(PyObject *val, int flags, int prec, int type)
13209{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013210 char *buf;
13211 int len;
13212 PyObject *str; /* temporary string object. */
13213 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013214
Benjamin Peterson14339b62009-01-31 16:36:08 +000013215 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13216 if (!str)
13217 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013219 Py_DECREF(str);
13220 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013221}
13222
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013223static Py_UCS4
13224formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013226 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013227 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013228 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013229 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013230 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 goto onError;
13232 }
13233 else {
13234 /* Integer input truncated to a character */
13235 long x;
13236 x = PyLong_AsLong(v);
13237 if (x == -1 && PyErr_Occurred())
13238 goto onError;
13239
13240 if (x < 0 || x > 0x10ffff) {
13241 PyErr_SetString(PyExc_OverflowError,
13242 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013243 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 }
13245
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013246 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013247 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013248
Benjamin Peterson29060642009-01-31 22:14:21 +000013249 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013250 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013251 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013252 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013253}
13254
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013255static int
13256repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13257{
13258 int r;
13259 assert(count > 0);
13260 assert(PyUnicode_Check(obj));
13261 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013262 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013263 if (repeated == NULL)
13264 return -1;
13265 r = _PyAccu_Accumulate(acc, repeated);
13266 Py_DECREF(repeated);
13267 return r;
13268 }
13269 else {
13270 do {
13271 if (_PyAccu_Accumulate(acc, obj))
13272 return -1;
13273 } while (--count);
13274 return 0;
13275 }
13276}
13277
Alexander Belopolsky40018472011-02-26 01:02:56 +000013278PyObject *
13279PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013280{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013281 void *fmt;
13282 int fmtkind;
13283 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013284 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013285 int r;
13286 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013287 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013288 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013289 PyObject *temp = NULL;
13290 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013291 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013292 _PyAccu acc;
13293 static PyObject *plus, *minus, *blank, *zero, *percent;
13294
13295 if (!plus && !(plus = get_latin1_char('+')))
13296 return NULL;
13297 if (!minus && !(minus = get_latin1_char('-')))
13298 return NULL;
13299 if (!blank && !(blank = get_latin1_char(' ')))
13300 return NULL;
13301 if (!zero && !(zero = get_latin1_char('0')))
13302 return NULL;
13303 if (!percent && !(percent = get_latin1_char('%')))
13304 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013305
Guido van Rossumd57fd912000-03-10 22:53:23 +000013306 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013307 PyErr_BadInternalCall();
13308 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013309 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013310 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013311 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013312 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013313 if (_PyAccu_Init(&acc))
13314 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013315 fmt = PyUnicode_DATA(uformat);
13316 fmtkind = PyUnicode_KIND(uformat);
13317 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13318 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013319
Guido van Rossumd57fd912000-03-10 22:53:23 +000013320 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013321 arglen = PyTuple_Size(args);
13322 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013323 }
13324 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 arglen = -1;
13326 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013327 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013328 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013329 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013330 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013331
13332 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013333 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013334 PyObject *nonfmt;
13335 Py_ssize_t nonfmtpos;
13336 nonfmtpos = fmtpos++;
13337 while (fmtcnt >= 0 &&
13338 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13339 fmtpos++;
13340 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013341 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013342 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013343 if (nonfmt == NULL)
13344 goto onError;
13345 r = _PyAccu_Accumulate(&acc, nonfmt);
13346 Py_DECREF(nonfmt);
13347 if (r)
13348 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013349 }
13350 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013351 /* Got a format specifier */
13352 int flags = 0;
13353 Py_ssize_t width = -1;
13354 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013355 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013356 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013357 int isnumok;
13358 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013359 void *pbuf = NULL;
13360 Py_ssize_t pindex, len;
13361 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013362
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013363 fmtpos++;
13364 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13365 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013366 Py_ssize_t keylen;
13367 PyObject *key;
13368 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013369
Benjamin Peterson29060642009-01-31 22:14:21 +000013370 if (dict == NULL) {
13371 PyErr_SetString(PyExc_TypeError,
13372 "format requires a mapping");
13373 goto onError;
13374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013375 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013377 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013378 /* Skip over balanced parentheses */
13379 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013380 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013381 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013382 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013383 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013384 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013386 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013387 if (fmtcnt < 0 || pcount > 0) {
13388 PyErr_SetString(PyExc_ValueError,
13389 "incomplete format key");
13390 goto onError;
13391 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013392 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013393 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013394 if (key == NULL)
13395 goto onError;
13396 if (args_owned) {
13397 Py_DECREF(args);
13398 args_owned = 0;
13399 }
13400 args = PyObject_GetItem(dict, key);
13401 Py_DECREF(key);
13402 if (args == NULL) {
13403 goto onError;
13404 }
13405 args_owned = 1;
13406 arglen = -1;
13407 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013408 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013409 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013410 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013411 case '-': flags |= F_LJUST; continue;
13412 case '+': flags |= F_SIGN; continue;
13413 case ' ': flags |= F_BLANK; continue;
13414 case '#': flags |= F_ALT; continue;
13415 case '0': flags |= F_ZERO; continue;
13416 }
13417 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013418 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013419 if (c == '*') {
13420 v = getnextarg(args, arglen, &argidx);
13421 if (v == NULL)
13422 goto onError;
13423 if (!PyLong_Check(v)) {
13424 PyErr_SetString(PyExc_TypeError,
13425 "* wants int");
13426 goto onError;
13427 }
13428 width = PyLong_AsLong(v);
13429 if (width == -1 && PyErr_Occurred())
13430 goto onError;
13431 if (width < 0) {
13432 flags |= F_LJUST;
13433 width = -width;
13434 }
13435 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013436 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013437 }
13438 else if (c >= '0' && c <= '9') {
13439 width = c - '0';
13440 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013441 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013442 if (c < '0' || c > '9')
13443 break;
13444 if ((width*10) / 10 != width) {
13445 PyErr_SetString(PyExc_ValueError,
13446 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013447 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013448 }
13449 width = width*10 + (c - '0');
13450 }
13451 }
13452 if (c == '.') {
13453 prec = 0;
13454 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013455 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013456 if (c == '*') {
13457 v = getnextarg(args, arglen, &argidx);
13458 if (v == NULL)
13459 goto onError;
13460 if (!PyLong_Check(v)) {
13461 PyErr_SetString(PyExc_TypeError,
13462 "* wants int");
13463 goto onError;
13464 }
13465 prec = PyLong_AsLong(v);
13466 if (prec == -1 && PyErr_Occurred())
13467 goto onError;
13468 if (prec < 0)
13469 prec = 0;
13470 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013471 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013472 }
13473 else if (c >= '0' && c <= '9') {
13474 prec = c - '0';
13475 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013476 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013477 if (c < '0' || c > '9')
13478 break;
13479 if ((prec*10) / 10 != prec) {
13480 PyErr_SetString(PyExc_ValueError,
13481 "prec too big");
13482 goto onError;
13483 }
13484 prec = prec*10 + (c - '0');
13485 }
13486 }
13487 } /* prec */
13488 if (fmtcnt >= 0) {
13489 if (c == 'h' || c == 'l' || c == 'L') {
13490 if (--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 }
13493 }
13494 if (fmtcnt < 0) {
13495 PyErr_SetString(PyExc_ValueError,
13496 "incomplete format");
13497 goto onError;
13498 }
13499 if (c != '%') {
13500 v = getnextarg(args, arglen, &argidx);
13501 if (v == NULL)
13502 goto onError;
13503 }
13504 sign = 0;
13505 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013506 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013507 switch (c) {
13508
13509 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013510 _PyAccu_Accumulate(&acc, percent);
13511 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013512
13513 case 's':
13514 case 'r':
13515 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013516 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013517 temp = v;
13518 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013519 }
13520 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 if (c == 's')
13522 temp = PyObject_Str(v);
13523 else if (c == 'r')
13524 temp = PyObject_Repr(v);
13525 else
13526 temp = PyObject_ASCII(v);
13527 if (temp == NULL)
13528 goto onError;
13529 if (PyUnicode_Check(temp))
13530 /* nothing to do */;
13531 else {
13532 Py_DECREF(temp);
13533 PyErr_SetString(PyExc_TypeError,
13534 "%s argument has non-string str()");
13535 goto onError;
13536 }
13537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013538 if (PyUnicode_READY(temp) == -1) {
13539 Py_CLEAR(temp);
13540 goto onError;
13541 }
13542 pbuf = PyUnicode_DATA(temp);
13543 kind = PyUnicode_KIND(temp);
13544 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 if (prec >= 0 && len > prec)
13546 len = prec;
13547 break;
13548
13549 case 'i':
13550 case 'd':
13551 case 'u':
13552 case 'o':
13553 case 'x':
13554 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 isnumok = 0;
13556 if (PyNumber_Check(v)) {
13557 PyObject *iobj=NULL;
13558
13559 if (PyLong_Check(v)) {
13560 iobj = v;
13561 Py_INCREF(iobj);
13562 }
13563 else {
13564 iobj = PyNumber_Long(v);
13565 }
13566 if (iobj!=NULL) {
13567 if (PyLong_Check(iobj)) {
13568 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013569 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013570 Py_DECREF(iobj);
13571 if (!temp)
13572 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013573 if (PyUnicode_READY(temp) == -1) {
13574 Py_CLEAR(temp);
13575 goto onError;
13576 }
13577 pbuf = PyUnicode_DATA(temp);
13578 kind = PyUnicode_KIND(temp);
13579 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013580 sign = 1;
13581 }
13582 else {
13583 Py_DECREF(iobj);
13584 }
13585 }
13586 }
13587 if (!isnumok) {
13588 PyErr_Format(PyExc_TypeError,
13589 "%%%c format: a number is required, "
13590 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13591 goto onError;
13592 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013593 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013594 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013595 fillobj = zero;
13596 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013597 break;
13598
13599 case 'e':
13600 case 'E':
13601 case 'f':
13602 case 'F':
13603 case 'g':
13604 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013605 temp = formatfloat(v, flags, prec, c);
13606 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013608 if (PyUnicode_READY(temp) == -1) {
13609 Py_CLEAR(temp);
13610 goto onError;
13611 }
13612 pbuf = PyUnicode_DATA(temp);
13613 kind = PyUnicode_KIND(temp);
13614 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013616 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013618 fillobj = zero;
13619 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013620 break;
13621
13622 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013623 {
13624 Py_UCS4 ch = formatchar(v);
13625 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013626 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013627 temp = _PyUnicode_FromUCS4(&ch, 1);
13628 if (temp == NULL)
13629 goto onError;
13630 pbuf = PyUnicode_DATA(temp);
13631 kind = PyUnicode_KIND(temp);
13632 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013633 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013634 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013635
13636 default:
13637 PyErr_Format(PyExc_ValueError,
13638 "unsupported format character '%c' (0x%x) "
13639 "at index %zd",
13640 (31<=c && c<=126) ? (char)c : '?',
13641 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013642 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013643 goto onError;
13644 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013645 /* pbuf is initialized here. */
13646 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013647 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013648 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13649 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013650 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013651 pindex++;
13652 }
13653 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13654 signobj = plus;
13655 len--;
13656 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013657 }
13658 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013659 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013660 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013661 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013662 else
13663 sign = 0;
13664 }
13665 if (width < len)
13666 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013667 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013668 if (fill != ' ') {
13669 assert(signobj != NULL);
13670 if (_PyAccu_Accumulate(&acc, signobj))
13671 goto onError;
13672 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013673 if (width > len)
13674 width--;
13675 }
13676 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013677 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013678 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013679 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013680 second = get_latin1_char(
13681 PyUnicode_READ(kind, pbuf, pindex + 1));
13682 pindex += 2;
13683 if (second == NULL ||
13684 _PyAccu_Accumulate(&acc, zero) ||
13685 _PyAccu_Accumulate(&acc, second))
13686 goto onError;
13687 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013688 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013689 width -= 2;
13690 if (width < 0)
13691 width = 0;
13692 len -= 2;
13693 }
13694 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013695 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013696 if (repeat_accumulate(&acc, fillobj, width - len))
13697 goto onError;
13698 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013699 }
13700 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013701 if (sign) {
13702 assert(signobj != NULL);
13703 if (_PyAccu_Accumulate(&acc, signobj))
13704 goto onError;
13705 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013706 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013707 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13708 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013709 second = get_latin1_char(
13710 PyUnicode_READ(kind, pbuf, pindex + 1));
13711 pindex += 2;
13712 if (second == NULL ||
13713 _PyAccu_Accumulate(&acc, zero) ||
13714 _PyAccu_Accumulate(&acc, second))
13715 goto onError;
13716 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013717 }
13718 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013719 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013720 if (temp != NULL) {
13721 assert(pbuf == PyUnicode_DATA(temp));
13722 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013723 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013724 else {
13725 const char *p = (const char *) pbuf;
13726 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013727 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013728 v = PyUnicode_FromKindAndData(kind, p, len);
13729 }
13730 if (v == NULL)
13731 goto onError;
13732 r = _PyAccu_Accumulate(&acc, v);
13733 Py_DECREF(v);
13734 if (r)
13735 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013736 if (width > len && repeat_accumulate(&acc, blank, width - len))
13737 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013738 if (dict && (argidx < arglen) && c != '%') {
13739 PyErr_SetString(PyExc_TypeError,
13740 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013741 goto onError;
13742 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013743 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013744 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745 } /* until end */
13746 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013747 PyErr_SetString(PyExc_TypeError,
13748 "not all arguments converted during string formatting");
13749 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013750 }
13751
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013752 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013753 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013754 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013755 }
13756 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013757 Py_XDECREF(temp);
13758 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013759 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013760
Benjamin Peterson29060642009-01-31 22:14:21 +000013761 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013762 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013763 Py_XDECREF(temp);
13764 Py_XDECREF(second);
13765 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013766 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013767 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013768 }
13769 return NULL;
13770}
13771
Jeremy Hylton938ace62002-07-17 16:30:39 +000013772static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013773unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13774
Tim Peters6d6c1a32001-08-02 04:15:00 +000013775static PyObject *
13776unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13777{
Benjamin Peterson29060642009-01-31 22:14:21 +000013778 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013779 static char *kwlist[] = {"object", "encoding", "errors", 0};
13780 char *encoding = NULL;
13781 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013782
Benjamin Peterson14339b62009-01-31 16:36:08 +000013783 if (type != &PyUnicode_Type)
13784 return unicode_subtype_new(type, args, kwds);
13785 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013786 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013787 return NULL;
13788 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013789 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013790 if (encoding == NULL && errors == NULL)
13791 return PyObject_Str(x);
13792 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013793 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013794}
13795
Guido van Rossume023fe02001-08-30 03:12:59 +000013796static PyObject *
13797unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13798{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013799 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013800 Py_ssize_t length, char_size;
13801 int share_wstr, share_utf8;
13802 unsigned int kind;
13803 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013804
Benjamin Peterson14339b62009-01-31 16:36:08 +000013805 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013806
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013807 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013808 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013809 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013810 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013811 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013812 return NULL;
13813
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013814 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013815 if (self == NULL) {
13816 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013817 return NULL;
13818 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013819 kind = PyUnicode_KIND(unicode);
13820 length = PyUnicode_GET_LENGTH(unicode);
13821
13822 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013823#ifdef Py_DEBUG
13824 _PyUnicode_HASH(self) = -1;
13825#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013826 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013827#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013828 _PyUnicode_STATE(self).interned = 0;
13829 _PyUnicode_STATE(self).kind = kind;
13830 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013831 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013832 _PyUnicode_STATE(self).ready = 1;
13833 _PyUnicode_WSTR(self) = NULL;
13834 _PyUnicode_UTF8_LENGTH(self) = 0;
13835 _PyUnicode_UTF8(self) = NULL;
13836 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013837 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013838
13839 share_utf8 = 0;
13840 share_wstr = 0;
13841 if (kind == PyUnicode_1BYTE_KIND) {
13842 char_size = 1;
13843 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13844 share_utf8 = 1;
13845 }
13846 else if (kind == PyUnicode_2BYTE_KIND) {
13847 char_size = 2;
13848 if (sizeof(wchar_t) == 2)
13849 share_wstr = 1;
13850 }
13851 else {
13852 assert(kind == PyUnicode_4BYTE_KIND);
13853 char_size = 4;
13854 if (sizeof(wchar_t) == 4)
13855 share_wstr = 1;
13856 }
13857
13858 /* Ensure we won't overflow the length. */
13859 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13860 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013862 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013863 data = PyObject_MALLOC((length + 1) * char_size);
13864 if (data == NULL) {
13865 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013866 goto onError;
13867 }
13868
Victor Stinnerc3c74152011-10-02 20:39:55 +020013869 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013870 if (share_utf8) {
13871 _PyUnicode_UTF8_LENGTH(self) = length;
13872 _PyUnicode_UTF8(self) = data;
13873 }
13874 if (share_wstr) {
13875 _PyUnicode_WSTR_LENGTH(self) = length;
13876 _PyUnicode_WSTR(self) = (wchar_t *)data;
13877 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013878
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013879 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013880 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013881 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013882#ifdef Py_DEBUG
13883 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13884#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013885 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013886 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013887
13888onError:
13889 Py_DECREF(unicode);
13890 Py_DECREF(self);
13891 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013892}
13893
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013894PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013895 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013896\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013897Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013898encoding defaults to the current default string encoding.\n\
13899errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013900
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013901static PyObject *unicode_iter(PyObject *seq);
13902
Guido van Rossumd57fd912000-03-10 22:53:23 +000013903PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013904 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013905 "str", /* tp_name */
13906 sizeof(PyUnicodeObject), /* tp_size */
13907 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013908 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 (destructor)unicode_dealloc, /* tp_dealloc */
13910 0, /* tp_print */
13911 0, /* tp_getattr */
13912 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013913 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013914 unicode_repr, /* tp_repr */
13915 &unicode_as_number, /* tp_as_number */
13916 &unicode_as_sequence, /* tp_as_sequence */
13917 &unicode_as_mapping, /* tp_as_mapping */
13918 (hashfunc) unicode_hash, /* tp_hash*/
13919 0, /* tp_call*/
13920 (reprfunc) unicode_str, /* tp_str */
13921 PyObject_GenericGetAttr, /* tp_getattro */
13922 0, /* tp_setattro */
13923 0, /* tp_as_buffer */
13924 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013925 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013926 unicode_doc, /* tp_doc */
13927 0, /* tp_traverse */
13928 0, /* tp_clear */
13929 PyUnicode_RichCompare, /* tp_richcompare */
13930 0, /* tp_weaklistoffset */
13931 unicode_iter, /* tp_iter */
13932 0, /* tp_iternext */
13933 unicode_methods, /* tp_methods */
13934 0, /* tp_members */
13935 0, /* tp_getset */
13936 &PyBaseObject_Type, /* tp_base */
13937 0, /* tp_dict */
13938 0, /* tp_descr_get */
13939 0, /* tp_descr_set */
13940 0, /* tp_dictoffset */
13941 0, /* tp_init */
13942 0, /* tp_alloc */
13943 unicode_new, /* tp_new */
13944 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945};
13946
13947/* Initialize the Unicode implementation */
13948
Victor Stinner3a50e702011-10-18 21:21:00 +020013949int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013950{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013951 int i;
13952
Thomas Wouters477c8d52006-05-27 19:21:47 +000013953 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013954 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013955 0x000A, /* LINE FEED */
13956 0x000D, /* CARRIAGE RETURN */
13957 0x001C, /* FILE SEPARATOR */
13958 0x001D, /* GROUP SEPARATOR */
13959 0x001E, /* RECORD SEPARATOR */
13960 0x0085, /* NEXT LINE */
13961 0x2028, /* LINE SEPARATOR */
13962 0x2029, /* PARAGRAPH SEPARATOR */
13963 };
13964
Fred Drakee4315f52000-05-09 19:53:39 +000013965 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013966 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013967 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013968 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013969 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013970
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013971 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013972 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013973 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013974 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013975
13976 /* initialize the linebreak bloom filter */
13977 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013978 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013979 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013980
13981 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013982
13983#ifdef HAVE_MBCS
13984 winver.dwOSVersionInfoSize = sizeof(winver);
13985 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13986 PyErr_SetFromWindowsErr(0);
13987 return -1;
13988 }
13989#endif
13990 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013991}
13992
13993/* Finalize the Unicode implementation */
13994
Christian Heimesa156e092008-02-16 07:38:31 +000013995int
13996PyUnicode_ClearFreeList(void)
13997{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013998 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013999}
14000
Guido van Rossumd57fd912000-03-10 22:53:23 +000014001void
Thomas Wouters78890102000-07-22 19:25:51 +000014002_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000014003{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014004 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000014005
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000014006 Py_XDECREF(unicode_empty);
14007 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000014008
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014009 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000014010 if (unicode_latin1[i]) {
14011 Py_DECREF(unicode_latin1[i]);
14012 unicode_latin1[i] = NULL;
14013 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000014014 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020014015 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000014016 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000014017}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000014018
Walter Dörwald16807132007-05-25 13:52:07 +000014019void
14020PyUnicode_InternInPlace(PyObject **p)
14021{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014022 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014023 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020014024#ifdef Py_DEBUG
14025 assert(s != NULL);
14026 assert(_PyUnicode_CHECK(s));
14027#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000014028 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020014029 return;
14030#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000014031 /* If it's a subclass, we don't really know what putting
14032 it in the interned dict might do. */
14033 if (!PyUnicode_CheckExact(s))
14034 return;
14035 if (PyUnicode_CHECK_INTERNED(s))
14036 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020014037 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014038 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014039 return;
14040 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014041 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 if (interned == NULL) {
14043 interned = PyDict_New();
14044 if (interned == NULL) {
14045 PyErr_Clear(); /* Don't leave an exception */
14046 return;
14047 }
14048 }
14049 /* It might be that the GetItem call fails even
14050 though the key is present in the dictionary,
14051 namely when this happens during a stack overflow. */
14052 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010014053 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014054 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000014055
Benjamin Peterson29060642009-01-31 22:14:21 +000014056 if (t) {
14057 Py_INCREF(t);
14058 Py_DECREF(*p);
14059 *p = t;
14060 return;
14061 }
Walter Dörwald16807132007-05-25 13:52:07 +000014062
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010014064 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014065 PyErr_Clear();
14066 PyThreadState_GET()->recursion_critical = 0;
14067 return;
14068 }
14069 PyThreadState_GET()->recursion_critical = 0;
14070 /* The two references in interned are not counted by refcnt.
14071 The deallocator will take care of this */
14072 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014073 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014074}
14075
14076void
14077PyUnicode_InternImmortal(PyObject **p)
14078{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014079 PyUnicode_InternInPlace(p);
14080 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020014081 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014082 Py_INCREF(*p);
14083 }
Walter Dörwald16807132007-05-25 13:52:07 +000014084}
14085
14086PyObject *
14087PyUnicode_InternFromString(const char *cp)
14088{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014089 PyObject *s = PyUnicode_FromString(cp);
14090 if (s == NULL)
14091 return NULL;
14092 PyUnicode_InternInPlace(&s);
14093 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014094}
14095
Alexander Belopolsky40018472011-02-26 01:02:56 +000014096void
14097_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014098{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014099 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014100 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014101 Py_ssize_t i, n;
14102 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014103
Benjamin Peterson14339b62009-01-31 16:36:08 +000014104 if (interned == NULL || !PyDict_Check(interned))
14105 return;
14106 keys = PyDict_Keys(interned);
14107 if (keys == NULL || !PyList_Check(keys)) {
14108 PyErr_Clear();
14109 return;
14110 }
Walter Dörwald16807132007-05-25 13:52:07 +000014111
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14113 detector, interned unicode strings are not forcibly deallocated;
14114 rather, we give them their stolen references back, and then clear
14115 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014116
Benjamin Peterson14339b62009-01-31 16:36:08 +000014117 n = PyList_GET_SIZE(keys);
14118 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014119 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014120 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014121 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014122 if (PyUnicode_READY(s) == -1) {
14123 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014124 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014125 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014126 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014127 case SSTATE_NOT_INTERNED:
14128 /* XXX Shouldn't happen */
14129 break;
14130 case SSTATE_INTERNED_IMMORTAL:
14131 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014132 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014133 break;
14134 case SSTATE_INTERNED_MORTAL:
14135 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014136 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014137 break;
14138 default:
14139 Py_FatalError("Inconsistent interned string state.");
14140 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014141 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014142 }
14143 fprintf(stderr, "total size of all interned strings: "
14144 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14145 "mortal/immortal\n", mortal_size, immortal_size);
14146 Py_DECREF(keys);
14147 PyDict_Clear(interned);
14148 Py_DECREF(interned);
14149 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014150}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014151
14152
14153/********************* Unicode Iterator **************************/
14154
14155typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014156 PyObject_HEAD
14157 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014158 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014159} unicodeiterobject;
14160
14161static void
14162unicodeiter_dealloc(unicodeiterobject *it)
14163{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014164 _PyObject_GC_UNTRACK(it);
14165 Py_XDECREF(it->it_seq);
14166 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014167}
14168
14169static int
14170unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14171{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014172 Py_VISIT(it->it_seq);
14173 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014174}
14175
14176static PyObject *
14177unicodeiter_next(unicodeiterobject *it)
14178{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014179 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014180
Benjamin Peterson14339b62009-01-31 16:36:08 +000014181 assert(it != NULL);
14182 seq = it->it_seq;
14183 if (seq == NULL)
14184 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014185 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014186
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014187 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14188 int kind = PyUnicode_KIND(seq);
14189 void *data = PyUnicode_DATA(seq);
14190 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14191 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014192 if (item != NULL)
14193 ++it->it_index;
14194 return item;
14195 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014196
Benjamin Peterson14339b62009-01-31 16:36:08 +000014197 Py_DECREF(seq);
14198 it->it_seq = NULL;
14199 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014200}
14201
14202static PyObject *
14203unicodeiter_len(unicodeiterobject *it)
14204{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014205 Py_ssize_t len = 0;
14206 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014207 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014208 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014209}
14210
14211PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14212
14213static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014214 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014215 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014216 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014217};
14218
14219PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014220 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14221 "str_iterator", /* tp_name */
14222 sizeof(unicodeiterobject), /* tp_basicsize */
14223 0, /* tp_itemsize */
14224 /* methods */
14225 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14226 0, /* tp_print */
14227 0, /* tp_getattr */
14228 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014229 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014230 0, /* tp_repr */
14231 0, /* tp_as_number */
14232 0, /* tp_as_sequence */
14233 0, /* tp_as_mapping */
14234 0, /* tp_hash */
14235 0, /* tp_call */
14236 0, /* tp_str */
14237 PyObject_GenericGetAttr, /* tp_getattro */
14238 0, /* tp_setattro */
14239 0, /* tp_as_buffer */
14240 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14241 0, /* tp_doc */
14242 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14243 0, /* tp_clear */
14244 0, /* tp_richcompare */
14245 0, /* tp_weaklistoffset */
14246 PyObject_SelfIter, /* tp_iter */
14247 (iternextfunc)unicodeiter_next, /* tp_iternext */
14248 unicodeiter_methods, /* tp_methods */
14249 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014250};
14251
14252static PyObject *
14253unicode_iter(PyObject *seq)
14254{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014255 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014256
Benjamin Peterson14339b62009-01-31 16:36:08 +000014257 if (!PyUnicode_Check(seq)) {
14258 PyErr_BadInternalCall();
14259 return NULL;
14260 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014261 if (PyUnicode_READY(seq) == -1)
14262 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014263 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14264 if (it == NULL)
14265 return NULL;
14266 it->it_index = 0;
14267 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014268 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014269 _PyObject_GC_TRACK(it);
14270 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014271}
14272
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014273
14274size_t
14275Py_UNICODE_strlen(const Py_UNICODE *u)
14276{
14277 int res = 0;
14278 while(*u++)
14279 res++;
14280 return res;
14281}
14282
14283Py_UNICODE*
14284Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14285{
14286 Py_UNICODE *u = s1;
14287 while ((*u++ = *s2++));
14288 return s1;
14289}
14290
14291Py_UNICODE*
14292Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14293{
14294 Py_UNICODE *u = s1;
14295 while ((*u++ = *s2++))
14296 if (n-- == 0)
14297 break;
14298 return s1;
14299}
14300
14301Py_UNICODE*
14302Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14303{
14304 Py_UNICODE *u1 = s1;
14305 u1 += Py_UNICODE_strlen(u1);
14306 Py_UNICODE_strcpy(u1, s2);
14307 return s1;
14308}
14309
14310int
14311Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14312{
14313 while (*s1 && *s2 && *s1 == *s2)
14314 s1++, s2++;
14315 if (*s1 && *s2)
14316 return (*s1 < *s2) ? -1 : +1;
14317 if (*s1)
14318 return 1;
14319 if (*s2)
14320 return -1;
14321 return 0;
14322}
14323
14324int
14325Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14326{
14327 register Py_UNICODE u1, u2;
14328 for (; n != 0; n--) {
14329 u1 = *s1;
14330 u2 = *s2;
14331 if (u1 != u2)
14332 return (u1 < u2) ? -1 : +1;
14333 if (u1 == '\0')
14334 return 0;
14335 s1++;
14336 s2++;
14337 }
14338 return 0;
14339}
14340
14341Py_UNICODE*
14342Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14343{
14344 const Py_UNICODE *p;
14345 for (p = s; *p; p++)
14346 if (*p == c)
14347 return (Py_UNICODE*)p;
14348 return NULL;
14349}
14350
14351Py_UNICODE*
14352Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14353{
14354 const Py_UNICODE *p;
14355 p = s + Py_UNICODE_strlen(s);
14356 while (p != s) {
14357 p--;
14358 if (*p == c)
14359 return (Py_UNICODE*)p;
14360 }
14361 return NULL;
14362}
Victor Stinner331ea922010-08-10 16:37:20 +000014363
Victor Stinner71133ff2010-09-01 23:43:53 +000014364Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014365PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014366{
Victor Stinner577db2c2011-10-11 22:12:48 +020014367 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014368 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014369
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014370 if (!PyUnicode_Check(unicode)) {
14371 PyErr_BadArgument();
14372 return NULL;
14373 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014374 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014375 if (u == NULL)
14376 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014377 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014378 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014379 PyErr_NoMemory();
14380 return NULL;
14381 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014382 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014383 size *= sizeof(Py_UNICODE);
14384 copy = PyMem_Malloc(size);
14385 if (copy == NULL) {
14386 PyErr_NoMemory();
14387 return NULL;
14388 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014389 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014390 return copy;
14391}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014392
Georg Brandl66c221e2010-10-14 07:04:07 +000014393/* A _string module, to export formatter_parser and formatter_field_name_split
14394 to the string.Formatter class implemented in Python. */
14395
14396static PyMethodDef _string_methods[] = {
14397 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14398 METH_O, PyDoc_STR("split the argument as a field name")},
14399 {"formatter_parser", (PyCFunction) formatter_parser,
14400 METH_O, PyDoc_STR("parse the argument as a format string")},
14401 {NULL, NULL}
14402};
14403
14404static struct PyModuleDef _string_module = {
14405 PyModuleDef_HEAD_INIT,
14406 "_string",
14407 PyDoc_STR("string helper module"),
14408 0,
14409 _string_methods,
14410 NULL,
14411 NULL,
14412 NULL,
14413 NULL
14414};
14415
14416PyMODINIT_FUNC
14417PyInit__string(void)
14418{
14419 return PyModule_Create(&_string_module);
14420}
14421
14422
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014423#ifdef __cplusplus
14424}
14425#endif