blob: 547c857ac833be0638adb856725ef067f91d1138 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
119 _PyUnicode_Ready((PyObject *)(op))))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
251 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
257 const Py_UNICODE *unicode, Py_ssize_t size,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200305/* FIXME: use PyObject* type for op */
306_PyUnicode_CheckConsistency(void *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200307{
308 PyASCIIObject *ascii;
309 unsigned int kind;
310
311 assert(PyUnicode_Check(op));
312
313 ascii = (PyASCIIObject *)op;
314 kind = ascii->state.kind;
315
Victor Stinnera3b334d2011-10-03 13:53:37 +0200316 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200318 assert(ascii->state.ready == 1);
319 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200320 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200321 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200322 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200323
Victor Stinnera41463c2011-10-04 01:05:08 +0200324 if (ascii->state.compact == 1) {
325 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200326 assert(kind == PyUnicode_1BYTE_KIND
327 || kind == PyUnicode_2BYTE_KIND
328 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200329 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200330 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200331 assert (compact->utf8 != data);
332 } else {
333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
337 assert(ascii->state.compact == 0);
338 assert(ascii->state.ascii == 0);
339 assert(ascii->state.ready == 0);
340 assert(ascii->wstr != NULL);
341 assert(data == NULL);
342 assert(compact->utf8 == NULL);
343 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
344 }
345 else {
346 assert(kind == PyUnicode_1BYTE_KIND
347 || kind == PyUnicode_2BYTE_KIND
348 || kind == PyUnicode_4BYTE_KIND);
349 assert(ascii->state.compact == 0);
350 assert(ascii->state.ready == 1);
351 assert(data != NULL);
352 if (ascii->state.ascii) {
353 assert (compact->utf8 == data);
354 assert (compact->utf8_length == ascii->length);
355 }
356 else
357 assert (compact->utf8 != data);
358 }
359 }
360 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200361 if (
362#if SIZEOF_WCHAR_T == 2
363 kind == PyUnicode_2BYTE_KIND
364#else
365 kind == PyUnicode_4BYTE_KIND
366#endif
367 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200368 {
369 assert(ascii->wstr == data);
370 assert(compact->wstr_length == ascii->length);
371 } else
372 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200373 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200374
375 if (compact->utf8 == NULL)
376 assert(compact->utf8_length == 0);
377 if (ascii->wstr == NULL)
378 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200379 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200380 /* check that the best kind is used */
381 if (check_content && kind != PyUnicode_WCHAR_KIND)
382 {
383 Py_ssize_t i;
384 Py_UCS4 maxchar = 0;
385 void *data = PyUnicode_DATA(ascii);
386 for (i=0; i < ascii->length; i++)
387 {
388 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
389 if (ch > maxchar)
390 maxchar = ch;
391 }
392 if (kind == PyUnicode_1BYTE_KIND) {
393 if (ascii->state.ascii == 0)
394 assert(maxchar >= 128);
395 else
396 assert(maxchar < 128);
397 }
398 else if (kind == PyUnicode_2BYTE_KIND)
399 assert(maxchar >= 0x100);
400 else
401 assert(maxchar >= 0x10000);
402 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200403 if (check_content && !unicode_is_singleton((PyObject*)ascii))
404 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400405 return 1;
406}
Victor Stinner910337b2011-10-03 03:20:16 +0200407#endif
408
Victor Stinner3a50e702011-10-18 21:21:00 +0200409#ifdef HAVE_MBCS
410static OSVERSIONINFOEX winver;
411#endif
412
Thomas Wouters477c8d52006-05-27 19:21:47 +0000413/* --- Bloom Filters ----------------------------------------------------- */
414
415/* stuff to implement simple "bloom filters" for Unicode characters.
416 to keep things simple, we use a single bitmask, using the least 5
417 bits from each unicode characters as the bit index. */
418
419/* the linebreak mask is set up by Unicode_Init below */
420
Antoine Pitrouf068f942010-01-13 14:19:12 +0000421#if LONG_BIT >= 128
422#define BLOOM_WIDTH 128
423#elif LONG_BIT >= 64
424#define BLOOM_WIDTH 64
425#elif LONG_BIT >= 32
426#define BLOOM_WIDTH 32
427#else
428#error "LONG_BIT is smaller than 32"
429#endif
430
Thomas Wouters477c8d52006-05-27 19:21:47 +0000431#define BLOOM_MASK unsigned long
432
433static BLOOM_MASK bloom_linebreak;
434
Antoine Pitrouf068f942010-01-13 14:19:12 +0000435#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
436#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437
Benjamin Peterson29060642009-01-31 22:14:21 +0000438#define BLOOM_LINEBREAK(ch) \
439 ((ch) < 128U ? ascii_linebreak[(ch)] : \
440 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441
Alexander Belopolsky40018472011-02-26 01:02:56 +0000442Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200443make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000444{
445 /* calculate simple bloom-style bitmask for a given unicode string */
446
Antoine Pitrouf068f942010-01-13 14:19:12 +0000447 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000448 Py_ssize_t i;
449
450 mask = 0;
451 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200452 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000453
454 return mask;
455}
456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200457#define BLOOM_MEMBER(mask, chr, str) \
458 (BLOOM(mask, chr) \
459 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000460
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200461/* Compilation of templated routines */
462
463#include "stringlib/asciilib.h"
464#include "stringlib/fastsearch.h"
465#include "stringlib/partition.h"
466#include "stringlib/split.h"
467#include "stringlib/count.h"
468#include "stringlib/find.h"
469#include "stringlib/find_max_char.h"
470#include "stringlib/localeutil.h"
471#include "stringlib/undef.h"
472
473#include "stringlib/ucs1lib.h"
474#include "stringlib/fastsearch.h"
475#include "stringlib/partition.h"
476#include "stringlib/split.h"
477#include "stringlib/count.h"
478#include "stringlib/find.h"
479#include "stringlib/find_max_char.h"
480#include "stringlib/localeutil.h"
481#include "stringlib/undef.h"
482
483#include "stringlib/ucs2lib.h"
484#include "stringlib/fastsearch.h"
485#include "stringlib/partition.h"
486#include "stringlib/split.h"
487#include "stringlib/count.h"
488#include "stringlib/find.h"
489#include "stringlib/find_max_char.h"
490#include "stringlib/localeutil.h"
491#include "stringlib/undef.h"
492
493#include "stringlib/ucs4lib.h"
494#include "stringlib/fastsearch.h"
495#include "stringlib/partition.h"
496#include "stringlib/split.h"
497#include "stringlib/count.h"
498#include "stringlib/find.h"
499#include "stringlib/find_max_char.h"
500#include "stringlib/localeutil.h"
501#include "stringlib/undef.h"
502
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200503#include "stringlib/unicodedefs.h"
504#include "stringlib/fastsearch.h"
505#include "stringlib/count.h"
506#include "stringlib/find.h"
507
Guido van Rossumd57fd912000-03-10 22:53:23 +0000508/* --- Unicode Object ----------------------------------------------------- */
509
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200510static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200511fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200513Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
514 Py_ssize_t size, Py_UCS4 ch,
515 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200516{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200517 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
518
519 switch (kind) {
520 case PyUnicode_1BYTE_KIND:
521 {
522 Py_UCS1 ch1 = (Py_UCS1) ch;
523 if (ch1 == ch)
524 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
525 else
526 return -1;
527 }
528 case PyUnicode_2BYTE_KIND:
529 {
530 Py_UCS2 ch2 = (Py_UCS2) ch;
531 if (ch2 == ch)
532 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
533 else
534 return -1;
535 }
536 case PyUnicode_4BYTE_KIND:
537 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
538 default:
539 assert(0);
540 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200541 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200542}
543
Victor Stinnerfe226c02011-10-03 03:52:20 +0200544static PyObject*
545resize_compact(PyObject *unicode, Py_ssize_t length)
546{
547 Py_ssize_t char_size;
548 Py_ssize_t struct_size;
549 Py_ssize_t new_size;
550 int share_wstr;
551
552 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200553 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200554 if (PyUnicode_IS_COMPACT_ASCII(unicode))
555 struct_size = sizeof(PyASCIIObject);
556 else
557 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200558 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200559
560 _Py_DEC_REFTOTAL;
561 _Py_ForgetReference(unicode);
562
563 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
564 PyErr_NoMemory();
565 return NULL;
566 }
567 new_size = (struct_size + (length + 1) * char_size);
568
569 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
570 if (unicode == NULL) {
571 PyObject_Del(unicode);
572 PyErr_NoMemory();
573 return NULL;
574 }
575 _Py_NewReference(unicode);
576 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200577 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200578 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
580 _PyUnicode_WSTR_LENGTH(unicode) = length;
581 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200582 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
583 length, 0);
584 return unicode;
585}
586
Alexander Belopolsky40018472011-02-26 01:02:56 +0000587static int
Victor Stinner95663112011-10-04 01:03:50 +0200588resize_inplace(PyUnicodeObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000589{
Victor Stinner95663112011-10-04 01:03:50 +0200590 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200591 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200592 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000593
Victor Stinner95663112011-10-04 01:03:50 +0200594 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200595
596 if (PyUnicode_IS_READY(unicode)) {
597 Py_ssize_t char_size;
598 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200599 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200600 void *data;
601
602 data = _PyUnicode_DATA_ANY(unicode);
603 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200604 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200605 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
606 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200607 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
608 {
609 PyObject_DEL(_PyUnicode_UTF8(unicode));
610 _PyUnicode_UTF8(unicode) = NULL;
611 _PyUnicode_UTF8_LENGTH(unicode) = 0;
612 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200613
614 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
615 PyErr_NoMemory();
616 return -1;
617 }
618 new_size = (length + 1) * char_size;
619
620 data = (PyObject *)PyObject_REALLOC(data, new_size);
621 if (data == NULL) {
622 PyErr_NoMemory();
623 return -1;
624 }
625 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200626 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200627 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 _PyUnicode_WSTR_LENGTH(unicode) = length;
629 }
630 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200631 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200632 _PyUnicode_UTF8_LENGTH(unicode) = length;
633 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200634 _PyUnicode_LENGTH(unicode) = length;
635 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200636 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200637 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200638 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200639 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 }
Victor Stinner95663112011-10-04 01:03:50 +0200641 assert(_PyUnicode_WSTR(unicode) != NULL);
642
643 /* check for integer overflow */
644 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
645 PyErr_NoMemory();
646 return -1;
647 }
648 wstr = _PyUnicode_WSTR(unicode);
649 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
650 if (!wstr) {
651 PyErr_NoMemory();
652 return -1;
653 }
654 _PyUnicode_WSTR(unicode) = wstr;
655 _PyUnicode_WSTR(unicode)[length] = 0;
656 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200657 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000658 return 0;
659}
660
Victor Stinnerfe226c02011-10-03 03:52:20 +0200661static PyObject*
662resize_copy(PyObject *unicode, Py_ssize_t length)
663{
664 Py_ssize_t copy_length;
665 if (PyUnicode_IS_COMPACT(unicode)) {
666 PyObject *copy;
667 assert(PyUnicode_IS_READY(unicode));
668
669 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
670 if (copy == NULL)
671 return NULL;
672
673 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200674 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200675 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200676 }
677 else {
Victor Stinner2fd82272011-10-03 04:06:05 +0200678 PyUnicodeObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200679 assert(_PyUnicode_WSTR(unicode) != NULL);
680 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner2fd82272011-10-03 04:06:05 +0200681 w = _PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200682 if (w == NULL)
683 return NULL;
684 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
685 copy_length = Py_MIN(copy_length, length);
686 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
687 copy_length);
688 return (PyObject*)w;
689 }
690}
691
Guido van Rossumd57fd912000-03-10 22:53:23 +0000692/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000693 Ux0000 terminated; some code (e.g. new_identifier)
694 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000695
696 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000697 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000698
699*/
700
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200701#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200702static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#endif
704
Alexander Belopolsky40018472011-02-26 01:02:56 +0000705static PyUnicodeObject *
706_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000707{
708 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000710
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712 if (length == 0 && unicode_empty != NULL) {
713 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200714 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000715 }
716
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000717 /* Ensure we won't overflow the size. */
718 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
719 return (PyUnicodeObject *)PyErr_NoMemory();
720 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200721 if (length < 0) {
722 PyErr_SetString(PyExc_SystemError,
723 "Negative size passed to _PyUnicode_New");
724 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000725 }
726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200727#ifdef Py_DEBUG
728 ++unicode_old_new_calls;
729#endif
730
731 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
732 if (unicode == NULL)
733 return NULL;
734 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
735 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
736 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000737 PyErr_NoMemory();
738 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000739 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200740
Jeremy Hyltond8082792003-09-16 19:41:39 +0000741 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000742 * the caller fails before initializing str -- unicode_resize()
743 * reads str[0], and the Keep-Alive optimization can keep memory
744 * allocated for str alive across a call to unicode_dealloc(unicode).
745 * We don't want unicode_resize to read uninitialized memory in
746 * that case.
747 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200748 _PyUnicode_WSTR(unicode)[0] = 0;
749 _PyUnicode_WSTR(unicode)[length] = 0;
750 _PyUnicode_WSTR_LENGTH(unicode) = length;
751 _PyUnicode_HASH(unicode) = -1;
752 _PyUnicode_STATE(unicode).interned = 0;
753 _PyUnicode_STATE(unicode).kind = 0;
754 _PyUnicode_STATE(unicode).compact = 0;
755 _PyUnicode_STATE(unicode).ready = 0;
756 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200757 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200758 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200759 _PyUnicode_UTF8(unicode) = NULL;
760 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner67072932011-10-18 22:10:14 +0200761 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000762 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000763
Benjamin Peterson29060642009-01-31 22:14:21 +0000764 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000765 /* XXX UNREF/NEWREF interface should be more symmetrical */
766 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000767 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000768 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000770}
771
Victor Stinnerf42dc442011-10-02 23:33:16 +0200772static const char*
773unicode_kind_name(PyObject *unicode)
774{
Victor Stinner42dfd712011-10-03 14:41:45 +0200775 /* don't check consistency: unicode_kind_name() is called from
776 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200777 if (!PyUnicode_IS_COMPACT(unicode))
778 {
779 if (!PyUnicode_IS_READY(unicode))
780 return "wstr";
781 switch(PyUnicode_KIND(unicode))
782 {
783 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200784 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200785 return "legacy ascii";
786 else
787 return "legacy latin1";
788 case PyUnicode_2BYTE_KIND:
789 return "legacy UCS2";
790 case PyUnicode_4BYTE_KIND:
791 return "legacy UCS4";
792 default:
793 return "<legacy invalid kind>";
794 }
795 }
796 assert(PyUnicode_IS_READY(unicode));
797 switch(PyUnicode_KIND(unicode))
798 {
799 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200800 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200801 return "ascii";
802 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200803 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200804 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 default:
809 return "<invalid compact kind>";
810 }
811}
812
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200813#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200814static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815
816/* Functions wrapping macros for use in debugger */
817char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200818 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819}
820
821void *_PyUnicode_compact_data(void *unicode) {
822 return _PyUnicode_COMPACT_DATA(unicode);
823}
824void *_PyUnicode_data(void *unicode){
825 printf("obj %p\n", unicode);
826 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
827 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
828 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
829 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
830 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
831 return PyUnicode_DATA(unicode);
832}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200833
834void
835_PyUnicode_Dump(PyObject *op)
836{
837 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200838 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
839 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
840 void *data;
841 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
842 if (ascii->state.compact)
843 data = (compact + 1);
844 else
845 data = unicode->data.any;
846 if (ascii->wstr == data)
847 printf("shared ");
848 printf("wstr=%p", ascii->wstr);
Victor Stinnera3b334d2011-10-03 13:53:37 +0200849 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200850 printf(" (%zu), ", compact->wstr_length);
851 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
852 printf("shared ");
853 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200854 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200856}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200857#endif
858
859PyObject *
860PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
861{
862 PyObject *obj;
863 PyCompactUnicodeObject *unicode;
864 void *data;
865 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200866 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867 Py_ssize_t char_size;
868 Py_ssize_t struct_size;
869
870 /* Optimization for empty strings */
871 if (size == 0 && unicode_empty != NULL) {
872 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200873 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200874 }
875
876#ifdef Py_DEBUG
877 ++unicode_new_new_calls;
878#endif
879
Victor Stinner9e9d6892011-10-04 01:02:02 +0200880 is_ascii = 0;
881 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200882 struct_size = sizeof(PyCompactUnicodeObject);
883 if (maxchar < 128) {
884 kind_state = PyUnicode_1BYTE_KIND;
885 char_size = 1;
886 is_ascii = 1;
887 struct_size = sizeof(PyASCIIObject);
888 }
889 else if (maxchar < 256) {
890 kind_state = PyUnicode_1BYTE_KIND;
891 char_size = 1;
892 }
893 else if (maxchar < 65536) {
894 kind_state = PyUnicode_2BYTE_KIND;
895 char_size = 2;
896 if (sizeof(wchar_t) == 2)
897 is_sharing = 1;
898 }
899 else {
900 kind_state = PyUnicode_4BYTE_KIND;
901 char_size = 4;
902 if (sizeof(wchar_t) == 4)
903 is_sharing = 1;
904 }
905
906 /* Ensure we won't overflow the size. */
907 if (size < 0) {
908 PyErr_SetString(PyExc_SystemError,
909 "Negative size passed to PyUnicode_New");
910 return NULL;
911 }
912 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
913 return PyErr_NoMemory();
914
915 /* Duplicated allocation code from _PyObject_New() instead of a call to
916 * PyObject_New() so we are able to allocate space for the object and
917 * it's data buffer.
918 */
919 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
920 if (obj == NULL)
921 return PyErr_NoMemory();
922 obj = PyObject_INIT(obj, &PyUnicode_Type);
923 if (obj == NULL)
924 return NULL;
925
926 unicode = (PyCompactUnicodeObject *)obj;
927 if (is_ascii)
928 data = ((PyASCIIObject*)obj) + 1;
929 else
930 data = unicode + 1;
931 _PyUnicode_LENGTH(unicode) = size;
932 _PyUnicode_HASH(unicode) = -1;
933 _PyUnicode_STATE(unicode).interned = 0;
934 _PyUnicode_STATE(unicode).kind = kind_state;
935 _PyUnicode_STATE(unicode).compact = 1;
936 _PyUnicode_STATE(unicode).ready = 1;
937 _PyUnicode_STATE(unicode).ascii = is_ascii;
938 if (is_ascii) {
939 ((char*)data)[size] = 0;
940 _PyUnicode_WSTR(unicode) = NULL;
941 }
942 else if (kind_state == PyUnicode_1BYTE_KIND) {
943 ((char*)data)[size] = 0;
944 _PyUnicode_WSTR(unicode) = NULL;
945 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200946 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200947 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200948 }
949 else {
950 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200951 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200952 if (kind_state == PyUnicode_2BYTE_KIND)
953 ((Py_UCS2*)data)[size] = 0;
954 else /* kind_state == PyUnicode_4BYTE_KIND */
955 ((Py_UCS4*)data)[size] = 0;
956 if (is_sharing) {
957 _PyUnicode_WSTR_LENGTH(unicode) = size;
958 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
959 }
960 else {
961 _PyUnicode_WSTR_LENGTH(unicode) = 0;
962 _PyUnicode_WSTR(unicode) = NULL;
963 }
964 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200965 assert(_PyUnicode_CheckConsistency(unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200966 return obj;
967}
968
969#if SIZEOF_WCHAR_T == 2
970/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
971 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200972 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200973
974 This function assumes that unicode can hold one more code point than wstr
975 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200976static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200977unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
978 PyUnicodeObject *unicode)
979{
980 const wchar_t *iter;
981 Py_UCS4 *ucs4_out;
982
Victor Stinner910337b2011-10-03 03:20:16 +0200983 assert(unicode != NULL);
984 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200985 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
986 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
987
988 for (iter = begin; iter < end; ) {
989 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
990 _PyUnicode_GET_LENGTH(unicode)));
991 if (*iter >= 0xD800 && *iter <= 0xDBFF
992 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
993 {
994 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
995 iter += 2;
996 }
997 else {
998 *ucs4_out++ = *iter;
999 iter++;
1000 }
1001 }
1002 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1003 _PyUnicode_GET_LENGTH(unicode)));
1004
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001005}
1006#endif
1007
Victor Stinnercd9950f2011-10-02 00:34:53 +02001008static int
1009_PyUnicode_Dirty(PyObject *unicode)
1010{
Victor Stinner910337b2011-10-03 03:20:16 +02001011 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001012 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001013 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001014 "Cannot modify a string having more than 1 reference");
1015 return -1;
1016 }
1017 _PyUnicode_DIRTY(unicode);
1018 return 0;
1019}
1020
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001021static int
1022_copy_characters(PyObject *to, Py_ssize_t to_start,
1023 PyObject *from, Py_ssize_t from_start,
1024 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001025{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001026 unsigned int from_kind, to_kind;
1027 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001028 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001029
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001030 assert(PyUnicode_Check(from));
1031 assert(PyUnicode_Check(to));
1032 assert(PyUnicode_IS_READY(from));
1033 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001034
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001035 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1036 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1037 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001038
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001039 if (how_many == 0)
1040 return 0;
1041
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001042 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001043 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001045 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001046
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001047#ifdef Py_DEBUG
1048 if (!check_maxchar
1049 && (from_kind > to_kind
1050 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001051 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001052 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1053 Py_UCS4 ch;
1054 Py_ssize_t i;
1055 for (i=0; i < how_many; i++) {
1056 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1057 assert(ch <= to_maxchar);
1058 }
1059 }
1060#endif
1061 fast = (from_kind == to_kind);
1062 if (check_maxchar
1063 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1064 {
1065 /* deny latin1 => ascii */
1066 fast = 0;
1067 }
1068
1069 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001070 Py_MEMCPY((char*)to_data + to_kind * to_start,
1071 (char*)from_data + from_kind * from_start,
1072 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001073 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001074 else if (from_kind == PyUnicode_1BYTE_KIND
1075 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001076 {
1077 _PyUnicode_CONVERT_BYTES(
1078 Py_UCS1, Py_UCS2,
1079 PyUnicode_1BYTE_DATA(from) + from_start,
1080 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1081 PyUnicode_2BYTE_DATA(to) + to_start
1082 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001083 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001085 && to_kind == PyUnicode_4BYTE_KIND)
1086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS4,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_4BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
1094 else if (from_kind == PyUnicode_2BYTE_KIND
1095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS2, Py_UCS4,
1099 PyUnicode_2BYTE_DATA(from) + from_start,
1100 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001104 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001105 /* check if max_char(from substring) <= max_char(to) */
1106 if (from_kind > to_kind
1107 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001108 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001109 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001110 /* slow path to check for character overflow */
1111 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001112 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001113 Py_ssize_t i;
1114
Victor Stinner56c161a2011-10-06 02:47:11 +02001115#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001116 for (i=0; i < how_many; i++) {
1117 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001118 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001119 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1120 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001121#else
1122 if (!check_maxchar) {
1123 for (i=0; i < how_many; i++) {
1124 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1125 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1126 }
1127 }
1128 else {
1129 for (i=0; i < how_many; i++) {
1130 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1131 if (ch > to_maxchar)
1132 return 1;
1133 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1134 }
1135 }
1136#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001137 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001138 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001139 assert(0 && "inconsistent state");
1140 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001141 }
1142 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001143 return 0;
1144}
1145
1146static void
1147copy_characters(PyObject *to, Py_ssize_t to_start,
1148 PyObject *from, Py_ssize_t from_start,
1149 Py_ssize_t how_many)
1150{
1151 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1152}
1153
1154Py_ssize_t
1155PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1156 PyObject *from, Py_ssize_t from_start,
1157 Py_ssize_t how_many)
1158{
1159 int err;
1160
1161 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1162 PyErr_BadInternalCall();
1163 return -1;
1164 }
1165
1166 if (PyUnicode_READY(from))
1167 return -1;
1168 if (PyUnicode_READY(to))
1169 return -1;
1170
1171 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1172 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1173 PyErr_Format(PyExc_SystemError,
1174 "Cannot write %zi characters at %zi "
1175 "in a string of %zi characters",
1176 how_many, to_start, PyUnicode_GET_LENGTH(to));
1177 return -1;
1178 }
1179
1180 if (how_many == 0)
1181 return 0;
1182
1183 if (_PyUnicode_Dirty(to))
1184 return -1;
1185
1186 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1187 if (err) {
1188 PyErr_Format(PyExc_SystemError,
1189 "Cannot copy %s characters "
1190 "into a string of %s characters",
1191 unicode_kind_name(from),
1192 unicode_kind_name(to));
1193 return -1;
1194 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001195 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001196}
1197
Victor Stinner17222162011-09-28 22:15:37 +02001198/* Find the maximum code point and count the number of surrogate pairs so a
1199 correct string length can be computed before converting a string to UCS4.
1200 This function counts single surrogates as a character and not as a pair.
1201
1202 Return 0 on success, or -1 on error. */
1203static int
1204find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1205 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206{
1207 const wchar_t *iter;
1208
Victor Stinnerc53be962011-10-02 21:33:54 +02001209 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210 *num_surrogates = 0;
1211 *maxchar = 0;
1212
1213 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001214 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001215 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001216#if SIZEOF_WCHAR_T != 2
1217 if (*maxchar >= 0x10000)
1218 return 0;
1219#endif
1220 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001221#if SIZEOF_WCHAR_T == 2
1222 if (*iter >= 0xD800 && *iter <= 0xDBFF
1223 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1224 {
1225 Py_UCS4 surrogate_val;
1226 surrogate_val = (((iter[0] & 0x3FF)<<10)
1227 | (iter[1] & 0x3FF)) + 0x10000;
1228 ++(*num_surrogates);
1229 if (surrogate_val > *maxchar)
1230 *maxchar = surrogate_val;
1231 iter += 2;
1232 }
1233 else
1234 iter++;
1235#else
1236 iter++;
1237#endif
1238 }
1239 return 0;
1240}
1241
1242#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001243static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001244#endif
1245
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001246static int
1247unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001248{
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001249 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001250 wchar_t *end;
1251 Py_UCS4 maxchar = 0;
1252 Py_ssize_t num_surrogates;
1253#if SIZEOF_WCHAR_T == 2
1254 Py_ssize_t length_wo_surrogates;
1255#endif
1256
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001257 assert(p_obj != NULL);
1258 unicode = (PyUnicodeObject *)*p_obj;
1259
Georg Brandl7597add2011-10-05 16:36:47 +02001260 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001261 strings were created using _PyObject_New() and where no canonical
1262 representation (the str field) has been set yet aka strings
1263 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001264 assert(_PyUnicode_CHECK(unicode));
1265 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001266 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001267 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001268 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001269 /* Actually, it should neither be interned nor be anything else: */
1270 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001271
1272#ifdef Py_DEBUG
1273 ++unicode_ready_calls;
1274#endif
1275
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001276#ifdef Py_DEBUG
1277 assert(!replace || Py_REFCNT(unicode) == 1);
1278#else
1279 if (replace && Py_REFCNT(unicode) != 1)
1280 replace = 0;
1281#endif
1282 if (replace) {
1283 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1284 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1285 /* Optimization for empty strings */
1286 if (len == 0) {
1287 Py_INCREF(unicode_empty);
1288 Py_DECREF(*p_obj);
1289 *p_obj = unicode_empty;
1290 return 0;
1291 }
1292 if (len == 1 && wstr[0] < 256) {
1293 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1294 if (latin1_char == NULL)
1295 return -1;
1296 Py_DECREF(*p_obj);
1297 *p_obj = latin1_char;
1298 return 0;
1299 }
1300 }
1301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001302 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001303 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001304 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001305 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001306
1307 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001308 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1309 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001310 PyErr_NoMemory();
1311 return -1;
1312 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001313 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001314 _PyUnicode_WSTR(unicode), end,
1315 PyUnicode_1BYTE_DATA(unicode));
1316 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1317 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1318 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1319 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001320 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001321 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001322 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001323 }
1324 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001325 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001326 _PyUnicode_UTF8(unicode) = NULL;
1327 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328 }
1329 PyObject_FREE(_PyUnicode_WSTR(unicode));
1330 _PyUnicode_WSTR(unicode) = NULL;
1331 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1332 }
1333 /* In this case we might have to convert down from 4-byte native
1334 wchar_t to 2-byte unicode. */
1335 else if (maxchar < 65536) {
1336 assert(num_surrogates == 0 &&
1337 "FindMaxCharAndNumSurrogatePairs() messed up");
1338
Victor Stinner506f5922011-09-28 22:34:18 +02001339#if SIZEOF_WCHAR_T == 2
1340 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001341 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001342 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1343 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1344 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001345 _PyUnicode_UTF8(unicode) = NULL;
1346 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001347#else
1348 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001349 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001350 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyErr_NoMemory();
1353 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001354 }
Victor Stinner506f5922011-09-28 22:34:18 +02001355 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1356 _PyUnicode_WSTR(unicode), end,
1357 PyUnicode_2BYTE_DATA(unicode));
1358 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1359 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1360 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001361 _PyUnicode_UTF8(unicode) = NULL;
1362 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001363 PyObject_FREE(_PyUnicode_WSTR(unicode));
1364 _PyUnicode_WSTR(unicode) = NULL;
1365 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1366#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001367 }
1368 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1369 else {
1370#if SIZEOF_WCHAR_T == 2
1371 /* in case the native representation is 2-bytes, we need to allocate a
1372 new normalized 4-byte version. */
1373 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001374 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1375 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001376 PyErr_NoMemory();
1377 return -1;
1378 }
1379 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1380 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001381 _PyUnicode_UTF8(unicode) = NULL;
1382 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001383 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1384 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001385 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyObject_FREE(_PyUnicode_WSTR(unicode));
1387 _PyUnicode_WSTR(unicode) = NULL;
1388 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1389#else
1390 assert(num_surrogates == 0);
1391
Victor Stinnerc3c74152011-10-02 20:39:55 +02001392 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001393 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001394 _PyUnicode_UTF8(unicode) = NULL;
1395 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1397#endif
1398 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1399 }
1400 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001401 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001402 return 0;
1403}
1404
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001405int
1406_PyUnicode_ReadyReplace(PyObject **op)
1407{
1408 return unicode_ready(op, 1);
1409}
1410
1411int
1412_PyUnicode_Ready(PyObject *op)
1413{
1414 return unicode_ready(&op, 0);
1415}
1416
Alexander Belopolsky40018472011-02-26 01:02:56 +00001417static void
1418unicode_dealloc(register PyUnicodeObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001419{
Walter Dörwald16807132007-05-25 13:52:07 +00001420 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001421 case SSTATE_NOT_INTERNED:
1422 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001423
Benjamin Peterson29060642009-01-31 22:14:21 +00001424 case SSTATE_INTERNED_MORTAL:
1425 /* revive dead object temporarily for DelItem */
1426 Py_REFCNT(unicode) = 3;
1427 if (PyDict_DelItem(interned, (PyObject *)unicode) != 0)
1428 Py_FatalError(
1429 "deletion of interned string failed");
1430 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001431
Benjamin Peterson29060642009-01-31 22:14:21 +00001432 case SSTATE_INTERNED_IMMORTAL:
1433 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001434
Benjamin Peterson29060642009-01-31 22:14:21 +00001435 default:
1436 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001437 }
1438
Victor Stinner03490912011-10-03 23:45:12 +02001439 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001440 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001441 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001442 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001443
1444 if (PyUnicode_IS_COMPACT(unicode)) {
1445 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001446 }
1447 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001448 if (_PyUnicode_DATA_ANY(unicode))
1449 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Benjamin Peterson29060642009-01-31 22:14:21 +00001450 Py_TYPE(unicode)->tp_free((PyObject *)unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001451 }
1452}
1453
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001454#ifdef Py_DEBUG
1455static int
1456unicode_is_singleton(PyObject *unicode)
1457{
1458 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1459 if (unicode == unicode_empty)
1460 return 1;
1461 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1462 {
1463 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1464 if (ch < 256 && unicode_latin1[ch] == unicode)
1465 return 1;
1466 }
1467 return 0;
1468}
1469#endif
1470
Alexander Belopolsky40018472011-02-26 01:02:56 +00001471static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001472unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001473{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001474 if (Py_REFCNT(unicode) != 1)
1475 return 0;
1476 if (PyUnicode_CHECK_INTERNED(unicode))
1477 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001478#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001479 /* singleton refcount is greater than 1 */
1480 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001481#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482 return 1;
1483}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001484
Victor Stinnerfe226c02011-10-03 03:52:20 +02001485static int
1486unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1487{
1488 PyObject *unicode;
1489 Py_ssize_t old_length;
1490
1491 assert(p_unicode != NULL);
1492 unicode = *p_unicode;
1493
1494 assert(unicode != NULL);
1495 assert(PyUnicode_Check(unicode));
1496 assert(0 <= length);
1497
Victor Stinner910337b2011-10-03 03:20:16 +02001498 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001499 old_length = PyUnicode_WSTR_LENGTH(unicode);
1500 else
1501 old_length = PyUnicode_GET_LENGTH(unicode);
1502 if (old_length == length)
1503 return 0;
1504
Victor Stinnerfe226c02011-10-03 03:52:20 +02001505 if (!unicode_resizable(unicode)) {
1506 PyObject *copy = resize_copy(unicode, length);
1507 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001508 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 Py_DECREF(*p_unicode);
1510 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001511 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001512 }
1513
Victor Stinnerfe226c02011-10-03 03:52:20 +02001514 if (PyUnicode_IS_COMPACT(unicode)) {
1515 *p_unicode = resize_compact(unicode, length);
1516 if (*p_unicode == NULL)
1517 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001518 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001519 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001520 }
1521 return resize_inplace((PyUnicodeObject*)unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001522}
1523
Alexander Belopolsky40018472011-02-26 01:02:56 +00001524int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001525PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001526{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001527 PyObject *unicode;
1528 if (p_unicode == NULL) {
1529 PyErr_BadInternalCall();
1530 return -1;
1531 }
1532 unicode = *p_unicode;
1533 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0
1534 || _PyUnicode_KIND(unicode) != PyUnicode_WCHAR_KIND)
1535 {
1536 PyErr_BadInternalCall();
1537 return -1;
1538 }
1539 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001540}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001542static PyObject*
1543get_latin1_char(unsigned char ch)
1544{
Victor Stinnera464fc12011-10-02 20:39:30 +02001545 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001546 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001547 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001548 if (!unicode)
1549 return NULL;
1550 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001551 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001552 unicode_latin1[ch] = unicode;
1553 }
1554 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001555 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001556}
1557
Alexander Belopolsky40018472011-02-26 01:02:56 +00001558PyObject *
1559PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001560{
1561 PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001562 Py_UCS4 maxchar = 0;
1563 Py_ssize_t num_surrogates;
1564
1565 if (u == NULL)
1566 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001567
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001568 /* If the Unicode data is known at construction time, we can apply
1569 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001570
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001571 /* Optimization for empty strings */
1572 if (size == 0 && unicode_empty != NULL) {
1573 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001574 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001575 }
Tim Petersced69f82003-09-16 20:30:58 +00001576
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001577 /* Single character Unicode objects in the Latin-1 range are
1578 shared when using this constructor */
1579 if (size == 1 && *u < 256)
1580 return get_latin1_char((unsigned char)*u);
1581
1582 /* If not empty and not single character, copy the Unicode data
1583 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001584 if (find_maxchar_surrogates(u, u + size,
1585 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001586 return NULL;
1587
1588 unicode = (PyUnicodeObject *) PyUnicode_New(size - num_surrogates,
1589 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001590 if (!unicode)
1591 return NULL;
1592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001593 switch (PyUnicode_KIND(unicode)) {
1594 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001595 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001596 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1597 break;
1598 case PyUnicode_2BYTE_KIND:
1599#if Py_UNICODE_SIZE == 2
1600 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1601#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001602 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001603 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1604#endif
1605 break;
1606 case PyUnicode_4BYTE_KIND:
1607#if SIZEOF_WCHAR_T == 2
1608 /* This is the only case which has to process surrogates, thus
1609 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001610 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001611#else
1612 assert(num_surrogates == 0);
1613 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1614#endif
1615 break;
1616 default:
1617 assert(0 && "Impossible state");
1618 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001619
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001620 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00001621 return (PyObject *)unicode;
1622}
1623
Alexander Belopolsky40018472011-02-26 01:02:56 +00001624PyObject *
1625PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001626{
1627 PyUnicodeObject *unicode;
Christian Heimes33fe8092008-04-13 13:53:33 +00001628
Benjamin Peterson14339b62009-01-31 16:36:08 +00001629 if (size < 0) {
1630 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001631 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001632 return NULL;
1633 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001634
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001635 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001636 some optimizations which share commonly used objects.
1637 Also, this means the input must be UTF-8, so fall back to the
1638 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001639 if (u != NULL) {
1640
Benjamin Peterson29060642009-01-31 22:14:21 +00001641 /* Optimization for empty strings */
1642 if (size == 0 && unicode_empty != NULL) {
1643 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001644 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001645 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001646
1647 /* Single characters are shared when using this constructor.
1648 Restrict to ASCII, since the input must be UTF-8. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 if (size == 1 && Py_CHARMASK(*u) < 128)
1650 return get_latin1_char(Py_CHARMASK(*u));
Martin v. Löwis9c121062007-08-05 20:26:11 +00001651
1652 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001653 }
1654
Walter Dörwald55507312007-05-18 13:12:10 +00001655 unicode = _PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001656 if (!unicode)
1657 return NULL;
1658
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001659 return (PyObject *)unicode;
1660}
1661
Alexander Belopolsky40018472011-02-26 01:02:56 +00001662PyObject *
1663PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001664{
1665 size_t size = strlen(u);
1666 if (size > PY_SSIZE_T_MAX) {
1667 PyErr_SetString(PyExc_OverflowError, "input too long");
1668 return NULL;
1669 }
1670
1671 return PyUnicode_FromStringAndSize(u, size);
1672}
1673
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001674PyObject *
1675_PyUnicode_FromId(_Py_Identifier *id)
1676{
1677 if (!id->object) {
1678 id->object = PyUnicode_FromString(id->string);
1679 if (!id->object)
1680 return NULL;
1681 PyUnicode_InternInPlace(&id->object);
1682 assert(!id->next);
1683 id->next = static_strings;
1684 static_strings = id;
1685 }
1686 Py_INCREF(id->object);
1687 return id->object;
1688}
1689
1690void
1691_PyUnicode_ClearStaticStrings()
1692{
1693 _Py_Identifier *i;
1694 for (i = static_strings; i; i = i->next) {
1695 Py_DECREF(i->object);
1696 i->object = NULL;
1697 i->next = NULL;
1698 }
1699}
1700
Victor Stinnere57b1c02011-09-28 22:20:48 +02001701static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001702unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001703{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001704 PyObject *res;
1705#ifdef Py_DEBUG
1706 const unsigned char *p;
1707 const unsigned char *end = s + size;
1708 for (p=s; p < end; p++) {
1709 assert(*p < 128);
1710 }
1711#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001712 if (size == 1)
1713 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001714 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001715 if (!res)
1716 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001717 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001718 return res;
1719}
1720
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001721static Py_UCS4
1722kind_maxchar_limit(unsigned int kind)
1723{
1724 switch(kind) {
1725 case PyUnicode_1BYTE_KIND:
1726 return 0x80;
1727 case PyUnicode_2BYTE_KIND:
1728 return 0x100;
1729 case PyUnicode_4BYTE_KIND:
1730 return 0x10000;
1731 default:
1732 assert(0 && "invalid kind");
1733 return 0x10ffff;
1734 }
1735}
1736
Victor Stinner702c7342011-10-05 13:50:52 +02001737static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001738_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001739{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001740 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001741 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001742
1743 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001744 if (size == 1)
1745 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001746 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001747 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001748 if (!res)
1749 return NULL;
1750 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001751 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001752 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001753}
1754
Victor Stinnere57b1c02011-09-28 22:20:48 +02001755static PyObject*
1756_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001757{
1758 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001759 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001760
1761 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001762 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001763 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001764 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001765 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001766 if (!res)
1767 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001768 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001769 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001770 else {
1771 _PyUnicode_CONVERT_BYTES(
1772 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1773 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001774 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001775 return res;
1776}
1777
Victor Stinnere57b1c02011-09-28 22:20:48 +02001778static PyObject*
1779_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001780{
1781 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001782 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001783
1784 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001785 if (size == 1 && u[0] < 256)
1786 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001787 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001788 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001789 if (!res)
1790 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001791 if (max_char < 256)
1792 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1793 PyUnicode_1BYTE_DATA(res));
1794 else if (max_char < 0x10000)
1795 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1796 PyUnicode_2BYTE_DATA(res));
1797 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001798 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001799 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800 return res;
1801}
1802
1803PyObject*
1804PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1805{
1806 switch(kind) {
1807 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001808 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001810 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001811 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001812 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001813 default:
1814 assert(0 && "invalid kind");
1815 PyErr_SetString(PyExc_SystemError, "invalid kind");
1816 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001817 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818}
1819
Victor Stinner25a4b292011-10-06 12:31:55 +02001820/* Ensure that a string uses the most efficient storage, if it is not the
1821 case: create a new string with of the right kind. Write NULL into *p_unicode
1822 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001823static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001824unicode_adjust_maxchar(PyObject **p_unicode)
1825{
1826 PyObject *unicode, *copy;
1827 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001828 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001829 unsigned int kind;
1830
1831 assert(p_unicode != NULL);
1832 unicode = *p_unicode;
1833 assert(PyUnicode_IS_READY(unicode));
1834 if (PyUnicode_IS_ASCII(unicode))
1835 return;
1836
1837 len = PyUnicode_GET_LENGTH(unicode);
1838 kind = PyUnicode_KIND(unicode);
1839 if (kind == PyUnicode_1BYTE_KIND) {
1840 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001841 max_char = ucs1lib_find_max_char(u, u + len);
1842 if (max_char >= 128)
1843 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001844 }
1845 else if (kind == PyUnicode_2BYTE_KIND) {
1846 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001847 max_char = ucs2lib_find_max_char(u, u + len);
1848 if (max_char >= 256)
1849 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001850 }
1851 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001852 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001853 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001854 max_char = ucs4lib_find_max_char(u, u + len);
1855 if (max_char >= 0x10000)
1856 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001857 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001858 copy = PyUnicode_New(len, max_char);
1859 copy_characters(copy, 0, unicode, 0, len);
1860 Py_DECREF(unicode);
1861 *p_unicode = copy;
1862}
1863
Victor Stinner034f6cf2011-09-30 02:26:44 +02001864PyObject*
1865PyUnicode_Copy(PyObject *unicode)
1866{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001867 Py_ssize_t size;
1868 PyObject *copy;
1869 void *data;
1870
Victor Stinner034f6cf2011-09-30 02:26:44 +02001871 if (!PyUnicode_Check(unicode)) {
1872 PyErr_BadInternalCall();
1873 return NULL;
1874 }
1875 if (PyUnicode_READY(unicode))
1876 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001877
1878 size = PyUnicode_GET_LENGTH(unicode);
1879 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1880 if (!copy)
1881 return NULL;
1882 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1883
1884 data = PyUnicode_DATA(unicode);
1885 switch (PyUnicode_KIND(unicode))
1886 {
1887 case PyUnicode_1BYTE_KIND:
1888 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1889 break;
1890 case PyUnicode_2BYTE_KIND:
1891 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1892 break;
1893 case PyUnicode_4BYTE_KIND:
1894 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1895 break;
1896 default:
1897 assert(0);
1898 break;
1899 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001900 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001901 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001902}
1903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001904
Victor Stinnerbc603d12011-10-02 01:00:40 +02001905/* Widen Unicode objects to larger buffers. Don't write terminating null
1906 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001907
1908void*
1909_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1910{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001911 Py_ssize_t len;
1912 void *result;
1913 unsigned int skind;
1914
1915 if (PyUnicode_READY(s))
1916 return NULL;
1917
1918 len = PyUnicode_GET_LENGTH(s);
1919 skind = PyUnicode_KIND(s);
1920 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001921 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001922 return NULL;
1923 }
1924 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001925 case PyUnicode_2BYTE_KIND:
1926 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1927 if (!result)
1928 return PyErr_NoMemory();
1929 assert(skind == PyUnicode_1BYTE_KIND);
1930 _PyUnicode_CONVERT_BYTES(
1931 Py_UCS1, Py_UCS2,
1932 PyUnicode_1BYTE_DATA(s),
1933 PyUnicode_1BYTE_DATA(s) + len,
1934 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001935 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001936 case PyUnicode_4BYTE_KIND:
1937 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1938 if (!result)
1939 return PyErr_NoMemory();
1940 if (skind == PyUnicode_2BYTE_KIND) {
1941 _PyUnicode_CONVERT_BYTES(
1942 Py_UCS2, Py_UCS4,
1943 PyUnicode_2BYTE_DATA(s),
1944 PyUnicode_2BYTE_DATA(s) + len,
1945 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001947 else {
1948 assert(skind == PyUnicode_1BYTE_KIND);
1949 _PyUnicode_CONVERT_BYTES(
1950 Py_UCS1, Py_UCS4,
1951 PyUnicode_1BYTE_DATA(s),
1952 PyUnicode_1BYTE_DATA(s) + len,
1953 result);
1954 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001955 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001956 default:
1957 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001958 }
Victor Stinner01698042011-10-04 00:04:26 +02001959 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001960 return NULL;
1961}
1962
1963static Py_UCS4*
1964as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
1965 int copy_null)
1966{
1967 int kind;
1968 void *data;
1969 Py_ssize_t len, targetlen;
1970 if (PyUnicode_READY(string) == -1)
1971 return NULL;
1972 kind = PyUnicode_KIND(string);
1973 data = PyUnicode_DATA(string);
1974 len = PyUnicode_GET_LENGTH(string);
1975 targetlen = len;
1976 if (copy_null)
1977 targetlen++;
1978 if (!target) {
1979 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
1980 PyErr_NoMemory();
1981 return NULL;
1982 }
1983 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
1984 if (!target) {
1985 PyErr_NoMemory();
1986 return NULL;
1987 }
1988 }
1989 else {
1990 if (targetsize < targetlen) {
1991 PyErr_Format(PyExc_SystemError,
1992 "string is longer than the buffer");
1993 if (copy_null && 0 < targetsize)
1994 target[0] = 0;
1995 return NULL;
1996 }
1997 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02001998 if (kind == PyUnicode_1BYTE_KIND) {
1999 Py_UCS1 *start = (Py_UCS1 *) data;
2000 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002002 else if (kind == PyUnicode_2BYTE_KIND) {
2003 Py_UCS2 *start = (Py_UCS2 *) data;
2004 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2005 }
2006 else {
2007 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002008 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002009 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002010 if (copy_null)
2011 target[len] = 0;
2012 return target;
2013}
2014
2015Py_UCS4*
2016PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2017 int copy_null)
2018{
2019 if (target == NULL || targetsize < 1) {
2020 PyErr_BadInternalCall();
2021 return NULL;
2022 }
2023 return as_ucs4(string, target, targetsize, copy_null);
2024}
2025
2026Py_UCS4*
2027PyUnicode_AsUCS4Copy(PyObject *string)
2028{
2029 return as_ucs4(string, NULL, 0, 1);
2030}
2031
2032#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002033
Alexander Belopolsky40018472011-02-26 01:02:56 +00002034PyObject *
2035PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002036{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002037 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002038 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002039 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002040 PyErr_BadInternalCall();
2041 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002042 }
2043
Martin v. Löwis790465f2008-04-05 20:41:37 +00002044 if (size == -1) {
2045 size = wcslen(w);
2046 }
2047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002049}
2050
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002051#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002052
Walter Dörwald346737f2007-05-31 10:44:43 +00002053static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002054makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2055 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002056{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002057 *fmt++ = '%';
2058 if (width) {
2059 if (zeropad)
2060 *fmt++ = '0';
2061 fmt += sprintf(fmt, "%d", width);
2062 }
2063 if (precision)
2064 fmt += sprintf(fmt, ".%d", precision);
2065 if (longflag)
2066 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002067 else if (longlongflag) {
2068 /* longlongflag should only ever be nonzero on machines with
2069 HAVE_LONG_LONG defined */
2070#ifdef HAVE_LONG_LONG
2071 char *f = PY_FORMAT_LONG_LONG;
2072 while (*f)
2073 *fmt++ = *f++;
2074#else
2075 /* we shouldn't ever get here */
2076 assert(0);
2077 *fmt++ = 'l';
2078#endif
2079 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002080 else if (size_tflag) {
2081 char *f = PY_FORMAT_SIZE_T;
2082 while (*f)
2083 *fmt++ = *f++;
2084 }
2085 *fmt++ = c;
2086 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002087}
2088
Victor Stinner96865452011-03-01 23:44:09 +00002089/* helper for PyUnicode_FromFormatV() */
2090
2091static const char*
2092parse_format_flags(const char *f,
2093 int *p_width, int *p_precision,
2094 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2095{
2096 int width, precision, longflag, longlongflag, size_tflag;
2097
2098 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2099 f++;
2100 width = 0;
2101 while (Py_ISDIGIT((unsigned)*f))
2102 width = (width*10) + *f++ - '0';
2103 precision = 0;
2104 if (*f == '.') {
2105 f++;
2106 while (Py_ISDIGIT((unsigned)*f))
2107 precision = (precision*10) + *f++ - '0';
2108 if (*f == '%') {
2109 /* "%.3%s" => f points to "3" */
2110 f--;
2111 }
2112 }
2113 if (*f == '\0') {
2114 /* bogus format "%.1" => go backward, f points to "1" */
2115 f--;
2116 }
2117 if (p_width != NULL)
2118 *p_width = width;
2119 if (p_precision != NULL)
2120 *p_precision = precision;
2121
2122 /* Handle %ld, %lu, %lld and %llu. */
2123 longflag = 0;
2124 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002125 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002126
2127 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002128 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002129 longflag = 1;
2130 ++f;
2131 }
2132#ifdef HAVE_LONG_LONG
2133 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002134 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002135 longlongflag = 1;
2136 f += 2;
2137 }
2138#endif
2139 }
2140 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002141 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002142 size_tflag = 1;
2143 ++f;
2144 }
2145 if (p_longflag != NULL)
2146 *p_longflag = longflag;
2147 if (p_longlongflag != NULL)
2148 *p_longlongflag = longlongflag;
2149 if (p_size_tflag != NULL)
2150 *p_size_tflag = size_tflag;
2151 return f;
2152}
2153
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002154/* maximum number of characters required for output of %ld. 21 characters
2155 allows for 64-bit integers (in decimal) and an optional sign. */
2156#define MAX_LONG_CHARS 21
2157/* maximum number of characters required for output of %lld.
2158 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2159 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2160#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2161
Walter Dörwaldd2034312007-05-18 16:29:38 +00002162PyObject *
2163PyUnicode_FromFormatV(const char *format, va_list vargs)
2164{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002165 va_list count;
2166 Py_ssize_t callcount = 0;
2167 PyObject **callresults = NULL;
2168 PyObject **callresult = NULL;
2169 Py_ssize_t n = 0;
2170 int width = 0;
2171 int precision = 0;
2172 int zeropad;
2173 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002174 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002175 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002176 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002177 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2178 Py_UCS4 argmaxchar;
2179 Py_ssize_t numbersize = 0;
2180 char *numberresults = NULL;
2181 char *numberresult = NULL;
2182 Py_ssize_t i;
2183 int kind;
2184 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002185
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002186 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002187 /* step 1: count the number of %S/%R/%A/%s format specifications
2188 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2189 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002190 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002191 * also estimate a upper bound for all the number formats in the string,
2192 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002193 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002194 for (f = format; *f; f++) {
2195 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002196 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002197 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2198 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2199 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2200 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002201
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002202 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002203#ifdef HAVE_LONG_LONG
2204 if (longlongflag) {
2205 if (width < MAX_LONG_LONG_CHARS)
2206 width = MAX_LONG_LONG_CHARS;
2207 }
2208 else
2209#endif
2210 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2211 including sign. Decimal takes the most space. This
2212 isn't enough for octal. If a width is specified we
2213 need more (which we allocate later). */
2214 if (width < MAX_LONG_CHARS)
2215 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216
2217 /* account for the size + '\0' to separate numbers
2218 inside of the numberresults buffer */
2219 numbersize += (width + 1);
2220 }
2221 }
2222 else if ((unsigned char)*f > 127) {
2223 PyErr_Format(PyExc_ValueError,
2224 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2225 "string, got a non-ASCII byte: 0x%02x",
2226 (unsigned char)*f);
2227 return NULL;
2228 }
2229 }
2230 /* step 2: allocate memory for the results of
2231 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2232 if (callcount) {
2233 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2234 if (!callresults) {
2235 PyErr_NoMemory();
2236 return NULL;
2237 }
2238 callresult = callresults;
2239 }
2240 /* step 2.5: allocate memory for the results of formating numbers */
2241 if (numbersize) {
2242 numberresults = PyObject_Malloc(numbersize);
2243 if (!numberresults) {
2244 PyErr_NoMemory();
2245 goto fail;
2246 }
2247 numberresult = numberresults;
2248 }
2249
2250 /* step 3: format numbers and figure out how large a buffer we need */
2251 for (f = format; *f; f++) {
2252 if (*f == '%') {
2253 const char* p;
2254 int longflag;
2255 int longlongflag;
2256 int size_tflag;
2257 int numprinted;
2258
2259 p = f;
2260 zeropad = (f[1] == '0');
2261 f = parse_format_flags(f, &width, &precision,
2262 &longflag, &longlongflag, &size_tflag);
2263 switch (*f) {
2264 case 'c':
2265 {
2266 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002267 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002268 n++;
2269 break;
2270 }
2271 case '%':
2272 n++;
2273 break;
2274 case 'i':
2275 case 'd':
2276 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2277 width, precision, *f);
2278 if (longflag)
2279 numprinted = sprintf(numberresult, fmt,
2280 va_arg(count, long));
2281#ifdef HAVE_LONG_LONG
2282 else if (longlongflag)
2283 numprinted = sprintf(numberresult, fmt,
2284 va_arg(count, PY_LONG_LONG));
2285#endif
2286 else if (size_tflag)
2287 numprinted = sprintf(numberresult, fmt,
2288 va_arg(count, Py_ssize_t));
2289 else
2290 numprinted = sprintf(numberresult, fmt,
2291 va_arg(count, int));
2292 n += numprinted;
2293 /* advance by +1 to skip over the '\0' */
2294 numberresult += (numprinted + 1);
2295 assert(*(numberresult - 1) == '\0');
2296 assert(*(numberresult - 2) != '\0');
2297 assert(numprinted >= 0);
2298 assert(numberresult <= numberresults + numbersize);
2299 break;
2300 case 'u':
2301 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2302 width, precision, 'u');
2303 if (longflag)
2304 numprinted = sprintf(numberresult, fmt,
2305 va_arg(count, unsigned long));
2306#ifdef HAVE_LONG_LONG
2307 else if (longlongflag)
2308 numprinted = sprintf(numberresult, fmt,
2309 va_arg(count, unsigned PY_LONG_LONG));
2310#endif
2311 else if (size_tflag)
2312 numprinted = sprintf(numberresult, fmt,
2313 va_arg(count, size_t));
2314 else
2315 numprinted = sprintf(numberresult, fmt,
2316 va_arg(count, unsigned int));
2317 n += numprinted;
2318 numberresult += (numprinted + 1);
2319 assert(*(numberresult - 1) == '\0');
2320 assert(*(numberresult - 2) != '\0');
2321 assert(numprinted >= 0);
2322 assert(numberresult <= numberresults + numbersize);
2323 break;
2324 case 'x':
2325 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2326 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2327 n += numprinted;
2328 numberresult += (numprinted + 1);
2329 assert(*(numberresult - 1) == '\0');
2330 assert(*(numberresult - 2) != '\0');
2331 assert(numprinted >= 0);
2332 assert(numberresult <= numberresults + numbersize);
2333 break;
2334 case 'p':
2335 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2336 /* %p is ill-defined: ensure leading 0x. */
2337 if (numberresult[1] == 'X')
2338 numberresult[1] = 'x';
2339 else if (numberresult[1] != 'x') {
2340 memmove(numberresult + 2, numberresult,
2341 strlen(numberresult) + 1);
2342 numberresult[0] = '0';
2343 numberresult[1] = 'x';
2344 numprinted += 2;
2345 }
2346 n += numprinted;
2347 numberresult += (numprinted + 1);
2348 assert(*(numberresult - 1) == '\0');
2349 assert(*(numberresult - 2) != '\0');
2350 assert(numprinted >= 0);
2351 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002352 break;
2353 case 's':
2354 {
2355 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002356 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002357 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2358 if (!str)
2359 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002360 /* since PyUnicode_DecodeUTF8 returns already flexible
2361 unicode objects, there is no need to call ready on them */
2362 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002363 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002364 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002365 /* Remember the str and switch to the next slot */
2366 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002367 break;
2368 }
2369 case 'U':
2370 {
2371 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002372 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002373 if (PyUnicode_READY(obj) == -1)
2374 goto fail;
2375 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002376 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002377 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002378 break;
2379 }
2380 case 'V':
2381 {
2382 PyObject *obj = va_arg(count, PyObject *);
2383 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002384 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002385 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002386 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002387 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002388 if (PyUnicode_READY(obj) == -1)
2389 goto fail;
2390 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002391 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002392 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002393 *callresult++ = NULL;
2394 }
2395 else {
2396 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2397 if (!str_obj)
2398 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002399 if (PyUnicode_READY(str_obj)) {
2400 Py_DECREF(str_obj);
2401 goto fail;
2402 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002404 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002405 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002406 *callresult++ = str_obj;
2407 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002408 break;
2409 }
2410 case 'S':
2411 {
2412 PyObject *obj = va_arg(count, PyObject *);
2413 PyObject *str;
2414 assert(obj);
2415 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002417 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002418 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002419 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002421 /* Remember the str and switch to the next slot */
2422 *callresult++ = str;
2423 break;
2424 }
2425 case 'R':
2426 {
2427 PyObject *obj = va_arg(count, PyObject *);
2428 PyObject *repr;
2429 assert(obj);
2430 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002432 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002434 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002436 /* Remember the repr and switch to the next slot */
2437 *callresult++ = repr;
2438 break;
2439 }
2440 case 'A':
2441 {
2442 PyObject *obj = va_arg(count, PyObject *);
2443 PyObject *ascii;
2444 assert(obj);
2445 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002446 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002449 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002450 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002451 /* Remember the repr and switch to the next slot */
2452 *callresult++ = ascii;
2453 break;
2454 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002455 default:
2456 /* if we stumble upon an unknown
2457 formatting code, copy the rest of
2458 the format string to the output
2459 string. (we cannot just skip the
2460 code, since there's no way to know
2461 what's in the argument list) */
2462 n += strlen(p);
2463 goto expand;
2464 }
2465 } else
2466 n++;
2467 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002468 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002469 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 we don't have to resize the string.
2472 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002473 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002474 if (!string)
2475 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002476 kind = PyUnicode_KIND(string);
2477 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002478 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002479 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002480
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002481 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002482 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002483 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002484
2485 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002486 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2487 /* checking for == because the last argument could be a empty
2488 string, which causes i to point to end, the assert at the end of
2489 the loop */
2490 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002491
Benjamin Peterson14339b62009-01-31 16:36:08 +00002492 switch (*f) {
2493 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002494 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002495 const int ordinal = va_arg(vargs, int);
2496 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002497 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002498 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002499 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002500 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002501 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002502 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002503 case 'p':
2504 /* unused, since we already have the result */
2505 if (*f == 'p')
2506 (void) va_arg(vargs, void *);
2507 else
2508 (void) va_arg(vargs, int);
2509 /* extract the result from numberresults and append. */
2510 for (; *numberresult; ++i, ++numberresult)
2511 PyUnicode_WRITE(kind, data, i, *numberresult);
2512 /* skip over the separating '\0' */
2513 assert(*numberresult == '\0');
2514 numberresult++;
2515 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002516 break;
2517 case 's':
2518 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002519 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002521 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 size = PyUnicode_GET_LENGTH(*callresult);
2523 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002524 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002526 /* We're done with the unicode()/repr() => forget it */
2527 Py_DECREF(*callresult);
2528 /* switch to next unicode()/repr() result */
2529 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002530 break;
2531 }
2532 case 'U':
2533 {
2534 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 Py_ssize_t size;
2536 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2537 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002538 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002539 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 break;
2541 }
2542 case 'V':
2543 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002544 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002545 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002546 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002547 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002548 size = PyUnicode_GET_LENGTH(obj);
2549 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002550 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002551 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002552 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002553 size = PyUnicode_GET_LENGTH(*callresult);
2554 assert(PyUnicode_KIND(*callresult) <=
2555 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002556 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002557 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002558 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002560 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002561 break;
2562 }
2563 case 'S':
2564 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002565 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002566 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002567 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002568 /* unused, since we already have the result */
2569 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002570 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002571 copy_characters(string, i, *callresult, 0, size);
2572 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002573 /* We're done with the unicode()/repr() => forget it */
2574 Py_DECREF(*callresult);
2575 /* switch to next unicode()/repr() result */
2576 ++callresult;
2577 break;
2578 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002579 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002580 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002581 break;
2582 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 for (; *p; ++p, ++i)
2584 PyUnicode_WRITE(kind, data, i, *p);
2585 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 goto end;
2587 }
Victor Stinner1205f272010-09-11 00:54:47 +00002588 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002589 else {
2590 assert(i < PyUnicode_GET_LENGTH(string));
2591 PyUnicode_WRITE(kind, data, i++, *f);
2592 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002593 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002594 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002595
Benjamin Peterson29060642009-01-31 22:14:21 +00002596 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002597 if (callresults)
2598 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002599 if (numberresults)
2600 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002601 assert(_PyUnicode_CheckConsistency(string, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002602 return (PyObject *)string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002603 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 if (callresults) {
2605 PyObject **callresult2 = callresults;
2606 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002607 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002608 ++callresult2;
2609 }
2610 PyObject_Free(callresults);
2611 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002612 if (numberresults)
2613 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002614 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002615}
2616
Walter Dörwaldd2034312007-05-18 16:29:38 +00002617PyObject *
2618PyUnicode_FromFormat(const char *format, ...)
2619{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 PyObject* ret;
2621 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002622
2623#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002624 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002625#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002626 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002627#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002628 ret = PyUnicode_FromFormatV(format, vargs);
2629 va_end(vargs);
2630 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002631}
2632
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633#ifdef HAVE_WCHAR_H
2634
Victor Stinner5593d8a2010-10-02 11:11:27 +00002635/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2636 convert a Unicode object to a wide character string.
2637
Victor Stinnerd88d9832011-09-06 02:00:05 +02002638 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002639 character) required to convert the unicode object. Ignore size argument.
2640
Victor Stinnerd88d9832011-09-06 02:00:05 +02002641 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002642 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002643 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002644static Py_ssize_t
Victor Stinner137c34c2010-09-29 10:25:54 +00002645unicode_aswidechar(PyUnicodeObject *unicode,
2646 wchar_t *w,
2647 Py_ssize_t size)
2648{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002649 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002650 const wchar_t *wstr;
2651
2652 wstr = PyUnicode_AsUnicodeAndSize((PyObject *)unicode, &res);
2653 if (wstr == NULL)
2654 return -1;
2655
Victor Stinner5593d8a2010-10-02 11:11:27 +00002656 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002657 if (size > res)
2658 size = res + 1;
2659 else
2660 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002661 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002662 return res;
2663 }
2664 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002665 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002666}
2667
2668Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002669PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002670 wchar_t *w,
2671 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002672{
2673 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002674 PyErr_BadInternalCall();
2675 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002676 }
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002677 return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002678}
2679
Victor Stinner137c34c2010-09-29 10:25:54 +00002680wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002681PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002682 Py_ssize_t *size)
2683{
2684 wchar_t* buffer;
2685 Py_ssize_t buflen;
2686
2687 if (unicode == NULL) {
2688 PyErr_BadInternalCall();
2689 return NULL;
2690 }
2691
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002692 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002693 if (buflen == -1)
2694 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002695 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002696 PyErr_NoMemory();
2697 return NULL;
2698 }
2699
Victor Stinner137c34c2010-09-29 10:25:54 +00002700 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2701 if (buffer == NULL) {
2702 PyErr_NoMemory();
2703 return NULL;
2704 }
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002705 buflen = unicode_aswidechar((PyUnicodeObject *)unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002706 if (buflen == -1)
2707 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002708 if (size != NULL)
2709 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002710 return buffer;
2711}
2712
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002713#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002714
Alexander Belopolsky40018472011-02-26 01:02:56 +00002715PyObject *
2716PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002717{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002718 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002719 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002720 PyErr_SetString(PyExc_ValueError,
2721 "chr() arg not in range(0x110000)");
2722 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002723 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002725 if (ordinal < 256)
2726 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002727
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002728 v = PyUnicode_New(1, ordinal);
2729 if (v == NULL)
2730 return NULL;
2731 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002732 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002733 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002734}
2735
Alexander Belopolsky40018472011-02-26 01:02:56 +00002736PyObject *
2737PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002738{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002739 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002740 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002741 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002742 if (PyUnicode_READY(obj))
2743 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002744 Py_INCREF(obj);
2745 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002746 }
2747 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002748 /* For a Unicode subtype that's not a Unicode object,
2749 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002750 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002751 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002752 PyErr_Format(PyExc_TypeError,
2753 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002754 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002755 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002756}
2757
Alexander Belopolsky40018472011-02-26 01:02:56 +00002758PyObject *
2759PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002760 const char *encoding,
2761 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002762{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002763 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002764 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002765
Guido van Rossumd57fd912000-03-10 22:53:23 +00002766 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002767 PyErr_BadInternalCall();
2768 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002769 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002770
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002771 /* Decoding bytes objects is the most common case and should be fast */
2772 if (PyBytes_Check(obj)) {
2773 if (PyBytes_GET_SIZE(obj) == 0) {
2774 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002775 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002776 }
2777 else {
2778 v = PyUnicode_Decode(
2779 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2780 encoding, errors);
2781 }
2782 return v;
2783 }
2784
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002785 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002786 PyErr_SetString(PyExc_TypeError,
2787 "decoding str is not supported");
2788 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002789 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002790
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002791 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2792 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2793 PyErr_Format(PyExc_TypeError,
2794 "coercing to str: need bytes, bytearray "
2795 "or buffer-like object, %.80s found",
2796 Py_TYPE(obj)->tp_name);
2797 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002798 }
Tim Petersced69f82003-09-16 20:30:58 +00002799
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002800 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002801 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002802 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002803 }
Tim Petersced69f82003-09-16 20:30:58 +00002804 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002805 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002806
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002807 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002808 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809}
2810
Victor Stinner600d3be2010-06-10 12:00:55 +00002811/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002812 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2813 1 on success. */
2814static int
2815normalize_encoding(const char *encoding,
2816 char *lower,
2817 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002818{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002819 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002820 char *l;
2821 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002822
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002823 if (encoding == NULL) {
2824 strcpy(lower, "utf-8");
2825 return 1;
2826 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002827 e = encoding;
2828 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002829 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002830 while (*e) {
2831 if (l == l_end)
2832 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002833 if (Py_ISUPPER(*e)) {
2834 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002835 }
2836 else if (*e == '_') {
2837 *l++ = '-';
2838 e++;
2839 }
2840 else {
2841 *l++ = *e++;
2842 }
2843 }
2844 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002845 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002846}
2847
Alexander Belopolsky40018472011-02-26 01:02:56 +00002848PyObject *
2849PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002850 Py_ssize_t size,
2851 const char *encoding,
2852 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002853{
2854 PyObject *buffer = NULL, *unicode;
2855 Py_buffer info;
2856 char lower[11]; /* Enough for any encoding shortcut */
2857
Fred Drakee4315f52000-05-09 19:53:39 +00002858 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002859 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002860 if ((strcmp(lower, "utf-8") == 0) ||
2861 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002862 return PyUnicode_DecodeUTF8(s, size, errors);
2863 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002864 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002865 (strcmp(lower, "iso-8859-1") == 0))
2866 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002867#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002868 else if (strcmp(lower, "mbcs") == 0)
2869 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002870#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002871 else if (strcmp(lower, "ascii") == 0)
2872 return PyUnicode_DecodeASCII(s, size, errors);
2873 else if (strcmp(lower, "utf-16") == 0)
2874 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2875 else if (strcmp(lower, "utf-32") == 0)
2876 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2877 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002878
2879 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002880 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002881 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002882 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002883 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002884 if (buffer == NULL)
2885 goto onError;
2886 unicode = PyCodec_Decode(buffer, encoding, errors);
2887 if (unicode == NULL)
2888 goto onError;
2889 if (!PyUnicode_Check(unicode)) {
2890 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002891 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002892 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002893 Py_DECREF(unicode);
2894 goto onError;
2895 }
2896 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002897#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002898 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002899 Py_DECREF(unicode);
2900 return NULL;
2901 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002902#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002903 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002904 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002905
Benjamin Peterson29060642009-01-31 22:14:21 +00002906 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002907 Py_XDECREF(buffer);
2908 return NULL;
2909}
2910
Alexander Belopolsky40018472011-02-26 01:02:56 +00002911PyObject *
2912PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002913 const char *encoding,
2914 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002915{
2916 PyObject *v;
2917
2918 if (!PyUnicode_Check(unicode)) {
2919 PyErr_BadArgument();
2920 goto onError;
2921 }
2922
2923 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002924 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002925
2926 /* Decode via the codec registry */
2927 v = PyCodec_Decode(unicode, encoding, errors);
2928 if (v == NULL)
2929 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002930 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002931 return v;
2932
Benjamin Peterson29060642009-01-31 22:14:21 +00002933 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002934 return NULL;
2935}
2936
Alexander Belopolsky40018472011-02-26 01:02:56 +00002937PyObject *
2938PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002939 const char *encoding,
2940 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002941{
2942 PyObject *v;
2943
2944 if (!PyUnicode_Check(unicode)) {
2945 PyErr_BadArgument();
2946 goto onError;
2947 }
2948
2949 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002950 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002951
2952 /* Decode via the codec registry */
2953 v = PyCodec_Decode(unicode, encoding, errors);
2954 if (v == NULL)
2955 goto onError;
2956 if (!PyUnicode_Check(v)) {
2957 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002958 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002959 Py_TYPE(v)->tp_name);
2960 Py_DECREF(v);
2961 goto onError;
2962 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002963 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002964 return v;
2965
Benjamin Peterson29060642009-01-31 22:14:21 +00002966 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002967 return NULL;
2968}
2969
Alexander Belopolsky40018472011-02-26 01:02:56 +00002970PyObject *
2971PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002972 Py_ssize_t size,
2973 const char *encoding,
2974 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002975{
2976 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002977
Guido van Rossumd57fd912000-03-10 22:53:23 +00002978 unicode = PyUnicode_FromUnicode(s, size);
2979 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002980 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002981 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
2982 Py_DECREF(unicode);
2983 return v;
2984}
2985
Alexander Belopolsky40018472011-02-26 01:02:56 +00002986PyObject *
2987PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002988 const char *encoding,
2989 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002990{
2991 PyObject *v;
2992
2993 if (!PyUnicode_Check(unicode)) {
2994 PyErr_BadArgument();
2995 goto onError;
2996 }
2997
2998 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002999 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003000
3001 /* Encode via the codec registry */
3002 v = PyCodec_Encode(unicode, encoding, errors);
3003 if (v == NULL)
3004 goto onError;
3005 return v;
3006
Benjamin Peterson29060642009-01-31 22:14:21 +00003007 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003008 return NULL;
3009}
3010
Victor Stinnerad158722010-10-27 00:25:46 +00003011PyObject *
3012PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003013{
Victor Stinner99b95382011-07-04 14:23:54 +02003014#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003015 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3016 PyUnicode_GET_SIZE(unicode),
3017 NULL);
3018#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003019 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003020#else
Victor Stinner793b5312011-04-27 00:24:21 +02003021 PyInterpreterState *interp = PyThreadState_GET()->interp;
3022 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3023 cannot use it to encode and decode filenames before it is loaded. Load
3024 the Python codec requires to encode at least its own filename. Use the C
3025 version of the locale codec until the codec registry is initialized and
3026 the Python codec is loaded.
3027
3028 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3029 cannot only rely on it: check also interp->fscodec_initialized for
3030 subinterpreters. */
3031 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003032 return PyUnicode_AsEncodedString(unicode,
3033 Py_FileSystemDefaultEncoding,
3034 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003035 }
3036 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003037 /* locale encoding with surrogateescape */
3038 wchar_t *wchar;
3039 char *bytes;
3040 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003041 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003042
3043 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3044 if (wchar == NULL)
3045 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003046 bytes = _Py_wchar2char(wchar, &error_pos);
3047 if (bytes == NULL) {
3048 if (error_pos != (size_t)-1) {
3049 char *errmsg = strerror(errno);
3050 PyObject *exc = NULL;
3051 if (errmsg == NULL)
3052 errmsg = "Py_wchar2char() failed";
3053 raise_encode_exception(&exc,
3054 "filesystemencoding",
3055 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
3056 error_pos, error_pos+1,
3057 errmsg);
3058 Py_XDECREF(exc);
3059 }
3060 else
3061 PyErr_NoMemory();
3062 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003063 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003064 }
3065 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003066
3067 bytes_obj = PyBytes_FromString(bytes);
3068 PyMem_Free(bytes);
3069 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003070 }
Victor Stinnerad158722010-10-27 00:25:46 +00003071#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003072}
3073
Alexander Belopolsky40018472011-02-26 01:02:56 +00003074PyObject *
3075PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003076 const char *encoding,
3077 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003078{
3079 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003080 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003081
Guido van Rossumd57fd912000-03-10 22:53:23 +00003082 if (!PyUnicode_Check(unicode)) {
3083 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003085 }
Fred Drakee4315f52000-05-09 19:53:39 +00003086
Fred Drakee4315f52000-05-09 19:53:39 +00003087 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003088 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003089 if ((strcmp(lower, "utf-8") == 0) ||
3090 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003091 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003092 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003093 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003094 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003095 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003096 }
Victor Stinner37296e82010-06-10 13:36:23 +00003097 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003098 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003099 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003100 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003101#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003102 else if (strcmp(lower, "mbcs") == 0)
3103 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3104 PyUnicode_GET_SIZE(unicode),
3105 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003106#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003107 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003108 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003109 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003110
3111 /* Encode via the codec registry */
3112 v = PyCodec_Encode(unicode, encoding, errors);
3113 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003114 return NULL;
3115
3116 /* The normal path */
3117 if (PyBytes_Check(v))
3118 return v;
3119
3120 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003121 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003122 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003123 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003124
3125 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3126 "encoder %s returned bytearray instead of bytes",
3127 encoding);
3128 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003129 Py_DECREF(v);
3130 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003131 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003132
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003133 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3134 Py_DECREF(v);
3135 return b;
3136 }
3137
3138 PyErr_Format(PyExc_TypeError,
3139 "encoder did not return a bytes object (type=%.400s)",
3140 Py_TYPE(v)->tp_name);
3141 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003142 return NULL;
3143}
3144
Alexander Belopolsky40018472011-02-26 01:02:56 +00003145PyObject *
3146PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003147 const char *encoding,
3148 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003149{
3150 PyObject *v;
3151
3152 if (!PyUnicode_Check(unicode)) {
3153 PyErr_BadArgument();
3154 goto onError;
3155 }
3156
3157 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003158 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003159
3160 /* Encode via the codec registry */
3161 v = PyCodec_Encode(unicode, encoding, errors);
3162 if (v == NULL)
3163 goto onError;
3164 if (!PyUnicode_Check(v)) {
3165 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003166 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003167 Py_TYPE(v)->tp_name);
3168 Py_DECREF(v);
3169 goto onError;
3170 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003171 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003172
Benjamin Peterson29060642009-01-31 22:14:21 +00003173 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003174 return NULL;
3175}
3176
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003177PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003178PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003179 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003180 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3181}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003182
Christian Heimes5894ba72007-11-04 11:43:14 +00003183PyObject*
3184PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3185{
Victor Stinner99b95382011-07-04 14:23:54 +02003186#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003187 return PyUnicode_DecodeMBCS(s, size, NULL);
3188#elif defined(__APPLE__)
3189 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3190#else
Victor Stinner793b5312011-04-27 00:24:21 +02003191 PyInterpreterState *interp = PyThreadState_GET()->interp;
3192 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3193 cannot use it to encode and decode filenames before it is loaded. Load
3194 the Python codec requires to encode at least its own filename. Use the C
3195 version of the locale codec until the codec registry is initialized and
3196 the Python codec is loaded.
3197
3198 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3199 cannot only rely on it: check also interp->fscodec_initialized for
3200 subinterpreters. */
3201 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003202 return PyUnicode_Decode(s, size,
3203 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003204 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003205 }
3206 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003207 /* locale encoding with surrogateescape */
3208 wchar_t *wchar;
3209 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003210 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003211
3212 if (s[size] != '\0' || size != strlen(s)) {
3213 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3214 return NULL;
3215 }
3216
Victor Stinner168e1172010-10-16 23:16:16 +00003217 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003218 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003219 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003220
Victor Stinner168e1172010-10-16 23:16:16 +00003221 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003222 PyMem_Free(wchar);
3223 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003224 }
Victor Stinnerad158722010-10-27 00:25:46 +00003225#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003226}
3227
Martin v. Löwis011e8422009-05-05 04:43:17 +00003228
3229int
3230PyUnicode_FSConverter(PyObject* arg, void* addr)
3231{
3232 PyObject *output = NULL;
3233 Py_ssize_t size;
3234 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003235 if (arg == NULL) {
3236 Py_DECREF(*(PyObject**)addr);
3237 return 1;
3238 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003239 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003240 output = arg;
3241 Py_INCREF(output);
3242 }
3243 else {
3244 arg = PyUnicode_FromObject(arg);
3245 if (!arg)
3246 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003247 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003248 Py_DECREF(arg);
3249 if (!output)
3250 return 0;
3251 if (!PyBytes_Check(output)) {
3252 Py_DECREF(output);
3253 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3254 return 0;
3255 }
3256 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003257 size = PyBytes_GET_SIZE(output);
3258 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003259 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003260 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003261 Py_DECREF(output);
3262 return 0;
3263 }
3264 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003265 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003266}
3267
3268
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003269int
3270PyUnicode_FSDecoder(PyObject* arg, void* addr)
3271{
3272 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003273 if (arg == NULL) {
3274 Py_DECREF(*(PyObject**)addr);
3275 return 1;
3276 }
3277 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003278 if (PyUnicode_READY(arg))
3279 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003280 output = arg;
3281 Py_INCREF(output);
3282 }
3283 else {
3284 arg = PyBytes_FromObject(arg);
3285 if (!arg)
3286 return 0;
3287 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3288 PyBytes_GET_SIZE(arg));
3289 Py_DECREF(arg);
3290 if (!output)
3291 return 0;
3292 if (!PyUnicode_Check(output)) {
3293 Py_DECREF(output);
3294 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3295 return 0;
3296 }
3297 }
Victor Stinner065836e2011-10-27 01:56:33 +02003298 if (PyUnicode_READY(output) < 0) {
3299 Py_DECREF(output);
3300 return 0;
3301 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003302 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003303 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003304 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3305 Py_DECREF(output);
3306 return 0;
3307 }
3308 *(PyObject**)addr = output;
3309 return Py_CLEANUP_SUPPORTED;
3310}
3311
3312
Martin v. Löwis5b222132007-06-10 09:51:05 +00003313char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003314PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003315{
Christian Heimesf3863112007-11-22 07:46:41 +00003316 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003317 PyUnicodeObject *u = (PyUnicodeObject *)unicode;
3318
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003319 if (!PyUnicode_Check(unicode)) {
3320 PyErr_BadArgument();
3321 return NULL;
3322 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003323 if (PyUnicode_READY(u) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003324 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003325
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003326 if (PyUnicode_UTF8(unicode) == NULL) {
3327 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003328 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3329 if (bytes == NULL)
3330 return NULL;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003331 _PyUnicode_UTF8(u) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3332 if (_PyUnicode_UTF8(u) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003333 Py_DECREF(bytes);
3334 return NULL;
3335 }
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003336 _PyUnicode_UTF8_LENGTH(u) = PyBytes_GET_SIZE(bytes);
3337 Py_MEMCPY(_PyUnicode_UTF8(u), PyBytes_AS_STRING(bytes), _PyUnicode_UTF8_LENGTH(u) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003338 Py_DECREF(bytes);
3339 }
3340
3341 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003342 *psize = PyUnicode_UTF8_LENGTH(unicode);
3343 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003344}
3345
3346char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003347PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003348{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003349 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3350}
3351
3352#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003353static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003354#endif
3355
3356
3357Py_UNICODE *
3358PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3359{
3360 PyUnicodeObject *u;
3361 const unsigned char *one_byte;
3362#if SIZEOF_WCHAR_T == 4
3363 const Py_UCS2 *two_bytes;
3364#else
3365 const Py_UCS4 *four_bytes;
3366 const Py_UCS4 *ucs4_end;
3367 Py_ssize_t num_surrogates;
3368#endif
3369 wchar_t *w;
3370 wchar_t *wchar_end;
3371
3372 if (!PyUnicode_Check(unicode)) {
3373 PyErr_BadArgument();
3374 return NULL;
3375 }
3376 u = (PyUnicodeObject*)unicode;
3377 if (_PyUnicode_WSTR(u) == NULL) {
3378 /* Non-ASCII compact unicode object */
3379 assert(_PyUnicode_KIND(u) != 0);
3380 assert(PyUnicode_IS_READY(u));
3381
3382#ifdef Py_DEBUG
3383 ++unicode_as_unicode_calls;
3384#endif
3385
3386 if (PyUnicode_KIND(u) == PyUnicode_4BYTE_KIND) {
3387#if SIZEOF_WCHAR_T == 2
3388 four_bytes = PyUnicode_4BYTE_DATA(u);
3389 ucs4_end = four_bytes + _PyUnicode_LENGTH(u);
3390 num_surrogates = 0;
3391
3392 for (; four_bytes < ucs4_end; ++four_bytes) {
3393 if (*four_bytes > 0xFFFF)
3394 ++num_surrogates;
3395 }
3396
3397 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(
3398 sizeof(wchar_t) * (_PyUnicode_LENGTH(u) + 1 + num_surrogates));
3399 if (!_PyUnicode_WSTR(u)) {
3400 PyErr_NoMemory();
3401 return NULL;
3402 }
3403 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u) + num_surrogates;
3404
3405 w = _PyUnicode_WSTR(u);
3406 wchar_end = w + _PyUnicode_WSTR_LENGTH(u);
3407 four_bytes = PyUnicode_4BYTE_DATA(u);
3408 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3409 if (*four_bytes > 0xFFFF) {
3410 /* encode surrogate pair in this case */
3411 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3412 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3413 }
3414 else
3415 *w = *four_bytes;
3416
3417 if (w > wchar_end) {
3418 assert(0 && "Miscalculated string end");
3419 }
3420 }
3421 *w = 0;
3422#else
3423 /* sizeof(wchar_t) == 4 */
3424 Py_FatalError("Impossible unicode object state, wstr and str "
3425 "should share memory already.");
3426 return NULL;
3427#endif
3428 }
3429 else {
3430 _PyUnicode_WSTR(u) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3431 (_PyUnicode_LENGTH(u) + 1));
3432 if (!_PyUnicode_WSTR(u)) {
3433 PyErr_NoMemory();
3434 return NULL;
3435 }
3436 if (!PyUnicode_IS_COMPACT_ASCII(u))
3437 _PyUnicode_WSTR_LENGTH(u) = _PyUnicode_LENGTH(u);
3438 w = _PyUnicode_WSTR(u);
3439 wchar_end = w + _PyUnicode_LENGTH(u);
3440
3441 if (PyUnicode_KIND(u) == PyUnicode_1BYTE_KIND) {
3442 one_byte = PyUnicode_1BYTE_DATA(u);
3443 for (; w < wchar_end; ++one_byte, ++w)
3444 *w = *one_byte;
3445 /* null-terminate the wstr */
3446 *w = 0;
3447 }
3448 else if (PyUnicode_KIND(u) == PyUnicode_2BYTE_KIND) {
3449#if SIZEOF_WCHAR_T == 4
3450 two_bytes = PyUnicode_2BYTE_DATA(u);
3451 for (; w < wchar_end; ++two_bytes, ++w)
3452 *w = *two_bytes;
3453 /* null-terminate the wstr */
3454 *w = 0;
3455#else
3456 /* sizeof(wchar_t) == 2 */
3457 PyObject_FREE(_PyUnicode_WSTR(u));
3458 _PyUnicode_WSTR(u) = NULL;
3459 Py_FatalError("Impossible unicode object state, wstr "
3460 "and str should share memory already.");
3461 return NULL;
3462#endif
3463 }
3464 else {
3465 assert(0 && "This should never happen.");
3466 }
3467 }
3468 }
3469 if (size != NULL)
3470 *size = PyUnicode_WSTR_LENGTH(u);
3471 return _PyUnicode_WSTR(u);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003472}
3473
Alexander Belopolsky40018472011-02-26 01:02:56 +00003474Py_UNICODE *
3475PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003476{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003477 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003478}
3479
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003480
Alexander Belopolsky40018472011-02-26 01:02:56 +00003481Py_ssize_t
3482PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003483{
3484 if (!PyUnicode_Check(unicode)) {
3485 PyErr_BadArgument();
3486 goto onError;
3487 }
3488 return PyUnicode_GET_SIZE(unicode);
3489
Benjamin Peterson29060642009-01-31 22:14:21 +00003490 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003491 return -1;
3492}
3493
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003494Py_ssize_t
3495PyUnicode_GetLength(PyObject *unicode)
3496{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003497 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003498 PyErr_BadArgument();
3499 return -1;
3500 }
3501
3502 return PyUnicode_GET_LENGTH(unicode);
3503}
3504
3505Py_UCS4
3506PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3507{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003508 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3509 PyErr_BadArgument();
3510 return (Py_UCS4)-1;
3511 }
3512 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3513 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003514 return (Py_UCS4)-1;
3515 }
3516 return PyUnicode_READ_CHAR(unicode, index);
3517}
3518
3519int
3520PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3521{
3522 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003523 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003524 return -1;
3525 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003526 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3527 PyErr_SetString(PyExc_IndexError, "string index out of range");
3528 return -1;
3529 }
3530 if (_PyUnicode_Dirty(unicode))
3531 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003532 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3533 index, ch);
3534 return 0;
3535}
3536
Alexander Belopolsky40018472011-02-26 01:02:56 +00003537const char *
3538PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003539{
Victor Stinner42cb4622010-09-01 19:39:01 +00003540 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003541}
3542
Victor Stinner554f3f02010-06-16 23:33:54 +00003543/* create or adjust a UnicodeDecodeError */
3544static void
3545make_decode_exception(PyObject **exceptionObject,
3546 const char *encoding,
3547 const char *input, Py_ssize_t length,
3548 Py_ssize_t startpos, Py_ssize_t endpos,
3549 const char *reason)
3550{
3551 if (*exceptionObject == NULL) {
3552 *exceptionObject = PyUnicodeDecodeError_Create(
3553 encoding, input, length, startpos, endpos, reason);
3554 }
3555 else {
3556 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3557 goto onError;
3558 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3559 goto onError;
3560 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3561 goto onError;
3562 }
3563 return;
3564
3565onError:
3566 Py_DECREF(*exceptionObject);
3567 *exceptionObject = NULL;
3568}
3569
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003570/* error handling callback helper:
3571 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003572 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003573 and adjust various state variables.
3574 return 0 on success, -1 on error
3575*/
3576
Alexander Belopolsky40018472011-02-26 01:02:56 +00003577static int
3578unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003579 const char *encoding, const char *reason,
3580 const char **input, const char **inend, Py_ssize_t *startinpos,
3581 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
3582 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003583{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003584 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003585
3586 PyObject *restuple = NULL;
3587 PyObject *repunicode = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003588 Py_ssize_t outsize = PyUnicode_GET_SIZE(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003589 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003590 Py_ssize_t requiredsize;
3591 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003592 const Py_UNICODE *repptr;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003593 PyObject *inputobj = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003594 Py_ssize_t repsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003595 int res = -1;
3596
3597 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003598 *errorHandler = PyCodec_LookupError(errors);
3599 if (*errorHandler == NULL)
3600 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003601 }
3602
Victor Stinner554f3f02010-06-16 23:33:54 +00003603 make_decode_exception(exceptionObject,
3604 encoding,
3605 *input, *inend - *input,
3606 *startinpos, *endinpos,
3607 reason);
3608 if (*exceptionObject == NULL)
3609 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003610
3611 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3612 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003613 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003614 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003615 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003616 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003617 }
3618 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003619 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003620
3621 /* Copy back the bytes variables, which might have been modified by the
3622 callback */
3623 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3624 if (!inputobj)
3625 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003626 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003627 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003628 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003629 *input = PyBytes_AS_STRING(inputobj);
3630 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003631 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003632 /* we can DECREF safely, as the exception has another reference,
3633 so the object won't go away. */
3634 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003635
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003636 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003637 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003638 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003639 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3640 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003641 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003642
3643 /* need more space? (at least enough for what we
3644 have+the replacement+the rest of the string (starting
3645 at the new input position), so we won't have to check space
3646 when there are no errors in the rest of the string) */
3647 repptr = PyUnicode_AS_UNICODE(repunicode);
3648 repsize = PyUnicode_GET_SIZE(repunicode);
3649 requiredsize = *outpos + repsize + insize-newpos;
3650 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003651 if (requiredsize<2*outsize)
3652 requiredsize = 2*outsize;
Victor Stinnerfe226c02011-10-03 03:52:20 +02003653 if (PyUnicode_Resize((PyObject**)output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003654 goto onError;
3655 *outptr = PyUnicode_AS_UNICODE(*output) + *outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003656 }
3657 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003658 *inptr = *input + newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003659 Py_UNICODE_COPY(*outptr, repptr, repsize);
3660 *outptr += repsize;
3661 *outpos += repsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003662
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003663 /* we made it! */
3664 res = 0;
3665
Benjamin Peterson29060642009-01-31 22:14:21 +00003666 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003667 Py_XDECREF(restuple);
3668 return res;
3669}
3670
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003671/* --- UTF-7 Codec -------------------------------------------------------- */
3672
Antoine Pitrou244651a2009-05-04 18:56:13 +00003673/* See RFC2152 for details. We encode conservatively and decode liberally. */
3674
3675/* Three simple macros defining base-64. */
3676
3677/* Is c a base-64 character? */
3678
3679#define IS_BASE64(c) \
3680 (((c) >= 'A' && (c) <= 'Z') || \
3681 ((c) >= 'a' && (c) <= 'z') || \
3682 ((c) >= '0' && (c) <= '9') || \
3683 (c) == '+' || (c) == '/')
3684
3685/* given that c is a base-64 character, what is its base-64 value? */
3686
3687#define FROM_BASE64(c) \
3688 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3689 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3690 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3691 (c) == '+' ? 62 : 63)
3692
3693/* What is the base-64 character of the bottom 6 bits of n? */
3694
3695#define TO_BASE64(n) \
3696 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3697
3698/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3699 * decoded as itself. We are permissive on decoding; the only ASCII
3700 * byte not decoding to itself is the + which begins a base64
3701 * string. */
3702
3703#define DECODE_DIRECT(c) \
3704 ((c) <= 127 && (c) != '+')
3705
3706/* The UTF-7 encoder treats ASCII characters differently according to
3707 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3708 * the above). See RFC2152. This array identifies these different
3709 * sets:
3710 * 0 : "Set D"
3711 * alphanumeric and '(),-./:?
3712 * 1 : "Set O"
3713 * !"#$%&*;<=>@[]^_`{|}
3714 * 2 : "whitespace"
3715 * ht nl cr sp
3716 * 3 : special (must be base64 encoded)
3717 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3718 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003719
Tim Petersced69f82003-09-16 20:30:58 +00003720static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003721char utf7_category[128] = {
3722/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3723 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3724/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3725 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3726/* sp ! " # $ % & ' ( ) * + , - . / */
3727 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3728/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3729 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3730/* @ A B C D E F G H I J K L M N O */
3731 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3732/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3733 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3734/* ` a b c d e f g h i j k l m n o */
3735 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3736/* p q r s t u v w x y z { | } ~ del */
3737 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003738};
3739
Antoine Pitrou244651a2009-05-04 18:56:13 +00003740/* ENCODE_DIRECT: this character should be encoded as itself. The
3741 * answer depends on whether we are encoding set O as itself, and also
3742 * on whether we are encoding whitespace as itself. RFC2152 makes it
3743 * clear that the answers to these questions vary between
3744 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003745
Antoine Pitrou244651a2009-05-04 18:56:13 +00003746#define ENCODE_DIRECT(c, directO, directWS) \
3747 ((c) < 128 && (c) > 0 && \
3748 ((utf7_category[(c)] == 0) || \
3749 (directWS && (utf7_category[(c)] == 2)) || \
3750 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003751
Alexander Belopolsky40018472011-02-26 01:02:56 +00003752PyObject *
3753PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003754 Py_ssize_t size,
3755 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003756{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003757 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3758}
3759
Antoine Pitrou244651a2009-05-04 18:56:13 +00003760/* The decoder. The only state we preserve is our read position,
3761 * i.e. how many characters we have consumed. So if we end in the
3762 * middle of a shift sequence we have to back off the read position
3763 * and the output to the beginning of the sequence, otherwise we lose
3764 * all the shift state (seen bits, number of bits seen, high
3765 * surrogate). */
3766
Alexander Belopolsky40018472011-02-26 01:02:56 +00003767PyObject *
3768PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003769 Py_ssize_t size,
3770 const char *errors,
3771 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003772{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003773 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003774 Py_ssize_t startinpos;
3775 Py_ssize_t endinpos;
3776 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003777 const char *e;
3778 PyUnicodeObject *unicode;
3779 Py_UNICODE *p;
3780 const char *errmsg = "";
3781 int inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003782 Py_UNICODE *shiftOutStart;
3783 unsigned int base64bits = 0;
3784 unsigned long base64buffer = 0;
3785 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003786 PyObject *errorHandler = NULL;
3787 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003788
3789 unicode = _PyUnicode_New(size);
3790 if (!unicode)
3791 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003792 if (size == 0) {
3793 if (consumed)
3794 *consumed = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003795 return (PyObject *)unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003796 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003797
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003798 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitrou244651a2009-05-04 18:56:13 +00003799 shiftOutStart = p;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003800 e = s + size;
3801
3802 while (s < e) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003803 Py_UNICODE ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003804 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003805 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003806
Antoine Pitrou244651a2009-05-04 18:56:13 +00003807 if (inShift) { /* in a base-64 section */
3808 if (IS_BASE64(ch)) { /* consume a base-64 character */
3809 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3810 base64bits += 6;
3811 s++;
3812 if (base64bits >= 16) {
3813 /* we have enough bits for a UTF-16 value */
3814 Py_UNICODE outCh = (Py_UNICODE)
3815 (base64buffer >> (base64bits-16));
3816 base64bits -= 16;
3817 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3818 if (surrogate) {
3819 /* expecting a second surrogate */
3820 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3821#ifdef Py_UNICODE_WIDE
3822 *p++ = (((surrogate & 0x3FF)<<10)
3823 | (outCh & 0x3FF)) + 0x10000;
3824#else
3825 *p++ = surrogate;
3826 *p++ = outCh;
3827#endif
3828 surrogate = 0;
3829 }
3830 else {
3831 surrogate = 0;
3832 errmsg = "second surrogate missing";
3833 goto utf7Error;
3834 }
3835 }
3836 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3837 /* first surrogate */
3838 surrogate = outCh;
3839 }
3840 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3841 errmsg = "unexpected second surrogate";
3842 goto utf7Error;
3843 }
3844 else {
3845 *p++ = outCh;
3846 }
3847 }
3848 }
3849 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003850 inShift = 0;
3851 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003852 if (surrogate) {
3853 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003854 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003855 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003856 if (base64bits > 0) { /* left-over bits */
3857 if (base64bits >= 6) {
3858 /* We've seen at least one base-64 character */
3859 errmsg = "partial character in shift sequence";
3860 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003861 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003862 else {
3863 /* Some bits remain; they should be zero */
3864 if (base64buffer != 0) {
3865 errmsg = "non-zero padding bits in shift sequence";
3866 goto utf7Error;
3867 }
3868 }
3869 }
3870 if (ch != '-') {
3871 /* '-' is absorbed; other terminating
3872 characters are preserved */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003873 *p++ = ch;
3874 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003875 }
3876 }
3877 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003878 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003879 s++; /* consume '+' */
3880 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003881 s++;
3882 *p++ = '+';
Antoine Pitrou244651a2009-05-04 18:56:13 +00003883 }
3884 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885 inShift = 1;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 shiftOutStart = p;
3887 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003888 }
3889 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003890 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003891 *p++ = ch;
3892 s++;
3893 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003894 else {
3895 startinpos = s-starts;
3896 s++;
3897 errmsg = "unexpected special character";
3898 goto utf7Error;
3899 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003900 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003901utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003902 outpos = p-PyUnicode_AS_UNICODE(unicode);
3903 endinpos = s-starts;
3904 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003905 errors, &errorHandler,
3906 "utf7", errmsg,
3907 &starts, &e, &startinpos, &endinpos, &exc, &s,
3908 &unicode, &outpos, &p))
3909 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003910 }
3911
Antoine Pitrou244651a2009-05-04 18:56:13 +00003912 /* end of string */
3913
3914 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3915 /* if we're in an inconsistent state, that's an error */
3916 if (surrogate ||
3917 (base64bits >= 6) ||
3918 (base64bits > 0 && base64buffer != 0)) {
3919 outpos = p-PyUnicode_AS_UNICODE(unicode);
3920 endinpos = size;
3921 if (unicode_decode_call_errorhandler(
3922 errors, &errorHandler,
3923 "utf7", "unterminated shift sequence",
3924 &starts, &e, &startinpos, &endinpos, &exc, &s,
3925 &unicode, &outpos, &p))
3926 goto onError;
3927 if (s < e)
3928 goto restart;
3929 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003930 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003931
3932 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003933 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003934 if (inShift) {
3935 p = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003936 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003937 }
3938 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003939 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003940 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003941 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003942
Victor Stinnerfe226c02011-10-03 03:52:20 +02003943 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003944 goto onError;
3945
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003946 Py_XDECREF(errorHandler);
3947 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003948#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003949 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003950 Py_DECREF(unicode);
3951 return NULL;
3952 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003953#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003954 assert(_PyUnicode_CheckConsistency(unicode, 1));
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003955 return (PyObject *)unicode;
3956
Benjamin Peterson29060642009-01-31 22:14:21 +00003957 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003958 Py_XDECREF(errorHandler);
3959 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003960 Py_DECREF(unicode);
3961 return NULL;
3962}
3963
3964
Alexander Belopolsky40018472011-02-26 01:02:56 +00003965PyObject *
3966PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003967 Py_ssize_t size,
3968 int base64SetO,
3969 int base64WhiteSpace,
3970 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003971{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003972 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003973 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003974 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003975 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003976 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003977 unsigned int base64bits = 0;
3978 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003979 char * out;
3980 char * start;
3981
3982 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003983 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003984
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00003985 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00003986 return PyErr_NoMemory();
3987
Antoine Pitrou244651a2009-05-04 18:56:13 +00003988 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003989 if (v == NULL)
3990 return NULL;
3991
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00003992 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003993 for (;i < size; ++i) {
3994 Py_UNICODE ch = s[i];
3995
Antoine Pitrou244651a2009-05-04 18:56:13 +00003996 if (inShift) {
3997 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
3998 /* shifting out */
3999 if (base64bits) { /* output remaining bits */
4000 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4001 base64buffer = 0;
4002 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004003 }
4004 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004005 /* Characters not in the BASE64 set implicitly unshift the sequence
4006 so no '-' is required, except if the character is itself a '-' */
4007 if (IS_BASE64(ch) || ch == '-') {
4008 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004009 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004010 *out++ = (char) ch;
4011 }
4012 else {
4013 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004014 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004015 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004016 else { /* not in a shift sequence */
4017 if (ch == '+') {
4018 *out++ = '+';
4019 *out++ = '-';
4020 }
4021 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4022 *out++ = (char) ch;
4023 }
4024 else {
4025 *out++ = '+';
4026 inShift = 1;
4027 goto encode_char;
4028 }
4029 }
4030 continue;
4031encode_char:
4032#ifdef Py_UNICODE_WIDE
4033 if (ch >= 0x10000) {
4034 /* code first surrogate */
4035 base64bits += 16;
4036 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4037 while (base64bits >= 6) {
4038 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4039 base64bits -= 6;
4040 }
4041 /* prepare second surrogate */
4042 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4043 }
4044#endif
4045 base64bits += 16;
4046 base64buffer = (base64buffer << 16) | ch;
4047 while (base64bits >= 6) {
4048 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4049 base64bits -= 6;
4050 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004051 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004052 if (base64bits)
4053 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4054 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004055 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004056 if (_PyBytes_Resize(&v, out - start) < 0)
4057 return NULL;
4058 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004059}
4060
Antoine Pitrou244651a2009-05-04 18:56:13 +00004061#undef IS_BASE64
4062#undef FROM_BASE64
4063#undef TO_BASE64
4064#undef DECODE_DIRECT
4065#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004066
Guido van Rossumd57fd912000-03-10 22:53:23 +00004067/* --- UTF-8 Codec -------------------------------------------------------- */
4068
Tim Petersced69f82003-09-16 20:30:58 +00004069static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004070char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004071 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4072 illegal prefix. See RFC 3629 for details */
4073 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4074 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004075 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004076 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4077 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4078 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4079 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004080 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4081 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 +00004082 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4083 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004084 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4085 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4086 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4087 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4088 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 +00004089};
4090
Alexander Belopolsky40018472011-02-26 01:02:56 +00004091PyObject *
4092PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004093 Py_ssize_t size,
4094 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004095{
Walter Dörwald69652032004-09-07 20:24:22 +00004096 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4097}
4098
Antoine Pitrouab868312009-01-10 15:40:25 +00004099/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4100#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4101
4102/* Mask to quickly check whether a C 'long' contains a
4103 non-ASCII, UTF8-encoded char. */
4104#if (SIZEOF_LONG == 8)
4105# define ASCII_CHAR_MASK 0x8080808080808080L
4106#elif (SIZEOF_LONG == 4)
4107# define ASCII_CHAR_MASK 0x80808080L
4108#else
4109# error C 'long' size should be either 4 or 8!
4110#endif
4111
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004112/* Scans a UTF-8 string and returns the maximum character to be expected,
4113 the size of the decoded unicode string and if any major errors were
4114 encountered.
4115
4116 This function does check basic UTF-8 sanity, it does however NOT CHECK
4117 if the string contains surrogates, and if all continuation bytes are
4118 within the correct ranges, these checks are performed in
4119 PyUnicode_DecodeUTF8Stateful.
4120
4121 If it sets has_errors to 1, it means the value of unicode_size and max_char
4122 will be bogus and you should not rely on useful information in them.
4123 */
4124static Py_UCS4
4125utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4126 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4127 int *has_errors)
4128{
4129 Py_ssize_t n;
4130 Py_ssize_t char_count = 0;
4131 Py_UCS4 max_char = 127, new_max;
4132 Py_UCS4 upper_bound;
4133 const unsigned char *p = (const unsigned char *)s;
4134 const unsigned char *end = p + string_size;
4135 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4136 int err = 0;
4137
4138 for (; p < end && !err; ++p, ++char_count) {
4139 /* Only check value if it's not a ASCII char... */
4140 if (*p < 0x80) {
4141 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4142 an explanation. */
4143 if (!((size_t) p & LONG_PTR_MASK)) {
4144 /* Help register allocation */
4145 register const unsigned char *_p = p;
4146 while (_p < aligned_end) {
4147 unsigned long value = *(unsigned long *) _p;
4148 if (value & ASCII_CHAR_MASK)
4149 break;
4150 _p += SIZEOF_LONG;
4151 char_count += SIZEOF_LONG;
4152 }
4153 p = _p;
4154 if (p == end)
4155 break;
4156 }
4157 }
4158 if (*p >= 0x80) {
4159 n = utf8_code_length[*p];
4160 new_max = max_char;
4161 switch (n) {
4162 /* invalid start byte */
4163 case 0:
4164 err = 1;
4165 break;
4166 case 2:
4167 /* Code points between 0x00FF and 0x07FF inclusive.
4168 Approximate the upper bound of the code point,
4169 if this flips over 255 we can be sure it will be more
4170 than 255 and the string will need 2 bytes per code coint,
4171 if it stays under or equal to 255, we can be sure 1 byte
4172 is enough.
4173 ((*p & 0b00011111) << 6) | 0b00111111 */
4174 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4175 if (max_char < upper_bound)
4176 new_max = upper_bound;
4177 /* Ensure we track at least that we left ASCII space. */
4178 if (new_max < 128)
4179 new_max = 128;
4180 break;
4181 case 3:
4182 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4183 always > 255 and <= 65535 and will always need 2 bytes. */
4184 if (max_char < 65535)
4185 new_max = 65535;
4186 break;
4187 case 4:
4188 /* Code point will be above 0xFFFF for sure in this case. */
4189 new_max = 65537;
4190 break;
4191 /* Internal error, this should be caught by the first if */
4192 case 1:
4193 default:
4194 assert(0 && "Impossible case in utf8_max_char_and_size");
4195 err = 1;
4196 }
4197 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004198 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004199 --n;
4200 /* Check if the follow up chars are all valid continuation bytes */
4201 if (n >= 1) {
4202 const unsigned char *cont;
4203 if ((p + n) >= end) {
4204 if (consumed == 0)
4205 /* incomplete data, non-incremental decoding */
4206 err = 1;
4207 break;
4208 }
4209 for (cont = p + 1; cont < (p + n); ++cont) {
4210 if ((*cont & 0xc0) != 0x80) {
4211 err = 1;
4212 break;
4213 }
4214 }
4215 p += n;
4216 }
4217 else
4218 err = 1;
4219 max_char = new_max;
4220 }
4221 }
4222
4223 if (unicode_size)
4224 *unicode_size = char_count;
4225 if (has_errors)
4226 *has_errors = err;
4227 return max_char;
4228}
4229
4230/* Similar to PyUnicode_WRITE but can also write into wstr field
4231 of the legacy unicode representation */
4232#define WRITE_FLEXIBLE_OR_WSTR(kind, buf, index, value) \
4233 do { \
4234 const int k_ = (kind); \
4235 if (k_ == PyUnicode_WCHAR_KIND) \
4236 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
4237 else if (k_ == PyUnicode_1BYTE_KIND) \
4238 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
4239 else if (k_ == PyUnicode_2BYTE_KIND) \
4240 ((Py_UCS2 *)(buf))[(index)] = (Py_UCS2)(value); \
4241 else \
4242 ((Py_UCS4 *)(buf))[(index)] = (Py_UCS4)(value); \
4243 } while (0)
4244
Alexander Belopolsky40018472011-02-26 01:02:56 +00004245PyObject *
4246PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004247 Py_ssize_t size,
4248 const char *errors,
4249 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004250{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004251 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004252 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004253 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004254 Py_ssize_t startinpos;
4255 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004256 const char *e, *aligned_end;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004257 PyUnicodeObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004258 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004259 PyObject *errorHandler = NULL;
4260 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004261 Py_UCS4 maxchar = 0;
4262 Py_ssize_t unicode_size;
4263 Py_ssize_t i;
4264 int kind;
4265 void *data;
4266 int has_errors;
4267 Py_UNICODE *error_outptr;
4268#if SIZEOF_WCHAR_T == 2
4269 Py_ssize_t wchar_offset = 0;
4270#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004271
Walter Dörwald69652032004-09-07 20:24:22 +00004272 if (size == 0) {
4273 if (consumed)
4274 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004275 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004276 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004277 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4278 consumed, &has_errors);
4279 if (has_errors) {
4280 unicode = _PyUnicode_New(size);
4281 if (!unicode)
4282 return NULL;
4283 kind = PyUnicode_WCHAR_KIND;
4284 data = PyUnicode_AS_UNICODE(unicode);
4285 assert(data != NULL);
4286 }
4287 else {
4288 unicode = (PyUnicodeObject *)PyUnicode_New(unicode_size, maxchar);
4289 if (!unicode)
4290 return NULL;
4291 /* When the string is ASCII only, just use memcpy and return.
4292 unicode_size may be != size if there is an incomplete UTF-8
4293 sequence at the end of the ASCII block. */
4294 if (maxchar < 128 && size == unicode_size) {
4295 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4296 return (PyObject *)unicode;
4297 }
4298 kind = PyUnicode_KIND(unicode);
4299 data = PyUnicode_DATA(unicode);
4300 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004301 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004302 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004303 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004304 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004305
4306 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004307 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004308
4309 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004310 /* Fast path for runs of ASCII characters. Given that common UTF-8
4311 input will consist of an overwhelming majority of ASCII
4312 characters, we try to optimize for this case by checking
4313 as many characters as a C 'long' can contain.
4314 First, check if we can do an aligned read, as most CPUs have
4315 a penalty for unaligned reads.
4316 */
4317 if (!((size_t) s & LONG_PTR_MASK)) {
4318 /* Help register allocation */
4319 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004320 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004321 while (_s < aligned_end) {
4322 /* Read a whole long at a time (either 4 or 8 bytes),
4323 and do a fast unrolled copy if it only contains ASCII
4324 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004325 unsigned long value = *(unsigned long *) _s;
4326 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004327 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004328 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+0, _s[0]);
4329 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+1, _s[1]);
4330 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+2, _s[2]);
4331 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004332#if (SIZEOF_LONG == 8)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004333 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+4, _s[4]);
4334 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+5, _s[5]);
4335 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+6, _s[6]);
4336 WRITE_FLEXIBLE_OR_WSTR(kind, data, _i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004337#endif
4338 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004339 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004340 }
4341 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004342 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004343 if (s == e)
4344 break;
4345 ch = (unsigned char)*s;
4346 }
4347 }
4348
4349 if (ch < 0x80) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004350 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004351 s++;
4352 continue;
4353 }
4354
4355 n = utf8_code_length[ch];
4356
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004357 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004358 if (consumed)
4359 break;
4360 else {
4361 errmsg = "unexpected end of data";
4362 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004363 endinpos = startinpos+1;
4364 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4365 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004366 goto utf8Error;
4367 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004368 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004369
4370 switch (n) {
4371
4372 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004373 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004374 startinpos = s-starts;
4375 endinpos = startinpos+1;
4376 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004377
4378 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004379 errmsg = "internal error";
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 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004385 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004386 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004387 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004388 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004389 goto utf8Error;
4390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004391 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004392 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004393 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004394 break;
4395
4396 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004397 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4398 will result in surrogates in range d800-dfff. Surrogates are
4399 not valid UTF-8 so they are rejected.
4400 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4401 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004402 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004403 (s[2] & 0xc0) != 0x80 ||
4404 ((unsigned char)s[0] == 0xE0 &&
4405 (unsigned char)s[1] < 0xA0) ||
4406 ((unsigned char)s[0] == 0xED &&
4407 (unsigned char)s[1] > 0x9F)) {
4408 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004409 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004410 endinpos = startinpos + 1;
4411
4412 /* if s[1] first two bits are 1 and 0, then the invalid
4413 continuation byte is s[2], so increment endinpos by 1,
4414 if not, s[1] is invalid and endinpos doesn't need to
4415 be incremented. */
4416 if ((s[1] & 0xC0) == 0x80)
4417 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 goto utf8Error;
4419 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004420 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004421 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004422 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004423 break;
4424
4425 case 4:
4426 if ((s[1] & 0xc0) != 0x80 ||
4427 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004428 (s[3] & 0xc0) != 0x80 ||
4429 ((unsigned char)s[0] == 0xF0 &&
4430 (unsigned char)s[1] < 0x90) ||
4431 ((unsigned char)s[0] == 0xF4 &&
4432 (unsigned char)s[1] > 0x8F)) {
4433 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004434 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004435 endinpos = startinpos + 1;
4436 if ((s[1] & 0xC0) == 0x80) {
4437 endinpos++;
4438 if ((s[2] & 0xC0) == 0x80)
4439 endinpos++;
4440 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004441 goto utf8Error;
4442 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004443 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004444 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4445 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004447 /* If the string is flexible or we have native UCS-4, write
4448 directly.. */
4449 if (sizeof(Py_UNICODE) > 2 || kind != PyUnicode_WCHAR_KIND)
4450 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++, ch);
Tim Petersced69f82003-09-16 20:30:58 +00004451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004452 else {
4453 /* compute and append the two surrogates: */
Tim Petersced69f82003-09-16 20:30:58 +00004454
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004455 /* translate from 10000..10FFFF to 0..FFFF */
4456 ch -= 0x10000;
Tim Petersced69f82003-09-16 20:30:58 +00004457
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004458 /* high surrogate = top 10 bits added to D800 */
4459 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4460 (Py_UNICODE)(0xD800 + (ch >> 10)));
4461
4462 /* low surrogate = bottom 10 bits added to DC00 */
4463 WRITE_FLEXIBLE_OR_WSTR(kind, data, i++,
4464 (Py_UNICODE)(0xDC00 + (ch & 0x03FF)));
4465 }
4466#if SIZEOF_WCHAR_T == 2
4467 wchar_offset++;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00004468#endif
Guido van Rossumd57fd912000-03-10 22:53:23 +00004469 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470 }
4471 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004473
Benjamin Peterson29060642009-01-31 22:14:21 +00004474 utf8Error:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004475 /* If this is not yet a resizable string, make it one.. */
4476 if (kind != PyUnicode_WCHAR_KIND) {
4477 const Py_UNICODE *u;
4478 PyUnicodeObject *new_unicode = _PyUnicode_New(size);
4479 if (!new_unicode)
4480 goto onError;
4481 u = PyUnicode_AsUnicode((PyObject *)unicode);
4482 if (!u)
4483 goto onError;
4484#if SIZEOF_WCHAR_T == 2
4485 i += wchar_offset;
4486#endif
4487 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(new_unicode), u, i);
4488 Py_DECREF(unicode);
4489 unicode = new_unicode;
4490 kind = 0;
4491 data = PyUnicode_AS_UNICODE(new_unicode);
4492 assert(data != NULL);
4493 }
4494 error_outptr = PyUnicode_AS_UNICODE(unicode) + i;
Benjamin Peterson29060642009-01-31 22:14:21 +00004495 if (unicode_decode_call_errorhandler(
4496 errors, &errorHandler,
4497 "utf8", errmsg,
4498 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004499 &unicode, &i, &error_outptr))
Benjamin Peterson29060642009-01-31 22:14:21 +00004500 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004501 /* Update data because unicode_decode_call_errorhandler might have
4502 re-created or resized the unicode object. */
4503 data = PyUnicode_AS_UNICODE(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004504 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004506 /* Ensure the unicode_size calculation above was correct: */
4507 assert(kind == PyUnicode_WCHAR_KIND || i == unicode_size);
4508
Walter Dörwald69652032004-09-07 20:24:22 +00004509 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004512 /* Adjust length and ready string when it contained errors and
4513 is of the old resizable kind. */
4514 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004515 if (PyUnicode_Resize((PyObject**)&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004516 goto onError;
4517 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004519 Py_XDECREF(errorHandler);
4520 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004521#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004522 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004523 Py_DECREF(unicode);
4524 return NULL;
4525 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004526#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004527 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00004528 return (PyObject *)unicode;
4529
Benjamin Peterson29060642009-01-31 22:14:21 +00004530 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004531 Py_XDECREF(errorHandler);
4532 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004533 Py_DECREF(unicode);
4534 return NULL;
4535}
4536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004537#undef WRITE_FLEXIBLE_OR_WSTR
Antoine Pitrouab868312009-01-10 15:40:25 +00004538
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004539#ifdef __APPLE__
4540
4541/* Simplified UTF-8 decoder using surrogateescape error handler,
4542 used to decode the command line arguments on Mac OS X. */
4543
4544wchar_t*
4545_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4546{
4547 int n;
4548 const char *e;
4549 wchar_t *unicode, *p;
4550
4551 /* Note: size will always be longer than the resulting Unicode
4552 character count */
4553 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4554 PyErr_NoMemory();
4555 return NULL;
4556 }
4557 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4558 if (!unicode)
4559 return NULL;
4560
4561 /* Unpack UTF-8 encoded data */
4562 p = unicode;
4563 e = s + size;
4564 while (s < e) {
4565 Py_UCS4 ch = (unsigned char)*s;
4566
4567 if (ch < 0x80) {
4568 *p++ = (wchar_t)ch;
4569 s++;
4570 continue;
4571 }
4572
4573 n = utf8_code_length[ch];
4574 if (s + n > e) {
4575 goto surrogateescape;
4576 }
4577
4578 switch (n) {
4579 case 0:
4580 case 1:
4581 goto surrogateescape;
4582
4583 case 2:
4584 if ((s[1] & 0xc0) != 0x80)
4585 goto surrogateescape;
4586 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4587 assert ((ch > 0x007F) && (ch <= 0x07FF));
4588 *p++ = (wchar_t)ch;
4589 break;
4590
4591 case 3:
4592 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4593 will result in surrogates in range d800-dfff. Surrogates are
4594 not valid UTF-8 so they are rejected.
4595 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4596 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4597 if ((s[1] & 0xc0) != 0x80 ||
4598 (s[2] & 0xc0) != 0x80 ||
4599 ((unsigned char)s[0] == 0xE0 &&
4600 (unsigned char)s[1] < 0xA0) ||
4601 ((unsigned char)s[0] == 0xED &&
4602 (unsigned char)s[1] > 0x9F)) {
4603
4604 goto surrogateescape;
4605 }
4606 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4607 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004608 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004609 break;
4610
4611 case 4:
4612 if ((s[1] & 0xc0) != 0x80 ||
4613 (s[2] & 0xc0) != 0x80 ||
4614 (s[3] & 0xc0) != 0x80 ||
4615 ((unsigned char)s[0] == 0xF0 &&
4616 (unsigned char)s[1] < 0x90) ||
4617 ((unsigned char)s[0] == 0xF4 &&
4618 (unsigned char)s[1] > 0x8F)) {
4619 goto surrogateescape;
4620 }
4621 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4622 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4623 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4624
4625#if SIZEOF_WCHAR_T == 4
4626 *p++ = (wchar_t)ch;
4627#else
4628 /* compute and append the two surrogates: */
4629
4630 /* translate from 10000..10FFFF to 0..FFFF */
4631 ch -= 0x10000;
4632
4633 /* high surrogate = top 10 bits added to D800 */
4634 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4635
4636 /* low surrogate = bottom 10 bits added to DC00 */
4637 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4638#endif
4639 break;
4640 }
4641 s += n;
4642 continue;
4643
4644 surrogateescape:
4645 *p++ = 0xDC00 + ch;
4646 s++;
4647 }
4648 *p = L'\0';
4649 return unicode;
4650}
4651
4652#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004653
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654/* Primary internal function which creates utf8 encoded bytes objects.
4655
4656 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004657 and allocate exactly as much space needed at the end. Else allocate the
4658 maximum possible needed (4 result bytes per Unicode character), and return
4659 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004660*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004661PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004662_PyUnicode_AsUTF8String(PyObject *obj, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004663{
Tim Peters602f7402002-04-27 18:03:26 +00004664#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004665
Guido van Rossum98297ee2007-11-06 21:34:58 +00004666 Py_ssize_t i; /* index into s of next input byte */
4667 PyObject *result; /* result string object */
4668 char *p; /* next free byte in output buffer */
4669 Py_ssize_t nallocated; /* number of result bytes allocated */
4670 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004671 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004672 PyObject *errorHandler = NULL;
4673 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004674 int kind;
4675 void *data;
4676 Py_ssize_t size;
4677 PyUnicodeObject *unicode = (PyUnicodeObject *)obj;
4678#if SIZEOF_WCHAR_T == 2
4679 Py_ssize_t wchar_offset = 0;
4680#endif
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004681
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004682 if (!PyUnicode_Check(unicode)) {
4683 PyErr_BadArgument();
4684 return NULL;
4685 }
4686
4687 if (PyUnicode_READY(unicode) == -1)
4688 return NULL;
4689
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004690 if (PyUnicode_UTF8(unicode))
4691 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4692 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004693
4694 kind = PyUnicode_KIND(unicode);
4695 data = PyUnicode_DATA(unicode);
4696 size = PyUnicode_GET_LENGTH(unicode);
4697
Tim Peters602f7402002-04-27 18:03:26 +00004698 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004699
Tim Peters602f7402002-04-27 18:03:26 +00004700 if (size <= MAX_SHORT_UNICHARS) {
4701 /* Write into the stack buffer; nallocated can't overflow.
4702 * At the end, we'll allocate exactly as much heap space as it
4703 * turns out we need.
4704 */
4705 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004706 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004707 p = stackbuf;
4708 }
4709 else {
4710 /* Overallocate on the heap, and give the excess back at the end. */
4711 nallocated = size * 4;
4712 if (nallocated / 4 != size) /* overflow! */
4713 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004714 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004715 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004716 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004717 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004718 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004719
Tim Peters602f7402002-04-27 18:03:26 +00004720 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004721 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004722
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004723 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004724 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004725 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004726
Guido van Rossumd57fd912000-03-10 22:53:23 +00004727 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004728 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004729 *p++ = (char)(0xc0 | (ch >> 6));
4730 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004731 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004732 Py_ssize_t newpos;
4733 PyObject *rep;
4734 Py_ssize_t repsize, k, startpos;
4735 startpos = i-1;
4736#if SIZEOF_WCHAR_T == 2
4737 startpos += wchar_offset;
Victor Stinner445a6232010-04-22 20:01:57 +00004738#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 rep = unicode_encode_call_errorhandler(
4740 errors, &errorHandler, "utf-8", "surrogates not allowed",
4741 PyUnicode_AS_UNICODE(unicode), PyUnicode_GET_SIZE(unicode),
4742 &exc, startpos, startpos+1, &newpos);
4743 if (!rep)
4744 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004745
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004746 if (PyBytes_Check(rep))
4747 repsize = PyBytes_GET_SIZE(rep);
4748 else
4749 repsize = PyUnicode_GET_SIZE(rep);
4750
4751 if (repsize > 4) {
4752 Py_ssize_t offset;
4753
4754 if (result == NULL)
4755 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004756 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004757 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004759 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4760 /* integer overflow */
4761 PyErr_NoMemory();
4762 goto error;
4763 }
4764 nallocated += repsize - 4;
4765 if (result != NULL) {
4766 if (_PyBytes_Resize(&result, nallocated) < 0)
4767 goto error;
4768 } else {
4769 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004770 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004771 goto error;
4772 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4773 }
4774 p = PyBytes_AS_STRING(result) + offset;
4775 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004776
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 if (PyBytes_Check(rep)) {
4778 char *prep = PyBytes_AS_STRING(rep);
4779 for(k = repsize; k > 0; k--)
4780 *p++ = *prep++;
4781 } else /* rep is unicode */ {
4782 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4783 Py_UNICODE c;
4784
4785 for(k=0; k<repsize; k++) {
4786 c = prep[k];
4787 if (0x80 <= c) {
4788 raise_encode_exception(&exc, "utf-8",
4789 PyUnicode_AS_UNICODE(unicode),
4790 size, i-1, i,
4791 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004792 goto error;
4793 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004794 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004795 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004796 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004798 } else if (ch < 0x10000) {
4799 *p++ = (char)(0xe0 | (ch >> 12));
4800 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4801 *p++ = (char)(0x80 | (ch & 0x3f));
4802 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004803 /* Encode UCS4 Unicode ordinals */
4804 *p++ = (char)(0xf0 | (ch >> 18));
4805 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4806 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4807 *p++ = (char)(0x80 | (ch & 0x3f));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004808#if SIZEOF_WCHAR_T == 2
4809 wchar_offset++;
4810#endif
Tim Peters602f7402002-04-27 18:03:26 +00004811 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004812 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004813
Guido van Rossum98297ee2007-11-06 21:34:58 +00004814 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004815 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004816 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004817 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004818 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004819 }
4820 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004821 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004822 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004823 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004824 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004825 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004826
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004827 Py_XDECREF(errorHandler);
4828 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004829 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004830 error:
4831 Py_XDECREF(errorHandler);
4832 Py_XDECREF(exc);
4833 Py_XDECREF(result);
4834 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004835
Tim Peters602f7402002-04-27 18:03:26 +00004836#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004837}
4838
Alexander Belopolsky40018472011-02-26 01:02:56 +00004839PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004840PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4841 Py_ssize_t size,
4842 const char *errors)
4843{
4844 PyObject *v, *unicode;
4845
4846 unicode = PyUnicode_FromUnicode(s, size);
4847 if (unicode == NULL)
4848 return NULL;
4849 v = _PyUnicode_AsUTF8String(unicode, errors);
4850 Py_DECREF(unicode);
4851 return v;
4852}
4853
4854PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004855PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004856{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004857 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004858}
4859
Walter Dörwald41980ca2007-08-16 21:55:45 +00004860/* --- UTF-32 Codec ------------------------------------------------------- */
4861
4862PyObject *
4863PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004864 Py_ssize_t size,
4865 const char *errors,
4866 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004867{
4868 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4869}
4870
4871PyObject *
4872PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004873 Py_ssize_t size,
4874 const char *errors,
4875 int *byteorder,
4876 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004877{
4878 const char *starts = s;
4879 Py_ssize_t startinpos;
4880 Py_ssize_t endinpos;
4881 Py_ssize_t outpos;
4882 PyUnicodeObject *unicode;
4883 Py_UNICODE *p;
4884#ifndef Py_UNICODE_WIDE
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004885 int pairs = 0;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004886 const unsigned char *qq;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004887#else
4888 const int pairs = 0;
4889#endif
Mark Dickinson7db923c2010-06-12 09:10:14 +00004890 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004891 int bo = 0; /* assume native ordering by default */
4892 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004893 /* Offsets from q for retrieving bytes in the right order. */
4894#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4895 int iorder[] = {0, 1, 2, 3};
4896#else
4897 int iorder[] = {3, 2, 1, 0};
4898#endif
4899 PyObject *errorHandler = NULL;
4900 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004901
Walter Dörwald41980ca2007-08-16 21:55:45 +00004902 q = (unsigned char *)s;
4903 e = q + size;
4904
4905 if (byteorder)
4906 bo = *byteorder;
4907
4908 /* Check for BOM marks (U+FEFF) in the input and adjust current
4909 byte order setting accordingly. In native mode, the leading BOM
4910 mark is skipped, in all other modes, it is copied to the output
4911 stream as-is (giving a ZWNBSP character). */
4912 if (bo == 0) {
4913 if (size >= 4) {
4914 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004915 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004916#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004917 if (bom == 0x0000FEFF) {
4918 q += 4;
4919 bo = -1;
4920 }
4921 else if (bom == 0xFFFE0000) {
4922 q += 4;
4923 bo = 1;
4924 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004925#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004926 if (bom == 0x0000FEFF) {
4927 q += 4;
4928 bo = 1;
4929 }
4930 else if (bom == 0xFFFE0000) {
4931 q += 4;
4932 bo = -1;
4933 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004934#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004935 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004936 }
4937
4938 if (bo == -1) {
4939 /* force LE */
4940 iorder[0] = 0;
4941 iorder[1] = 1;
4942 iorder[2] = 2;
4943 iorder[3] = 3;
4944 }
4945 else if (bo == 1) {
4946 /* force BE */
4947 iorder[0] = 3;
4948 iorder[1] = 2;
4949 iorder[2] = 1;
4950 iorder[3] = 0;
4951 }
4952
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004953 /* On narrow builds we split characters outside the BMP into two
4954 codepoints => count how much extra space we need. */
4955#ifndef Py_UNICODE_WIDE
4956 for (qq = q; qq < e; qq += 4)
4957 if (qq[iorder[2]] != 0 || qq[iorder[3]] != 0)
4958 pairs++;
4959#endif
4960
4961 /* This might be one to much, because of a BOM */
4962 unicode = _PyUnicode_New((size+3)/4+pairs);
4963 if (!unicode)
4964 return NULL;
4965 if (size == 0)
4966 return (PyObject *)unicode;
4967
4968 /* Unpack UTF-32 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004969 p = PyUnicode_AS_UNICODE(unicode);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004970
Walter Dörwald41980ca2007-08-16 21:55:45 +00004971 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 Py_UCS4 ch;
4973 /* remaining bytes at the end? (size should be divisible by 4) */
4974 if (e-q<4) {
4975 if (consumed)
4976 break;
4977 errmsg = "truncated data";
4978 startinpos = ((const char *)q)-starts;
4979 endinpos = ((const char *)e)-starts;
4980 goto utf32Error;
4981 /* The remaining input chars are ignored if the callback
4982 chooses to skip the input */
4983 }
4984 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4985 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004986
Benjamin Peterson29060642009-01-31 22:14:21 +00004987 if (ch >= 0x110000)
4988 {
4989 errmsg = "codepoint not in range(0x110000)";
4990 startinpos = ((const char *)q)-starts;
4991 endinpos = startinpos+4;
4992 goto utf32Error;
4993 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004994#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00004995 if (ch >= 0x10000)
4996 {
4997 *p++ = 0xD800 | ((ch-0x10000) >> 10);
4998 *p++ = 0xDC00 | ((ch-0x10000) & 0x3FF);
4999 }
5000 else
Walter Dörwald41980ca2007-08-16 21:55:45 +00005001#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005002 *p++ = ch;
5003 q += 4;
5004 continue;
5005 utf32Error:
5006 outpos = p-PyUnicode_AS_UNICODE(unicode);
5007 if (unicode_decode_call_errorhandler(
5008 errors, &errorHandler,
5009 "utf32", errmsg,
5010 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
5011 &unicode, &outpos, &p))
5012 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005013 }
5014
5015 if (byteorder)
5016 *byteorder = bo;
5017
5018 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005019 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005020
5021 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005022 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005023 goto onError;
5024
5025 Py_XDECREF(errorHandler);
5026 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005027#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005028 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005029 Py_DECREF(unicode);
5030 return NULL;
5031 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005032#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005033 assert(_PyUnicode_CheckConsistency(unicode, 1));
Walter Dörwald41980ca2007-08-16 21:55:45 +00005034 return (PyObject *)unicode;
5035
Benjamin Peterson29060642009-01-31 22:14:21 +00005036 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005037 Py_DECREF(unicode);
5038 Py_XDECREF(errorHandler);
5039 Py_XDECREF(exc);
5040 return NULL;
5041}
5042
5043PyObject *
5044PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005045 Py_ssize_t size,
5046 const char *errors,
5047 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005048{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005049 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005051 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005053 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005054#else
5055 const int pairs = 0;
5056#endif
5057 /* Offsets from p for storing byte pairs in the right order. */
5058#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5059 int iorder[] = {0, 1, 2, 3};
5060#else
5061 int iorder[] = {3, 2, 1, 0};
5062#endif
5063
Benjamin Peterson29060642009-01-31 22:14:21 +00005064#define STORECHAR(CH) \
5065 do { \
5066 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5067 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5068 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5069 p[iorder[0]] = (CH) & 0xff; \
5070 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005071 } while(0)
5072
5073 /* In narrow builds we can output surrogate pairs as one codepoint,
5074 so we need less space. */
5075#ifndef Py_UNICODE_WIDE
5076 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005077 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5078 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5079 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005080#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005081 nsize = (size - pairs + (byteorder == 0));
5082 bytesize = nsize * 4;
5083 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005084 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005085 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086 if (v == NULL)
5087 return NULL;
5088
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005089 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005090 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005091 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005093 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005094
5095 if (byteorder == -1) {
5096 /* force LE */
5097 iorder[0] = 0;
5098 iorder[1] = 1;
5099 iorder[2] = 2;
5100 iorder[3] = 3;
5101 }
5102 else if (byteorder == 1) {
5103 /* force BE */
5104 iorder[0] = 3;
5105 iorder[1] = 2;
5106 iorder[2] = 1;
5107 iorder[3] = 0;
5108 }
5109
5110 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005111 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005112#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005113 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5114 Py_UCS4 ch2 = *s;
5115 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5116 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5117 s++;
5118 size--;
5119 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005120 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005121#endif
5122 STORECHAR(ch);
5123 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005124
5125 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005126 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005127#undef STORECHAR
5128}
5129
Alexander Belopolsky40018472011-02-26 01:02:56 +00005130PyObject *
5131PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005132{
5133 if (!PyUnicode_Check(unicode)) {
5134 PyErr_BadArgument();
5135 return NULL;
5136 }
5137 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005138 PyUnicode_GET_SIZE(unicode),
5139 NULL,
5140 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005141}
5142
Guido van Rossumd57fd912000-03-10 22:53:23 +00005143/* --- UTF-16 Codec ------------------------------------------------------- */
5144
Tim Peters772747b2001-08-09 22:21:55 +00005145PyObject *
5146PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005147 Py_ssize_t size,
5148 const char *errors,
5149 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005150{
Walter Dörwald69652032004-09-07 20:24:22 +00005151 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5152}
5153
Antoine Pitrouab868312009-01-10 15:40:25 +00005154/* Two masks for fast checking of whether a C 'long' may contain
5155 UTF16-encoded surrogate characters. This is an efficient heuristic,
5156 assuming that non-surrogate characters with a code point >= 0x8000 are
5157 rare in most input.
5158 FAST_CHAR_MASK is used when the input is in native byte ordering,
5159 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005160*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005161#if (SIZEOF_LONG == 8)
5162# define FAST_CHAR_MASK 0x8000800080008000L
5163# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5164#elif (SIZEOF_LONG == 4)
5165# define FAST_CHAR_MASK 0x80008000L
5166# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5167#else
5168# error C 'long' size should be either 4 or 8!
5169#endif
5170
Walter Dörwald69652032004-09-07 20:24:22 +00005171PyObject *
5172PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005173 Py_ssize_t size,
5174 const char *errors,
5175 int *byteorder,
5176 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005177{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005178 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005179 Py_ssize_t startinpos;
5180 Py_ssize_t endinpos;
5181 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005182 PyUnicodeObject *unicode;
5183 Py_UNICODE *p;
Antoine Pitrouab868312009-01-10 15:40:25 +00005184 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005185 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005186 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005187 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005188 /* Offsets from q for retrieving byte pairs in the right order. */
5189#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5190 int ihi = 1, ilo = 0;
5191#else
5192 int ihi = 0, ilo = 1;
5193#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005194 PyObject *errorHandler = NULL;
5195 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005196
5197 /* Note: size will always be longer than the resulting Unicode
5198 character count */
5199 unicode = _PyUnicode_New(size);
5200 if (!unicode)
5201 return NULL;
5202 if (size == 0)
5203 return (PyObject *)unicode;
5204
5205 /* Unpack UTF-16 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005206 p = PyUnicode_AS_UNICODE(unicode);
Tim Peters772747b2001-08-09 22:21:55 +00005207 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005208 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005209
5210 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005211 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005213 /* Check for BOM marks (U+FEFF) in the input and adjust current
5214 byte order setting accordingly. In native mode, the leading BOM
5215 mark is skipped, in all other modes, it is copied to the output
5216 stream as-is (giving a ZWNBSP character). */
5217 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005218 if (size >= 2) {
5219 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005220#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005221 if (bom == 0xFEFF) {
5222 q += 2;
5223 bo = -1;
5224 }
5225 else if (bom == 0xFFFE) {
5226 q += 2;
5227 bo = 1;
5228 }
Tim Petersced69f82003-09-16 20:30:58 +00005229#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005230 if (bom == 0xFEFF) {
5231 q += 2;
5232 bo = 1;
5233 }
5234 else if (bom == 0xFFFE) {
5235 q += 2;
5236 bo = -1;
5237 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005238#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005240 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005241
Tim Peters772747b2001-08-09 22:21:55 +00005242 if (bo == -1) {
5243 /* force LE */
5244 ihi = 1;
5245 ilo = 0;
5246 }
5247 else if (bo == 1) {
5248 /* force BE */
5249 ihi = 0;
5250 ilo = 1;
5251 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005252#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5253 native_ordering = ilo < ihi;
5254#else
5255 native_ordering = ilo > ihi;
5256#endif
Tim Peters772747b2001-08-09 22:21:55 +00005257
Antoine Pitrouab868312009-01-10 15:40:25 +00005258 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005259 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005260 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005261 /* First check for possible aligned read of a C 'long'. Unaligned
5262 reads are more expensive, better to defer to another iteration. */
5263 if (!((size_t) q & LONG_PTR_MASK)) {
5264 /* Fast path for runs of non-surrogate chars. */
5265 register const unsigned char *_q = q;
5266 Py_UNICODE *_p = p;
5267 if (native_ordering) {
5268 /* Native ordering is simple: as long as the input cannot
5269 possibly contain a surrogate char, do an unrolled copy
5270 of several 16-bit code points to the target object.
5271 The non-surrogate check is done on several input bytes
5272 at a time (as many as a C 'long' can contain). */
5273 while (_q < aligned_end) {
5274 unsigned long data = * (unsigned long *) _q;
5275 if (data & FAST_CHAR_MASK)
5276 break;
5277 _p[0] = ((unsigned short *) _q)[0];
5278 _p[1] = ((unsigned short *) _q)[1];
5279#if (SIZEOF_LONG == 8)
5280 _p[2] = ((unsigned short *) _q)[2];
5281 _p[3] = ((unsigned short *) _q)[3];
5282#endif
5283 _q += SIZEOF_LONG;
5284 _p += SIZEOF_LONG / 2;
5285 }
5286 }
5287 else {
5288 /* Byteswapped ordering is similar, but we must decompose
5289 the copy bytewise, and take care of zero'ing out the
5290 upper bytes if the target object is in 32-bit units
5291 (that is, in UCS-4 builds). */
5292 while (_q < aligned_end) {
5293 unsigned long data = * (unsigned long *) _q;
5294 if (data & SWAPPED_FAST_CHAR_MASK)
5295 break;
5296 /* Zero upper bytes in UCS-4 builds */
5297#if (Py_UNICODE_SIZE > 2)
5298 _p[0] = 0;
5299 _p[1] = 0;
5300#if (SIZEOF_LONG == 8)
5301 _p[2] = 0;
5302 _p[3] = 0;
5303#endif
5304#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005305 /* Issue #4916; UCS-4 builds on big endian machines must
5306 fill the two last bytes of each 4-byte unit. */
5307#if (!defined(BYTEORDER_IS_LITTLE_ENDIAN) && Py_UNICODE_SIZE > 2)
5308# define OFF 2
5309#else
5310# define OFF 0
Antoine Pitrouab868312009-01-10 15:40:25 +00005311#endif
Antoine Pitroud6e8de12009-01-11 23:56:55 +00005312 ((unsigned char *) _p)[OFF + 1] = _q[0];
5313 ((unsigned char *) _p)[OFF + 0] = _q[1];
5314 ((unsigned char *) _p)[OFF + 1 + Py_UNICODE_SIZE] = _q[2];
5315 ((unsigned char *) _p)[OFF + 0 + Py_UNICODE_SIZE] = _q[3];
5316#if (SIZEOF_LONG == 8)
5317 ((unsigned char *) _p)[OFF + 1 + 2 * Py_UNICODE_SIZE] = _q[4];
5318 ((unsigned char *) _p)[OFF + 0 + 2 * Py_UNICODE_SIZE] = _q[5];
5319 ((unsigned char *) _p)[OFF + 1 + 3 * Py_UNICODE_SIZE] = _q[6];
5320 ((unsigned char *) _p)[OFF + 0 + 3 * Py_UNICODE_SIZE] = _q[7];
5321#endif
5322#undef OFF
Antoine Pitrouab868312009-01-10 15:40:25 +00005323 _q += SIZEOF_LONG;
5324 _p += SIZEOF_LONG / 2;
5325 }
5326 }
5327 p = _p;
5328 q = _q;
5329 if (q >= e)
5330 break;
5331 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005332 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005333
Benjamin Peterson14339b62009-01-31 16:36:08 +00005334 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005335
5336 if (ch < 0xD800 || ch > 0xDFFF) {
5337 *p++ = ch;
5338 continue;
5339 }
5340
5341 /* UTF-16 code pair: */
5342 if (q > e) {
5343 errmsg = "unexpected end of data";
5344 startinpos = (((const char *)q) - 2) - starts;
5345 endinpos = ((const char *)e) + 1 - starts;
5346 goto utf16Error;
5347 }
5348 if (0xD800 <= ch && ch <= 0xDBFF) {
5349 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5350 q += 2;
5351 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Fredrik Lundh8f455852001-06-27 18:59:43 +00005352#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005353 *p++ = ch;
5354 *p++ = ch2;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005355#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 *p++ = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005357#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 continue;
5359 }
5360 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005361 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005362 startinpos = (((const char *)q)-4)-starts;
5363 endinpos = startinpos+2;
5364 goto utf16Error;
5365 }
5366
Benjamin Peterson14339b62009-01-31 16:36:08 +00005367 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005368 errmsg = "illegal encoding";
5369 startinpos = (((const char *)q)-2)-starts;
5370 endinpos = startinpos+2;
5371 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005372
Benjamin Peterson29060642009-01-31 22:14:21 +00005373 utf16Error:
5374 outpos = p - PyUnicode_AS_UNICODE(unicode);
5375 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005376 errors,
5377 &errorHandler,
5378 "utf16", errmsg,
5379 &starts,
5380 (const char **)&e,
5381 &startinpos,
5382 &endinpos,
5383 &exc,
5384 (const char **)&q,
5385 &unicode,
5386 &outpos,
5387 &p))
Benjamin Peterson29060642009-01-31 22:14:21 +00005388 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005389 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005390 /* remaining byte at the end? (size should be even) */
5391 if (e == q) {
5392 if (!consumed) {
5393 errmsg = "truncated data";
5394 startinpos = ((const char *)q) - starts;
5395 endinpos = ((const char *)e) + 1 - starts;
5396 outpos = p - PyUnicode_AS_UNICODE(unicode);
5397 if (unicode_decode_call_errorhandler(
5398 errors,
5399 &errorHandler,
5400 "utf16", errmsg,
5401 &starts,
5402 (const char **)&e,
5403 &startinpos,
5404 &endinpos,
5405 &exc,
5406 (const char **)&q,
5407 &unicode,
5408 &outpos,
5409 &p))
5410 goto onError;
5411 /* The remaining input chars are ignored if the callback
5412 chooses to skip the input */
5413 }
5414 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005415
5416 if (byteorder)
5417 *byteorder = bo;
5418
Walter Dörwald69652032004-09-07 20:24:22 +00005419 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005420 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005421
Guido van Rossumd57fd912000-03-10 22:53:23 +00005422 /* Adjust length */
Victor Stinnerfe226c02011-10-03 03:52:20 +02005423 if (PyUnicode_Resize((PyObject**)&unicode, p - PyUnicode_AS_UNICODE(unicode)) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424 goto onError;
5425
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005426 Py_XDECREF(errorHandler);
5427 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005428#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005429 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005430 Py_DECREF(unicode);
5431 return NULL;
5432 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005433#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005434 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005435 return (PyObject *)unicode;
5436
Benjamin Peterson29060642009-01-31 22:14:21 +00005437 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005438 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005439 Py_XDECREF(errorHandler);
5440 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005441 return NULL;
5442}
5443
Antoine Pitrouab868312009-01-10 15:40:25 +00005444#undef FAST_CHAR_MASK
5445#undef SWAPPED_FAST_CHAR_MASK
5446
Tim Peters772747b2001-08-09 22:21:55 +00005447PyObject *
5448PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005449 Py_ssize_t size,
5450 const char *errors,
5451 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005452{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005453 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005454 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005455 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005456#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005457 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005458#else
5459 const int pairs = 0;
5460#endif
Tim Peters772747b2001-08-09 22:21:55 +00005461 /* Offsets from p for storing byte pairs in the right order. */
5462#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5463 int ihi = 1, ilo = 0;
5464#else
5465 int ihi = 0, ilo = 1;
5466#endif
5467
Benjamin Peterson29060642009-01-31 22:14:21 +00005468#define STORECHAR(CH) \
5469 do { \
5470 p[ihi] = ((CH) >> 8) & 0xff; \
5471 p[ilo] = (CH) & 0xff; \
5472 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005473 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005474
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005475#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005476 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005477 if (s[i] >= 0x10000)
5478 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005479#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005480 /* 2 * (size + pairs + (byteorder == 0)) */
5481 if (size > PY_SSIZE_T_MAX ||
5482 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005483 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005484 nsize = size + pairs + (byteorder == 0);
5485 bytesize = nsize * 2;
5486 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005487 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005488 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005489 if (v == NULL)
5490 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005491
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005492 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005493 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005494 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005495 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005496 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005497
5498 if (byteorder == -1) {
5499 /* force LE */
5500 ihi = 1;
5501 ilo = 0;
5502 }
5503 else if (byteorder == 1) {
5504 /* force BE */
5505 ihi = 0;
5506 ilo = 1;
5507 }
5508
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005509 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005510 Py_UNICODE ch = *s++;
5511 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005512#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005513 if (ch >= 0x10000) {
5514 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5515 ch = 0xD800 | ((ch-0x10000) >> 10);
5516 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005517#endif
Tim Peters772747b2001-08-09 22:21:55 +00005518 STORECHAR(ch);
5519 if (ch2)
5520 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005521 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005522
5523 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005524 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005525#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005526}
5527
Alexander Belopolsky40018472011-02-26 01:02:56 +00005528PyObject *
5529PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530{
5531 if (!PyUnicode_Check(unicode)) {
5532 PyErr_BadArgument();
5533 return NULL;
5534 }
5535 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005536 PyUnicode_GET_SIZE(unicode),
5537 NULL,
5538 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005539}
5540
5541/* --- Unicode Escape Codec ----------------------------------------------- */
5542
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005543/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5544 if all the escapes in the string make it still a valid ASCII string.
5545 Returns -1 if any escapes were found which cause the string to
5546 pop out of ASCII range. Otherwise returns the length of the
5547 required buffer to hold the string.
5548 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005549static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005550length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5551{
5552 const unsigned char *p = (const unsigned char *)s;
5553 const unsigned char *end = p + size;
5554 Py_ssize_t length = 0;
5555
5556 if (size < 0)
5557 return -1;
5558
5559 for (; p < end; ++p) {
5560 if (*p > 127) {
5561 /* Non-ASCII */
5562 return -1;
5563 }
5564 else if (*p != '\\') {
5565 /* Normal character */
5566 ++length;
5567 }
5568 else {
5569 /* Backslash-escape, check next char */
5570 ++p;
5571 /* Escape sequence reaches till end of string or
5572 non-ASCII follow-up. */
5573 if (p >= end || *p > 127)
5574 return -1;
5575 switch (*p) {
5576 case '\n':
5577 /* backslash + \n result in zero characters */
5578 break;
5579 case '\\': case '\'': case '\"':
5580 case 'b': case 'f': case 't':
5581 case 'n': case 'r': case 'v': case 'a':
5582 ++length;
5583 break;
5584 case '0': case '1': case '2': case '3':
5585 case '4': case '5': case '6': case '7':
5586 case 'x': case 'u': case 'U': case 'N':
5587 /* these do not guarantee ASCII characters */
5588 return -1;
5589 default:
5590 /* count the backslash + the other character */
5591 length += 2;
5592 }
5593 }
5594 }
5595 return length;
5596}
5597
5598/* Similar to PyUnicode_WRITE but either write into wstr field
5599 or treat string as ASCII. */
5600#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5601 do { \
5602 if ((kind) != PyUnicode_WCHAR_KIND) \
5603 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5604 else \
5605 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5606 } while (0)
5607
5608#define WRITE_WSTR(buf, index, value) \
5609 assert(kind == PyUnicode_WCHAR_KIND), \
5610 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5611
5612
Fredrik Lundh06d12682001-01-24 07:59:11 +00005613static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005614
Alexander Belopolsky40018472011-02-26 01:02:56 +00005615PyObject *
5616PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005617 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005618 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005619{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005620 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005621 Py_ssize_t startinpos;
5622 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005623 int j;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005624 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005625 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005627 char* message;
5628 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005629 PyObject *errorHandler = NULL;
5630 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005631 Py_ssize_t ascii_length;
5632 Py_ssize_t i;
5633 int kind;
5634 void *data;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005635
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005636 ascii_length = length_of_escaped_ascii_string(s, size);
5637
5638 /* After length_of_escaped_ascii_string() there are two alternatives,
5639 either the string is pure ASCII with named escapes like \n, etc.
5640 and we determined it's exact size (common case)
5641 or it contains \x, \u, ... escape sequences. then we create a
5642 legacy wchar string and resize it at the end of this function. */
5643 if (ascii_length >= 0) {
5644 v = (PyUnicodeObject *)PyUnicode_New(ascii_length, 127);
5645 if (!v)
5646 goto onError;
5647 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
5648 kind = PyUnicode_1BYTE_KIND;
5649 data = PyUnicode_DATA(v);
5650 }
5651 else {
5652 /* Escaped strings will always be longer than the resulting
5653 Unicode string, so we start with size here and then reduce the
5654 length after conversion to the true value.
5655 (but if the error callback returns a long replacement string
5656 we'll have to allocate more space) */
5657 v = _PyUnicode_New(size);
5658 if (!v)
5659 goto onError;
5660 kind = PyUnicode_WCHAR_KIND;
5661 data = PyUnicode_AS_UNICODE(v);
5662 }
5663
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 if (size == 0)
5665 return (PyObject *)v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005666 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005668
Guido van Rossumd57fd912000-03-10 22:53:23 +00005669 while (s < end) {
5670 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005671 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005672 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005674 if (kind == PyUnicode_WCHAR_KIND) {
5675 assert(i < _PyUnicode_WSTR_LENGTH(v));
5676 }
5677 else {
5678 /* The only case in which i == ascii_length is a backslash
5679 followed by a newline. */
5680 assert(i <= ascii_length);
5681 }
5682
Guido van Rossumd57fd912000-03-10 22:53:23 +00005683 /* Non-escape characters are interpreted as Unicode ordinals */
5684 if (*s != '\\') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005685 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char) *s++);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005686 continue;
5687 }
5688
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005689 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005690 /* \ - Escapes */
5691 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005692 c = *s++;
5693 if (s > end)
5694 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005695
5696 if (kind == PyUnicode_WCHAR_KIND) {
5697 assert(i < _PyUnicode_WSTR_LENGTH(v));
5698 }
5699 else {
5700 /* The only case in which i == ascii_length is a backslash
5701 followed by a newline. */
5702 assert(i < ascii_length || (i == ascii_length && c == '\n'));
5703 }
5704
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005705 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005706
Benjamin Peterson29060642009-01-31 22:14:21 +00005707 /* \x escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005708 case '\n': break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005709 case '\\': WRITE_ASCII_OR_WSTR(kind, data, i++, '\\'); break;
5710 case '\'': WRITE_ASCII_OR_WSTR(kind, data, i++, '\''); break;
5711 case '\"': WRITE_ASCII_OR_WSTR(kind, data, i++, '\"'); break;
5712 case 'b': WRITE_ASCII_OR_WSTR(kind, data, i++, '\b'); break;
5713 /* FF */
5714 case 'f': WRITE_ASCII_OR_WSTR(kind, data, i++, '\014'); break;
5715 case 't': WRITE_ASCII_OR_WSTR(kind, data, i++, '\t'); break;
5716 case 'n': WRITE_ASCII_OR_WSTR(kind, data, i++, '\n'); break;
5717 case 'r': WRITE_ASCII_OR_WSTR(kind, data, i++, '\r'); break;
5718 /* VT */
5719 case 'v': WRITE_ASCII_OR_WSTR(kind, data, i++, '\013'); break;
5720 /* BEL, not classic C */
5721 case 'a': WRITE_ASCII_OR_WSTR(kind, data, i++, '\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005722
Benjamin Peterson29060642009-01-31 22:14:21 +00005723 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005724 case '0': case '1': case '2': case '3':
5725 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005726 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005727 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005728 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005729 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005730 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005731 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005732 WRITE_WSTR(data, i++, x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733 break;
5734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 /* hex escapes */
5736 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005737 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005738 digits = 2;
5739 message = "truncated \\xXX escape";
5740 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005741
Benjamin Peterson29060642009-01-31 22:14:21 +00005742 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005743 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005744 digits = 4;
5745 message = "truncated \\uXXXX escape";
5746 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005747
Benjamin Peterson29060642009-01-31 22:14:21 +00005748 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005749 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005750 digits = 8;
5751 message = "truncated \\UXXXXXXXX escape";
5752 hexescape:
5753 chr = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005754 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005755 if (s+digits>end) {
5756 endinpos = size;
5757 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005758 errors, &errorHandler,
5759 "unicodeescape", "end of string in escape sequence",
5760 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005761 &v, &i, &p))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005762 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005763 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005764 goto nextByte;
5765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005766 for (j = 0; j < digits; ++j) {
5767 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005768 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005769 endinpos = (s+j+1)-starts;
5770 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005771 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005772 errors, &errorHandler,
5773 "unicodeescape", message,
5774 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005775 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005776 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005777 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005778 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005779 }
5780 chr = (chr<<4) & ~0xF;
5781 if (c >= '0' && c <= '9')
5782 chr += c - '0';
5783 else if (c >= 'a' && c <= 'f')
5784 chr += 10 + c - 'a';
5785 else
5786 chr += 10 + c - 'A';
5787 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005788 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005789 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005790 /* _decoding_error will have already written into the
5791 target buffer. */
5792 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005793 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005794 /* when we get here, chr is a 32-bit unicode character */
5795 if (chr <= 0xffff)
5796 /* UCS-2 character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005797 WRITE_WSTR(data, i++, chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005798 else if (chr <= 0x10ffff) {
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005799 /* UCS-4 character. Either store directly, or as
Walter Dörwald8c077222002-03-25 11:16:18 +00005800 surrogate pair. */
Fredrik Lundh8f455852001-06-27 18:59:43 +00005801#ifdef Py_UNICODE_WIDE
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005802 WRITE_WSTR(data, i++, chr);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005803#else
Fredrik Lundhdf846752000-09-03 11:29:49 +00005804 chr -= 0x10000L;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005805 WRITE_WSTR(data, i++, 0xD800 + (Py_UNICODE) (chr >> 10));
5806 WRITE_WSTR(data, i++, 0xDC00 + (Py_UNICODE) (chr & 0x03FF));
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005807#endif
Fredrik Lundhdf846752000-09-03 11:29:49 +00005808 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005809 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005810 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005811 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005812 errors, &errorHandler,
5813 "unicodeescape", "illegal Unicode character",
5814 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005815 &v, &i, &p))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005816 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005817 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005818 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005819 break;
5820
Benjamin Peterson29060642009-01-31 22:14:21 +00005821 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822 case 'N':
5823 message = "malformed \\N character escape";
5824 if (ucnhash_CAPI == NULL) {
5825 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005826 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5827 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005828 if (ucnhash_CAPI == NULL)
5829 goto ucnhashError;
5830 }
5831 if (*s == '{') {
5832 const char *start = s+1;
5833 /* look for the closing brace */
5834 while (*s != '}' && s < end)
5835 s++;
5836 if (s > start && s < end && *s == '}') {
5837 /* found a name. look it up in the unicode database */
5838 message = "unknown Unicode character name";
5839 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005840 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005841 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005842 goto store;
5843 }
5844 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005845 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005846 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005847 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005848 errors, &errorHandler,
5849 "unicodeescape", message,
5850 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005851 &v, &i, &p))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005852 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005853 data = PyUnicode_AS_UNICODE(v);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005854 break;
5855
5856 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005857 if (s > end) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005858 assert(kind == PyUnicode_WCHAR_KIND);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005859 message = "\\ at end of string";
5860 s--;
5861 endinpos = s-starts;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005862 p = PyUnicode_AS_UNICODE(v) + i;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005863 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005864 errors, &errorHandler,
5865 "unicodeescape", message,
5866 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005867 &v, &i, &p))
Walter Dörwald8c077222002-03-25 11:16:18 +00005868 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005869 data = PyUnicode_AS_UNICODE(v);
Walter Dörwald8c077222002-03-25 11:16:18 +00005870 }
5871 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005872 WRITE_ASCII_OR_WSTR(kind, data, i++, '\\');
5873 WRITE_ASCII_OR_WSTR(kind, data, i++, (unsigned char)s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005874 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005875 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005877 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005878 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005879 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005880 /* Ensure the length prediction worked in case of ASCII strings */
5881 assert(kind == PyUnicode_WCHAR_KIND || i == ascii_length);
5882
Victor Stinnerfe226c02011-10-03 03:52:20 +02005883 if (kind == PyUnicode_WCHAR_KIND)
5884 {
5885 if (PyUnicode_Resize((PyObject**)&v, i) < 0)
5886 goto onError;
Victor Stinnerfe226c02011-10-03 03:52:20 +02005887 }
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005888 Py_XDECREF(errorHandler);
5889 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005890#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005891 if (_PyUnicode_READY_REPLACE(&v)) {
5892 Py_DECREF(v);
5893 return NULL;
5894 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005895#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005896 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897 return (PyObject *)v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005898
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005900 PyErr_SetString(
5901 PyExc_UnicodeError,
5902 "\\N escapes not supported (can't load unicodedata module)"
5903 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005904 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005905 Py_XDECREF(errorHandler);
5906 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005907 return NULL;
5908
Benjamin Peterson29060642009-01-31 22:14:21 +00005909 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005910 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005911 Py_XDECREF(errorHandler);
5912 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005913 return NULL;
5914}
5915
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005916#undef WRITE_ASCII_OR_WSTR
5917#undef WRITE_WSTR
5918
Guido van Rossumd57fd912000-03-10 22:53:23 +00005919/* Return a Unicode-Escape string version of the Unicode object.
5920
5921 If quotes is true, the string is enclosed in u"" or u'' quotes as
5922 appropriate.
5923
5924*/
5925
Alexander Belopolsky40018472011-02-26 01:02:56 +00005926PyObject *
5927PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005928 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005929{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005930 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005931 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005932
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005933#ifdef Py_UNICODE_WIDE
5934 const Py_ssize_t expandsize = 10;
5935#else
5936 const Py_ssize_t expandsize = 6;
5937#endif
5938
Thomas Wouters89f507f2006-12-13 04:49:30 +00005939 /* XXX(nnorwitz): rather than over-allocating, it would be
5940 better to choose a different scheme. Perhaps scan the
5941 first N-chars of the string and allocate based on that size.
5942 */
5943 /* Initial allocation is based on the longest-possible unichr
5944 escape.
5945
5946 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5947 unichr, so in this case it's the longest unichr escape. In
5948 narrow (UTF-16) builds this is five chars per source unichr
5949 since there are two unichrs in the surrogate pair, so in narrow
5950 (UTF-16) builds it's not the longest unichr escape.
5951
5952 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5953 so in the narrow (UTF-16) build case it's the longest unichr
5954 escape.
5955 */
5956
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005957 if (size == 0)
5958 return PyBytes_FromStringAndSize(NULL, 0);
5959
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005960 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005961 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005962
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005963 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 2
5965 + expandsize*size
5966 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 if (repr == NULL)
5968 return NULL;
5969
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005970 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 while (size-- > 0) {
5973 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005974
Walter Dörwald79e913e2007-05-12 11:08:06 +00005975 /* Escape backslashes */
5976 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005977 *p++ = '\\';
5978 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005979 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005980 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005981
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005982#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005983 /* Map 21-bit characters to '\U00xxxxxx' */
5984 else if (ch >= 0x10000) {
5985 *p++ = '\\';
5986 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005987 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5988 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5989 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5990 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5991 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5992 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5993 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5994 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005995 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005996 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005997#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005998 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5999 else if (ch >= 0xD800 && ch < 0xDC00) {
6000 Py_UNICODE ch2;
6001 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00006002
Benjamin Peterson29060642009-01-31 22:14:21 +00006003 ch2 = *s++;
6004 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006005 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006006 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6007 *p++ = '\\';
6008 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006009 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
6010 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
6011 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
6012 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
6013 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
6014 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
6015 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
6016 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00006017 continue;
6018 }
6019 /* Fall through: isolated surrogates are copied as-is */
6020 s--;
6021 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006022 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00006023#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006024
Guido van Rossumd57fd912000-03-10 22:53:23 +00006025 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00006026 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006027 *p++ = '\\';
6028 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006029 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
6030 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
6031 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6032 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006033 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006034
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006035 /* Map special whitespace to '\t', \n', '\r' */
6036 else if (ch == '\t') {
6037 *p++ = '\\';
6038 *p++ = 't';
6039 }
6040 else if (ch == '\n') {
6041 *p++ = '\\';
6042 *p++ = 'n';
6043 }
6044 else if (ch == '\r') {
6045 *p++ = '\\';
6046 *p++ = 'r';
6047 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006048
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006049 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00006050 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006051 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00006052 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006053 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6054 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006055 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006056
Guido van Rossumd57fd912000-03-10 22:53:23 +00006057 /* Copy everything else as-is */
6058 else
6059 *p++ = (char) ch;
6060 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006062 assert(p - PyBytes_AS_STRING(repr) > 0);
6063 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6064 return NULL;
6065 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006066}
6067
Alexander Belopolsky40018472011-02-26 01:02:56 +00006068PyObject *
6069PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006070{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006071 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006072 if (!PyUnicode_Check(unicode)) {
6073 PyErr_BadArgument();
6074 return NULL;
6075 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00006076 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6077 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006078 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006079}
6080
6081/* --- Raw Unicode Escape Codec ------------------------------------------- */
6082
Alexander Belopolsky40018472011-02-26 01:02:56 +00006083PyObject *
6084PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006085 Py_ssize_t size,
6086 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006087{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006088 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006089 Py_ssize_t startinpos;
6090 Py_ssize_t endinpos;
6091 Py_ssize_t outpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006092 PyUnicodeObject *v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006093 Py_UNICODE *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006094 const char *end;
6095 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006096 PyObject *errorHandler = NULL;
6097 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006098
Guido van Rossumd57fd912000-03-10 22:53:23 +00006099 /* Escaped strings will always be longer than the resulting
6100 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006101 length after conversion to the true value. (But decoding error
6102 handler might have to resize the string) */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006103 v = _PyUnicode_New(size);
6104 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006106 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 return (PyObject *)v;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006108 p = PyUnicode_AS_UNICODE(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109 end = s + size;
6110 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006111 unsigned char c;
6112 Py_UCS4 x;
6113 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006114 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 /* Non-escape characters are interpreted as Unicode ordinals */
6117 if (*s != '\\') {
6118 *p++ = (unsigned char)*s++;
6119 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006120 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006121 startinpos = s-starts;
6122
6123 /* \u-escapes are only interpreted iff the number of leading
6124 backslashes if odd */
6125 bs = s;
6126 for (;s < end;) {
6127 if (*s != '\\')
6128 break;
6129 *p++ = (unsigned char)*s++;
6130 }
6131 if (((s - bs) & 1) == 0 ||
6132 s >= end ||
6133 (*s != 'u' && *s != 'U')) {
6134 continue;
6135 }
6136 p--;
6137 count = *s=='u' ? 4 : 8;
6138 s++;
6139
6140 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
6141 outpos = p-PyUnicode_AS_UNICODE(v);
6142 for (x = 0, i = 0; i < count; ++i, ++s) {
6143 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006144 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006145 endinpos = s-starts;
6146 if (unicode_decode_call_errorhandler(
6147 errors, &errorHandler,
6148 "rawunicodeescape", "truncated \\uXXXX",
6149 &starts, &end, &startinpos, &endinpos, &exc, &s,
6150 &v, &outpos, &p))
6151 goto onError;
6152 goto nextByte;
6153 }
6154 x = (x<<4) & ~0xF;
6155 if (c >= '0' && c <= '9')
6156 x += c - '0';
6157 else if (c >= 'a' && c <= 'f')
6158 x += 10 + c - 'a';
6159 else
6160 x += 10 + c - 'A';
6161 }
Christian Heimesfe337bf2008-03-23 21:54:12 +00006162 if (x <= 0xffff)
Benjamin Peterson29060642009-01-31 22:14:21 +00006163 /* UCS-2 character */
6164 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006165 else if (x <= 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006166 /* UCS-4 character. Either store directly, or as
6167 surrogate pair. */
Christian Heimesfe337bf2008-03-23 21:54:12 +00006168#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 *p++ = (Py_UNICODE) x;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006170#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006171 x -= 0x10000L;
6172 *p++ = 0xD800 + (Py_UNICODE) (x >> 10);
6173 *p++ = 0xDC00 + (Py_UNICODE) (x & 0x03FF);
Christian Heimesfe337bf2008-03-23 21:54:12 +00006174#endif
6175 } else {
6176 endinpos = s-starts;
6177 outpos = p-PyUnicode_AS_UNICODE(v);
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006178 if (unicode_decode_call_errorhandler(
6179 errors, &errorHandler,
6180 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006181 &starts, &end, &startinpos, &endinpos, &exc, &s,
6182 &v, &outpos, &p))
6183 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006184 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006185 nextByte:
6186 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006187 }
Victor Stinnerfe226c02011-10-03 03:52:20 +02006188 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006189 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006190 Py_XDECREF(errorHandler);
6191 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006192#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006193 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006194 Py_DECREF(v);
6195 return NULL;
6196 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006197#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006198 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006200
Benjamin Peterson29060642009-01-31 22:14:21 +00006201 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006203 Py_XDECREF(errorHandler);
6204 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006205 return NULL;
6206}
6207
Alexander Belopolsky40018472011-02-26 01:02:56 +00006208PyObject *
6209PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006210 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006211{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006212 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006213 char *p;
6214 char *q;
6215
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006216#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006217 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006218#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006219 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006220#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006221
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006222 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006224
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006225 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006226 if (repr == NULL)
6227 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006228 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006229 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006230
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006231 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006232 while (size-- > 0) {
6233 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006234#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006235 /* Map 32-bit characters to '\Uxxxxxxxx' */
6236 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006237 *p++ = '\\';
6238 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006239 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6240 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6241 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6242 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6243 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6244 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6245 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6246 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006247 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006248 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006249#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006250 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6251 if (ch >= 0xD800 && ch < 0xDC00) {
6252 Py_UNICODE ch2;
6253 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006254
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 ch2 = *s++;
6256 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006257 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006258 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6259 *p++ = '\\';
6260 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006261 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6262 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6263 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6264 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6265 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6266 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6267 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6268 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006269 continue;
6270 }
6271 /* Fall through: isolated surrogates are copied as-is */
6272 s--;
6273 size++;
6274 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006275#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006276 /* Map 16-bit characters to '\uxxxx' */
6277 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006278 *p++ = '\\';
6279 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006280 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6281 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6282 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6283 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006284 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006285 /* Copy everything else as-is */
6286 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006287 *p++ = (char) ch;
6288 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006289 size = p - q;
6290
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006291 assert(size > 0);
6292 if (_PyBytes_Resize(&repr, size) < 0)
6293 return NULL;
6294 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006295}
6296
Alexander Belopolsky40018472011-02-26 01:02:56 +00006297PyObject *
6298PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006300 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006302 PyErr_BadArgument();
6303 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006304 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006305 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6306 PyUnicode_GET_SIZE(unicode));
6307
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006308 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309}
6310
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006311/* --- Unicode Internal Codec ------------------------------------------- */
6312
Alexander Belopolsky40018472011-02-26 01:02:56 +00006313PyObject *
6314_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006315 Py_ssize_t size,
6316 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006317{
6318 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006319 Py_ssize_t startinpos;
6320 Py_ssize_t endinpos;
6321 Py_ssize_t outpos;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006322 PyUnicodeObject *v;
6323 Py_UNICODE *p;
6324 const char *end;
6325 const char *reason;
6326 PyObject *errorHandler = NULL;
6327 PyObject *exc = NULL;
6328
Neal Norwitzd43069c2006-01-08 01:12:10 +00006329#ifdef Py_UNICODE_WIDE
6330 Py_UNICODE unimax = PyUnicode_GetMax();
6331#endif
6332
Thomas Wouters89f507f2006-12-13 04:49:30 +00006333 /* XXX overflow detection missing */
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006334 v = _PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE);
6335 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006336 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006337 /* Intentionally PyUnicode_GET_SIZE instead of PyUnicode_GET_LENGTH
6338 as string was created with the old API. */
6339 if (PyUnicode_GET_SIZE(v) == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 return (PyObject *)v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006341 p = PyUnicode_AS_UNICODE(v);
6342 end = s + size;
6343
6344 while (s < end) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00006345 memcpy(p, s, sizeof(Py_UNICODE));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006346 /* We have to sanity check the raw data, otherwise doom looms for
6347 some malformed UCS-4 data. */
6348 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006349#ifdef Py_UNICODE_WIDE
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006350 *p > unimax || *p < 0 ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006351#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006352 end-s < Py_UNICODE_SIZE
6353 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006354 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006355 startinpos = s - starts;
6356 if (end-s < Py_UNICODE_SIZE) {
6357 endinpos = end-starts;
6358 reason = "truncated input";
6359 }
6360 else {
6361 endinpos = s - starts + Py_UNICODE_SIZE;
6362 reason = "illegal code point (> 0x10FFFF)";
6363 }
6364 outpos = p - PyUnicode_AS_UNICODE(v);
6365 if (unicode_decode_call_errorhandler(
6366 errors, &errorHandler,
6367 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006368 &starts, &end, &startinpos, &endinpos, &exc, &s,
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00006369 &v, &outpos, &p)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006370 goto onError;
6371 }
6372 }
6373 else {
6374 p++;
6375 s += Py_UNICODE_SIZE;
6376 }
6377 }
6378
Victor Stinnerfe226c02011-10-03 03:52:20 +02006379 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006380 goto onError;
6381 Py_XDECREF(errorHandler);
6382 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006383#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006384 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006385 Py_DECREF(v);
6386 return NULL;
6387 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006388#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006389 assert(_PyUnicode_CheckConsistency(v, 1));
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006390 return (PyObject *)v;
6391
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006393 Py_XDECREF(v);
6394 Py_XDECREF(errorHandler);
6395 Py_XDECREF(exc);
6396 return NULL;
6397}
6398
Guido van Rossumd57fd912000-03-10 22:53:23 +00006399/* --- Latin-1 Codec ------------------------------------------------------ */
6400
Alexander Belopolsky40018472011-02-26 01:02:56 +00006401PyObject *
6402PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006403 Py_ssize_t size,
6404 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006405{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006406 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006407 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006408}
6409
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006410/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006411static void
6412make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006413 const char *encoding,
6414 const Py_UNICODE *unicode, Py_ssize_t size,
6415 Py_ssize_t startpos, Py_ssize_t endpos,
6416 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006417{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 if (*exceptionObject == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006419 *exceptionObject = PyUnicodeEncodeError_Create(
6420 encoding, unicode, size, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006421 }
6422 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006423 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6424 goto onError;
6425 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6426 goto onError;
6427 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6428 goto onError;
6429 return;
6430 onError:
6431 Py_DECREF(*exceptionObject);
6432 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006433 }
6434}
6435
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006436/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006437static void
6438raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006439 const char *encoding,
6440 const Py_UNICODE *unicode, Py_ssize_t size,
6441 Py_ssize_t startpos, Py_ssize_t endpos,
6442 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006443{
6444 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006445 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006446 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006447 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006448}
6449
6450/* error handling callback helper:
6451 build arguments, call the callback and check the arguments,
6452 put the result into newpos and return the replacement string, which
6453 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006454static PyObject *
6455unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006456 PyObject **errorHandler,
6457 const char *encoding, const char *reason,
6458 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
6459 Py_ssize_t startpos, Py_ssize_t endpos,
6460 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006461{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006462 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006463
6464 PyObject *restuple;
6465 PyObject *resunicode;
6466
6467 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006469 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006471 }
6472
6473 make_encode_exception(exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00006474 encoding, unicode, size, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006475 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006476 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006477
6478 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006480 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006481 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006482 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006483 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006484 Py_DECREF(restuple);
6485 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006486 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006487 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 &resunicode, newpos)) {
6489 Py_DECREF(restuple);
6490 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006491 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006492 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6493 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6494 Py_DECREF(restuple);
6495 return NULL;
6496 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006497 if (*newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006498 *newpos = size+*newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006499 if (*newpos<0 || *newpos>size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6501 Py_DECREF(restuple);
6502 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006503 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006504 Py_INCREF(resunicode);
6505 Py_DECREF(restuple);
6506 return resunicode;
6507}
6508
Alexander Belopolsky40018472011-02-26 01:02:56 +00006509static PyObject *
6510unicode_encode_ucs1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006511 Py_ssize_t size,
6512 const char *errors,
6513 int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006514{
6515 /* output object */
6516 PyObject *res;
6517 /* pointers to the beginning and end+1 of input */
6518 const Py_UNICODE *startp = p;
6519 const Py_UNICODE *endp = p + size;
6520 /* pointer to the beginning of the unencodable characters */
6521 /* const Py_UNICODE *badp = NULL; */
6522 /* pointer into the output */
6523 char *str;
6524 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006525 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006526 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6527 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006528 PyObject *errorHandler = NULL;
6529 PyObject *exc = NULL;
6530 /* the following variable is used for caching string comparisons
6531 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6532 int known_errorHandler = -1;
6533
6534 /* allocate enough for a simple encoding without
6535 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006536 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006537 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006538 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006539 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006540 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006541 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006542 ressize = size;
6543
6544 while (p<endp) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006545 Py_UNICODE c = *p;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006546
Benjamin Peterson29060642009-01-31 22:14:21 +00006547 /* can we encode this? */
6548 if (c<limit) {
6549 /* no overflow check, because we know that the space is enough */
6550 *str++ = (char)c;
6551 ++p;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006552 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006553 else {
6554 Py_ssize_t unicodepos = p-startp;
6555 Py_ssize_t requiredsize;
6556 PyObject *repunicode;
6557 Py_ssize_t repsize;
6558 Py_ssize_t newpos;
6559 Py_ssize_t respos;
6560 Py_UNICODE *uni2;
6561 /* startpos for collecting unencodable chars */
6562 const Py_UNICODE *collstart = p;
6563 const Py_UNICODE *collend = p;
6564 /* find all unecodable characters */
6565 while ((collend < endp) && ((*collend)>=limit))
6566 ++collend;
6567 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6568 if (known_errorHandler==-1) {
6569 if ((errors==NULL) || (!strcmp(errors, "strict")))
6570 known_errorHandler = 1;
6571 else if (!strcmp(errors, "replace"))
6572 known_errorHandler = 2;
6573 else if (!strcmp(errors, "ignore"))
6574 known_errorHandler = 3;
6575 else if (!strcmp(errors, "xmlcharrefreplace"))
6576 known_errorHandler = 4;
6577 else
6578 known_errorHandler = 0;
6579 }
6580 switch (known_errorHandler) {
6581 case 1: /* strict */
6582 raise_encode_exception(&exc, encoding, startp, size, collstart-startp, collend-startp, reason);
6583 goto onError;
6584 case 2: /* replace */
6585 while (collstart++<collend)
6586 *str++ = '?'; /* fall through */
6587 case 3: /* ignore */
6588 p = collend;
6589 break;
6590 case 4: /* xmlcharrefreplace */
6591 respos = str - PyBytes_AS_STRING(res);
6592 /* determine replacement size (temporarily (mis)uses p) */
6593 for (p = collstart, repsize = 0; p < collend; ++p) {
6594 if (*p<10)
6595 repsize += 2+1+1;
6596 else if (*p<100)
6597 repsize += 2+2+1;
6598 else if (*p<1000)
6599 repsize += 2+3+1;
6600 else if (*p<10000)
6601 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006602#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006603 else
6604 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006605#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006606 else if (*p<100000)
6607 repsize += 2+5+1;
6608 else if (*p<1000000)
6609 repsize += 2+6+1;
6610 else
6611 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006612#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006613 }
6614 requiredsize = respos+repsize+(endp-collend);
6615 if (requiredsize > ressize) {
6616 if (requiredsize<2*ressize)
6617 requiredsize = 2*ressize;
6618 if (_PyBytes_Resize(&res, requiredsize))
6619 goto onError;
6620 str = PyBytes_AS_STRING(res) + respos;
6621 ressize = requiredsize;
6622 }
6623 /* generate replacement (temporarily (mis)uses p) */
6624 for (p = collstart; p < collend; ++p) {
6625 str += sprintf(str, "&#%d;", (int)*p);
6626 }
6627 p = collend;
6628 break;
6629 default:
6630 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
6631 encoding, reason, startp, size, &exc,
6632 collstart-startp, collend-startp, &newpos);
6633 if (repunicode == NULL)
6634 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006635 if (PyBytes_Check(repunicode)) {
6636 /* Directly copy bytes result to output. */
6637 repsize = PyBytes_Size(repunicode);
6638 if (repsize > 1) {
6639 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006640 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006641 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6642 Py_DECREF(repunicode);
6643 goto onError;
6644 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006645 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006646 ressize += repsize-1;
6647 }
6648 memcpy(str, PyBytes_AsString(repunicode), repsize);
6649 str += repsize;
6650 p = startp + newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006651 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006652 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006653 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006654 /* need more space? (at least enough for what we
6655 have+the replacement+the rest of the string, so
6656 we won't have to check space for encodable characters) */
6657 respos = str - PyBytes_AS_STRING(res);
6658 repsize = PyUnicode_GET_SIZE(repunicode);
6659 requiredsize = respos+repsize+(endp-collend);
6660 if (requiredsize > ressize) {
6661 if (requiredsize<2*ressize)
6662 requiredsize = 2*ressize;
6663 if (_PyBytes_Resize(&res, requiredsize)) {
6664 Py_DECREF(repunicode);
6665 goto onError;
6666 }
6667 str = PyBytes_AS_STRING(res) + respos;
6668 ressize = requiredsize;
6669 }
6670 /* check if there is anything unencodable in the replacement
6671 and copy it to the output */
6672 for (uni2 = PyUnicode_AS_UNICODE(repunicode);repsize-->0; ++uni2, ++str) {
6673 c = *uni2;
6674 if (c >= limit) {
6675 raise_encode_exception(&exc, encoding, startp, size,
6676 unicodepos, unicodepos+1, reason);
6677 Py_DECREF(repunicode);
6678 goto onError;
6679 }
6680 *str = (char)c;
6681 }
6682 p = startp + newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006683 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006684 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006685 }
6686 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006687 /* Resize if we allocated to much */
6688 size = str - PyBytes_AS_STRING(res);
6689 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006690 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006691 if (_PyBytes_Resize(&res, size) < 0)
6692 goto onError;
6693 }
6694
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006695 Py_XDECREF(errorHandler);
6696 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006697 return res;
6698
6699 onError:
6700 Py_XDECREF(res);
6701 Py_XDECREF(errorHandler);
6702 Py_XDECREF(exc);
6703 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006704}
6705
Alexander Belopolsky40018472011-02-26 01:02:56 +00006706PyObject *
6707PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006708 Py_ssize_t size,
6709 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006710{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 return unicode_encode_ucs1(p, size, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006712}
6713
Alexander Belopolsky40018472011-02-26 01:02:56 +00006714PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006715_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006716{
6717 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 PyErr_BadArgument();
6719 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006720 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006721 if (PyUnicode_READY(unicode) == -1)
6722 return NULL;
6723 /* Fast path: if it is a one-byte string, construct
6724 bytes object directly. */
6725 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6726 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6727 PyUnicode_GET_LENGTH(unicode));
6728 /* Non-Latin-1 characters present. Defer to above function to
6729 raise the exception. */
Guido van Rossumd57fd912000-03-10 22:53:23 +00006730 return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006732 errors);
6733}
6734
6735PyObject*
6736PyUnicode_AsLatin1String(PyObject *unicode)
6737{
6738 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006739}
6740
6741/* --- 7-bit ASCII Codec -------------------------------------------------- */
6742
Alexander Belopolsky40018472011-02-26 01:02:56 +00006743PyObject *
6744PyUnicode_DecodeASCII(const char *s,
6745 Py_ssize_t size,
6746 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006747{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006748 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 PyUnicodeObject *v;
Victor Stinner702c7342011-10-05 13:50:52 +02006750 Py_UNICODE *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006751 Py_ssize_t startinpos;
6752 Py_ssize_t endinpos;
6753 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006754 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006755 int has_error;
6756 const unsigned char *p = (const unsigned char *)s;
6757 const unsigned char *end = p + size;
6758 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006759 PyObject *errorHandler = NULL;
6760 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006761
Guido van Rossumd57fd912000-03-10 22:53:23 +00006762 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006763 if (size == 1 && (unsigned char)s[0] < 128)
6764 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006765
Victor Stinner702c7342011-10-05 13:50:52 +02006766 has_error = 0;
6767 while (p < end && !has_error) {
6768 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6769 an explanation. */
6770 if (!((size_t) p & LONG_PTR_MASK)) {
6771 /* Help register allocation */
6772 register const unsigned char *_p = p;
6773 while (_p < aligned_end) {
6774 unsigned long value = *(unsigned long *) _p;
6775 if (value & ASCII_CHAR_MASK) {
6776 has_error = 1;
6777 break;
6778 }
6779 _p += SIZEOF_LONG;
6780 }
6781 if (_p == end)
6782 break;
6783 if (has_error)
6784 break;
6785 p = _p;
6786 }
6787 if (*p & 0x80) {
6788 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006789 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006790 }
6791 else {
6792 ++p;
6793 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006794 }
Victor Stinner702c7342011-10-05 13:50:52 +02006795 if (!has_error)
6796 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006797
Guido van Rossumd57fd912000-03-10 22:53:23 +00006798 v = _PyUnicode_New(size);
6799 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006800 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006801 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006802 return (PyObject *)v;
Victor Stinner702c7342011-10-05 13:50:52 +02006803 u = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006804 e = s + size;
6805 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006806 register unsigned char c = (unsigned char)*s;
6807 if (c < 128) {
Victor Stinner702c7342011-10-05 13:50:52 +02006808 *u++ = c;
Benjamin Peterson29060642009-01-31 22:14:21 +00006809 ++s;
6810 }
6811 else {
6812 startinpos = s-starts;
6813 endinpos = startinpos + 1;
Victor Stinner702c7342011-10-05 13:50:52 +02006814 outpos = u - (Py_UNICODE *)PyUnicode_AS_UNICODE(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006815 if (unicode_decode_call_errorhandler(
6816 errors, &errorHandler,
6817 "ascii", "ordinal not in range(128)",
6818 &starts, &e, &startinpos, &endinpos, &exc, &s,
Victor Stinner702c7342011-10-05 13:50:52 +02006819 &v, &outpos, &u))
Benjamin Peterson29060642009-01-31 22:14:21 +00006820 goto onError;
6821 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006822 }
Victor Stinner702c7342011-10-05 13:50:52 +02006823 if (u - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
6824 if (PyUnicode_Resize((PyObject**)&v, u - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006825 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006826 Py_XDECREF(errorHandler);
6827 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02006828#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02006829 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006830 Py_DECREF(v);
6831 return NULL;
6832 }
Victor Stinner17efeed2011-10-04 20:05:46 +02006833#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006834 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006835 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00006836
Benjamin Peterson29060642009-01-31 22:14:21 +00006837 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006838 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006839 Py_XDECREF(errorHandler);
6840 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006841 return NULL;
6842}
6843
Alexander Belopolsky40018472011-02-26 01:02:56 +00006844PyObject *
6845PyUnicode_EncodeASCII(const Py_UNICODE *p,
6846 Py_ssize_t size,
6847 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006848{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006849 return unicode_encode_ucs1(p, size, errors, 128);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006850}
6851
Alexander Belopolsky40018472011-02-26 01:02:56 +00006852PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006853_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006854{
6855 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006856 PyErr_BadArgument();
6857 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006858 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006859 if (PyUnicode_READY(unicode) == -1)
6860 return NULL;
6861 /* Fast path: if it is an ASCII-only string, construct bytes object
6862 directly. Else defer to above function to raise the exception. */
6863 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6864 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6865 PyUnicode_GET_LENGTH(unicode));
Guido van Rossumd57fd912000-03-10 22:53:23 +00006866 return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00006867 PyUnicode_GET_SIZE(unicode),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006868 errors);
6869}
6870
6871PyObject *
6872PyUnicode_AsASCIIString(PyObject *unicode)
6873{
6874 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006875}
6876
Victor Stinner99b95382011-07-04 14:23:54 +02006877#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006878
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006879/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006880
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006881#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006882#define NEED_RETRY
6883#endif
6884
Victor Stinner3a50e702011-10-18 21:21:00 +02006885#ifndef WC_ERR_INVALID_CHARS
6886# define WC_ERR_INVALID_CHARS 0x0080
6887#endif
6888
6889static char*
6890code_page_name(UINT code_page, PyObject **obj)
6891{
6892 *obj = NULL;
6893 if (code_page == CP_ACP)
6894 return "mbcs";
6895 if (code_page == CP_UTF7)
6896 return "CP_UTF7";
6897 if (code_page == CP_UTF8)
6898 return "CP_UTF8";
6899
6900 *obj = PyBytes_FromFormat("cp%u", code_page);
6901 if (*obj == NULL)
6902 return NULL;
6903 return PyBytes_AS_STRING(*obj);
6904}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006905
Alexander Belopolsky40018472011-02-26 01:02:56 +00006906static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006907is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006908{
6909 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006910 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006911
Victor Stinner3a50e702011-10-18 21:21:00 +02006912 if (!IsDBCSLeadByteEx(code_page, *curr))
6913 return 0;
6914
6915 prev = CharPrevExA(code_page, s, curr, 0);
6916 if (prev == curr)
6917 return 1;
6918 /* FIXME: This code is limited to "true" double-byte encodings,
6919 as it assumes an incomplete character consists of a single
6920 byte. */
6921 if (curr - prev == 2)
6922 return 1;
6923 if (!IsDBCSLeadByteEx(code_page, *prev))
6924 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006925 return 0;
6926}
6927
Victor Stinner3a50e702011-10-18 21:21:00 +02006928static DWORD
6929decode_code_page_flags(UINT code_page)
6930{
6931 if (code_page == CP_UTF7) {
6932 /* The CP_UTF7 decoder only supports flags=0 */
6933 return 0;
6934 }
6935 else
6936 return MB_ERR_INVALID_CHARS;
6937}
6938
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006939/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006940 * Decode a byte string from a Windows code page into unicode object in strict
6941 * mode.
6942 *
6943 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6944 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006945 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006946static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006947decode_code_page_strict(UINT code_page,
6948 PyUnicodeObject **v,
6949 const char *in,
6950 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006951{
Victor Stinner3a50e702011-10-18 21:21:00 +02006952 const DWORD flags = decode_code_page_flags(code_page);
6953 Py_UNICODE *out;
6954 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006955
6956 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006957 assert(insize > 0);
6958 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6959 if (outsize <= 0)
6960 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006961
6962 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006963 /* Create unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006964 *v = _PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006965 if (*v == NULL)
6966 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006967 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006968 }
6969 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006970 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006971 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6972 if (PyUnicode_Resize((PyObject**)v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006973 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006974 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006975 }
6976
6977 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006978 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6979 if (outsize <= 0)
6980 goto error;
6981 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006982
Victor Stinner3a50e702011-10-18 21:21:00 +02006983error:
6984 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6985 return -2;
6986 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006987 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006988}
6989
Victor Stinner3a50e702011-10-18 21:21:00 +02006990/*
6991 * Decode a byte string from a code page into unicode object with an error
6992 * handler.
6993 *
6994 * Returns consumed size if succeed, or raise a WindowsError or
6995 * UnicodeDecodeError exception and returns -1 on error.
6996 */
6997static int
6998decode_code_page_errors(UINT code_page,
6999 PyUnicodeObject **v,
7000 const char *in,
7001 int size,
7002 const char *errors)
7003{
7004 const char *startin = in;
7005 const char *endin = in + size;
7006 const DWORD flags = decode_code_page_flags(code_page);
7007 /* Ideally, we should get reason from FormatMessage. This is the Windows
7008 2000 English version of the message. */
7009 const char *reason = "No mapping for the Unicode character exists "
7010 "in the target code page.";
7011 /* each step cannot decode more than 1 character, but a character can be
7012 represented as a surrogate pair */
7013 wchar_t buffer[2], *startout, *out;
7014 int insize, outsize;
7015 PyObject *errorHandler = NULL;
7016 PyObject *exc = NULL;
7017 PyObject *encoding_obj = NULL;
7018 char *encoding;
7019 DWORD err;
7020 int ret = -1;
7021
7022 assert(size > 0);
7023
7024 encoding = code_page_name(code_page, &encoding_obj);
7025 if (encoding == NULL)
7026 return -1;
7027
7028 if (errors == NULL || strcmp(errors, "strict") == 0) {
7029 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
7030 UnicodeDecodeError. */
7031 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
7032 if (exc != NULL) {
7033 PyCodec_StrictErrors(exc);
7034 Py_CLEAR(exc);
7035 }
7036 goto error;
7037 }
7038
7039 if (*v == NULL) {
7040 /* Create unicode object */
7041 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7042 PyErr_NoMemory();
7043 goto error;
7044 }
7045 *v = _PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
7046 if (*v == NULL)
7047 goto error;
7048 startout = PyUnicode_AS_UNICODE(*v);
7049 }
7050 else {
7051 /* Extend unicode object */
7052 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
7053 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
7054 PyErr_NoMemory();
7055 goto error;
7056 }
7057 if (PyUnicode_Resize((PyObject**)v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
7058 goto error;
7059 startout = PyUnicode_AS_UNICODE(*v) + n;
7060 }
7061
7062 /* Decode the byte string character per character */
7063 out = startout;
7064 while (in < endin)
7065 {
7066 /* Decode a character */
7067 insize = 1;
7068 do
7069 {
7070 outsize = MultiByteToWideChar(code_page, flags,
7071 in, insize,
7072 buffer, Py_ARRAY_LENGTH(buffer));
7073 if (outsize > 0)
7074 break;
7075 err = GetLastError();
7076 if (err != ERROR_NO_UNICODE_TRANSLATION
7077 && err != ERROR_INSUFFICIENT_BUFFER)
7078 {
7079 PyErr_SetFromWindowsErr(0);
7080 goto error;
7081 }
7082 insize++;
7083 }
7084 /* 4=maximum length of a UTF-8 sequence */
7085 while (insize <= 4 && (in + insize) <= endin);
7086
7087 if (outsize <= 0) {
7088 Py_ssize_t startinpos, endinpos, outpos;
7089
7090 startinpos = in - startin;
7091 endinpos = startinpos + 1;
7092 outpos = out - PyUnicode_AS_UNICODE(*v);
7093 if (unicode_decode_call_errorhandler(
7094 errors, &errorHandler,
7095 encoding, reason,
7096 &startin, &endin, &startinpos, &endinpos, &exc, &in,
7097 v, &outpos, &out))
7098 {
7099 goto error;
7100 }
7101 }
7102 else {
7103 in += insize;
7104 memcpy(out, buffer, outsize * sizeof(wchar_t));
7105 out += outsize;
7106 }
7107 }
7108
7109 /* write a NUL character at the end */
7110 *out = 0;
7111
7112 /* Extend unicode object */
7113 outsize = out - startout;
7114 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
7115 if (PyUnicode_Resize((PyObject**)v, outsize) < 0)
7116 goto error;
7117 ret = 0;
7118
7119error:
7120 Py_XDECREF(encoding_obj);
7121 Py_XDECREF(errorHandler);
7122 Py_XDECREF(exc);
7123 return ret;
7124}
7125
7126/*
7127 * Decode a byte string from a Windows code page into unicode object. If
7128 * 'final' is set, converts trailing lead-byte too.
7129 *
7130 * Returns consumed size if succeed, or raise a WindowsError or
7131 * UnicodeDecodeError exception and returns -1 on error.
7132 */
7133static int
7134decode_code_page(UINT code_page,
7135 PyUnicodeObject **v,
7136 const char *s, int size,
7137 int final, const char *errors)
7138{
7139 int done;
7140
7141 /* Skip trailing lead-byte unless 'final' is set */
7142 if (size == 0) {
7143 if (*v == NULL) {
7144 Py_INCREF(unicode_empty);
7145 *v = (PyUnicodeObject*)unicode_empty;
7146 if (*v == NULL)
7147 return -1;
7148 }
7149 return 0;
7150 }
7151
7152 if (!final && is_dbcs_lead_byte(code_page, s, size - 1))
7153 --size;
7154
7155 done = decode_code_page_strict(code_page, v, s, size);
7156 if (done == -2)
7157 done = decode_code_page_errors(code_page, v, s, size, errors);
7158 return done;
7159}
7160
7161static PyObject *
7162decode_code_page_stateful(int code_page,
7163 const char *s,
7164 Py_ssize_t size,
7165 const char *errors,
7166 Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007167{
7168 PyUnicodeObject *v = NULL;
7169 int done;
7170
Victor Stinner3a50e702011-10-18 21:21:00 +02007171 if (code_page < 0) {
7172 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7173 return NULL;
7174 }
7175
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007176 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007177 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007178
7179#ifdef NEED_RETRY
7180 retry:
7181 if (size > INT_MAX)
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 done = decode_code_page(code_page, &v, s, INT_MAX, 0, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007183 else
7184#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 done = decode_code_page(code_page, &v, s, (int)size, !consumed, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007186
7187 if (done < 0) {
7188 Py_XDECREF(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00007189 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190 }
7191
7192 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007193 *consumed += done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007194
7195#ifdef NEED_RETRY
7196 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007197 s += done;
7198 size -= done;
7199 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007200 }
7201#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007202
Victor Stinner17efeed2011-10-04 20:05:46 +02007203#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007204 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007205 Py_DECREF(v);
7206 return NULL;
7207 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007208#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007209 assert(_PyUnicode_CheckConsistency(v, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007210 return (PyObject *)v;
7211}
7212
Alexander Belopolsky40018472011-02-26 01:02:56 +00007213PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007214PyUnicode_DecodeCodePageStateful(int code_page,
7215 const char *s,
7216 Py_ssize_t size,
7217 const char *errors,
7218 Py_ssize_t *consumed)
7219{
7220 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7221}
7222
7223PyObject *
7224PyUnicode_DecodeMBCSStateful(const char *s,
7225 Py_ssize_t size,
7226 const char *errors,
7227 Py_ssize_t *consumed)
7228{
7229 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7230}
7231
7232PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007233PyUnicode_DecodeMBCS(const char *s,
7234 Py_ssize_t size,
7235 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007236{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007237 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7238}
7239
Victor Stinner3a50e702011-10-18 21:21:00 +02007240static DWORD
7241encode_code_page_flags(UINT code_page, const char *errors)
7242{
7243 if (code_page == CP_UTF8) {
7244 if (winver.dwMajorVersion >= 6)
7245 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7246 and later */
7247 return WC_ERR_INVALID_CHARS;
7248 else
7249 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7250 return 0;
7251 }
7252 else if (code_page == CP_UTF7) {
7253 /* CP_UTF7 only supports flags=0 */
7254 return 0;
7255 }
7256 else {
7257 if (errors != NULL && strcmp(errors, "replace") == 0)
7258 return 0;
7259 else
7260 return WC_NO_BEST_FIT_CHARS;
7261 }
7262}
7263
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007264/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007265 * Encode a Unicode string to a Windows code page into a byte string in strict
7266 * mode.
7267 *
7268 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7269 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007270 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007271static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007272encode_code_page_strict(UINT code_page, PyObject **outbytes,
7273 const Py_UNICODE *p, const int size,
7274 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007275{
Victor Stinner554f3f02010-06-16 23:33:54 +00007276 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007277 BOOL *pusedDefaultChar = &usedDefaultChar;
7278 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007279 PyObject *exc = NULL;
Victor Stinner3a50e702011-10-18 21:21:00 +02007280 const DWORD flags = encode_code_page_flags(code_page, NULL);
7281 char *out;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007282
Victor Stinner3a50e702011-10-18 21:21:00 +02007283 assert(size > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007284
Victor Stinner3a50e702011-10-18 21:21:00 +02007285 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007286 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007287 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007288 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007289
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007290 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007291 outsize = WideCharToMultiByte(code_page, flags,
7292 p, size,
7293 NULL, 0,
7294 NULL, pusedDefaultChar);
7295 if (outsize <= 0)
7296 goto error;
7297 /* If we used a default char, then we failed! */
7298 if (pusedDefaultChar && *pusedDefaultChar)
7299 return -2;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007300
Victor Stinner3a50e702011-10-18 21:21:00 +02007301 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007302 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007303 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7304 if (*outbytes == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007305 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007306 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007307 }
7308 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007309 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007310 const Py_ssize_t n = PyBytes_Size(*outbytes);
7311 if (outsize > PY_SSIZE_T_MAX - n) {
7312 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00007313 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007314 }
7315 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7316 return -1;
7317 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007318 }
7319
7320 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007321 outsize = WideCharToMultiByte(code_page, flags,
7322 p, size,
7323 out, outsize,
7324 NULL, pusedDefaultChar);
7325 if (outsize <= 0)
7326 goto error;
7327 if (pusedDefaultChar && *pusedDefaultChar)
7328 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007329 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007330
Victor Stinner3a50e702011-10-18 21:21:00 +02007331error:
7332 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7333 return -2;
7334 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007335 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007336}
7337
Victor Stinner3a50e702011-10-18 21:21:00 +02007338/*
7339 * Encode a Unicode string to a Windows code page into a byte string using a
7340 * error handler.
7341 *
7342 * Returns consumed characters if succeed, or raise a WindowsError and returns
7343 * -1 on other error.
7344 */
7345static int
7346encode_code_page_errors(UINT code_page, PyObject **outbytes,
7347 const Py_UNICODE *in, const int insize,
7348 const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007349{
Victor Stinner3a50e702011-10-18 21:21:00 +02007350 const DWORD flags = encode_code_page_flags(code_page, errors);
7351 const Py_UNICODE *startin = in;
7352 const Py_UNICODE *endin = in + insize;
7353 /* Ideally, we should get reason from FormatMessage. This is the Windows
7354 2000 English version of the message. */
7355 const char *reason = "invalid character";
7356 /* 4=maximum length of a UTF-8 sequence */
7357 char buffer[4];
7358 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7359 Py_ssize_t outsize;
7360 char *out;
7361 int charsize;
7362 PyObject *errorHandler = NULL;
7363 PyObject *exc = NULL;
7364 PyObject *encoding_obj = NULL;
7365 char *encoding;
Victor Stinner3a50e702011-10-18 21:21:00 +02007366 Py_ssize_t startpos, newpos, newoutsize;
7367 PyObject *rep;
7368 int ret = -1;
7369
7370 assert(insize > 0);
7371
7372 encoding = code_page_name(code_page, &encoding_obj);
7373 if (encoding == NULL)
7374 return -1;
7375
7376 if (errors == NULL || strcmp(errors, "strict") == 0) {
7377 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7378 then we raise a UnicodeEncodeError. */
7379 make_encode_exception(&exc, encoding, in, insize, 0, 0, reason);
7380 if (exc != NULL) {
7381 PyCodec_StrictErrors(exc);
7382 Py_DECREF(exc);
7383 }
7384 Py_XDECREF(encoding_obj);
7385 return -1;
7386 }
7387
7388 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7389 pusedDefaultChar = &usedDefaultChar;
7390 else
7391 pusedDefaultChar = NULL;
7392
7393 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7394 PyErr_NoMemory();
7395 goto error;
7396 }
7397 outsize = insize * Py_ARRAY_LENGTH(buffer);
7398
7399 if (*outbytes == NULL) {
7400 /* Create string object */
7401 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7402 if (*outbytes == NULL)
7403 goto error;
7404 out = PyBytes_AS_STRING(*outbytes);
7405 }
7406 else {
7407 /* Extend string object */
7408 Py_ssize_t n = PyBytes_Size(*outbytes);
7409 if (n > PY_SSIZE_T_MAX - outsize) {
7410 PyErr_NoMemory();
7411 goto error;
7412 }
7413 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7414 goto error;
7415 out = PyBytes_AS_STRING(*outbytes) + n;
7416 }
7417
7418 /* Encode the string character per character */
7419 while (in < endin)
7420 {
7421 if ((in + 2) <= endin
7422 && 0xD800 <= in[0] && in[0] <= 0xDBFF
7423 && 0xDC00 <= in[1] && in[1] <= 0xDFFF)
7424 charsize = 2;
7425 else
7426 charsize = 1;
7427
7428 outsize = WideCharToMultiByte(code_page, flags,
7429 in, charsize,
7430 buffer, Py_ARRAY_LENGTH(buffer),
7431 NULL, pusedDefaultChar);
7432 if (outsize > 0) {
7433 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7434 {
7435 in += charsize;
7436 memcpy(out, buffer, outsize);
7437 out += outsize;
7438 continue;
7439 }
7440 }
7441 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7442 PyErr_SetFromWindowsErr(0);
7443 goto error;
7444 }
7445
7446 charsize = Py_MAX(charsize - 1, 1);
7447 startpos = in - startin;
7448 rep = unicode_encode_call_errorhandler(
7449 errors, &errorHandler, encoding, reason,
7450 startin, insize, &exc,
7451 startpos, startpos + charsize, &newpos);
7452 if (rep == NULL)
7453 goto error;
7454 in = startin + newpos;
7455
7456 if (PyBytes_Check(rep)) {
7457 outsize = PyBytes_GET_SIZE(rep);
7458 if (outsize != 1) {
7459 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7460 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7461 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7462 Py_DECREF(rep);
7463 goto error;
7464 }
7465 out = PyBytes_AS_STRING(*outbytes) + offset;
7466 }
7467 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7468 out += outsize;
7469 }
7470 else {
7471 Py_ssize_t i;
7472 enum PyUnicode_Kind kind;
7473 void *data;
7474
7475 if (PyUnicode_READY(rep) < 0) {
7476 Py_DECREF(rep);
7477 goto error;
7478 }
7479
7480 outsize = PyUnicode_GET_LENGTH(rep);
7481 if (outsize != 1) {
7482 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7483 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7484 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7485 Py_DECREF(rep);
7486 goto error;
7487 }
7488 out = PyBytes_AS_STRING(*outbytes) + offset;
7489 }
7490 kind = PyUnicode_KIND(rep);
7491 data = PyUnicode_DATA(rep);
7492 for (i=0; i < outsize; i++) {
7493 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7494 if (ch > 127) {
7495 raise_encode_exception(&exc,
7496 encoding,
7497 startin, insize,
7498 startpos, startpos + charsize,
7499 "unable to encode error handler result to ASCII");
7500 Py_DECREF(rep);
7501 goto error;
7502 }
7503 *out = (unsigned char)ch;
7504 out++;
7505 }
7506 }
7507 Py_DECREF(rep);
7508 }
7509 /* write a NUL byte */
7510 *out = 0;
7511 outsize = out - PyBytes_AS_STRING(*outbytes);
7512 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7513 if (_PyBytes_Resize(outbytes, outsize) < 0)
7514 goto error;
7515 ret = 0;
7516
7517error:
7518 Py_XDECREF(encoding_obj);
7519 Py_XDECREF(errorHandler);
7520 Py_XDECREF(exc);
7521 return ret;
7522}
7523
7524/*
7525 * Encode a Unicode string to a Windows code page into a byte string.
7526 *
7527 * Returns consumed characters if succeed, or raise a WindowsError and returns
7528 * -1 on other error.
7529 */
7530static int
7531encode_code_page_chunk(UINT code_page, PyObject **outbytes,
7532 const Py_UNICODE *p, int size,
7533 const char* errors)
7534{
7535 int done;
7536
7537 if (size == 0) {
7538 if (*outbytes == NULL) {
7539 *outbytes = PyBytes_FromStringAndSize(NULL, 0);
7540 if (*outbytes == NULL)
7541 return -1;
7542 }
7543 return 0;
7544 }
7545
7546 done = encode_code_page_strict(code_page, outbytes, p, size, errors);
7547 if (done == -2)
7548 done = encode_code_page_errors(code_page, outbytes, p, size, errors);
7549 return done;
7550}
7551
7552static PyObject *
7553encode_code_page(int code_page,
7554 const Py_UNICODE *p, Py_ssize_t size,
7555 const char *errors)
7556{
7557 PyObject *outbytes = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007558 int ret;
Guido van Rossum03e29f12000-05-04 15:52:20 +00007559
Victor Stinner3a50e702011-10-18 21:21:00 +02007560 if (code_page < 0) {
7561 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7562 return NULL;
7563 }
7564
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007565#ifdef NEED_RETRY
Benjamin Peterson29060642009-01-31 22:14:21 +00007566 retry:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007567 if (size > INT_MAX)
Victor Stinner3a50e702011-10-18 21:21:00 +02007568 ret = encode_code_page_chunk(code_page, &outbytes, p, INT_MAX, errors);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007569 else
7570#endif
Victor Stinner3a50e702011-10-18 21:21:00 +02007571 ret = encode_code_page_chunk(code_page, &outbytes, p, (int)size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007572
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007573 if (ret < 0) {
Victor Stinner3a50e702011-10-18 21:21:00 +02007574 Py_XDECREF(outbytes);
Benjamin Peterson29060642009-01-31 22:14:21 +00007575 return NULL;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007576 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007577
7578#ifdef NEED_RETRY
7579 if (size > INT_MAX) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 p += INT_MAX;
7581 size -= INT_MAX;
7582 goto retry;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007583 }
7584#endif
7585
Victor Stinner3a50e702011-10-18 21:21:00 +02007586 return outbytes;
7587}
7588
7589PyObject *
7590PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7591 Py_ssize_t size,
7592 const char *errors)
7593{
7594 return encode_code_page(CP_ACP, p, size, errors);
7595}
7596
7597PyObject *
7598PyUnicode_EncodeCodePage(int code_page,
7599 PyObject *unicode,
7600 const char *errors)
7601{
7602 const Py_UNICODE *p;
7603 Py_ssize_t size;
7604 p = PyUnicode_AsUnicodeAndSize(unicode, &size);
7605 if (p == NULL)
7606 return NULL;
7607 return encode_code_page(code_page, p, size, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007608}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007609
Alexander Belopolsky40018472011-02-26 01:02:56 +00007610PyObject *
7611PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007612{
7613 if (!PyUnicode_Check(unicode)) {
7614 PyErr_BadArgument();
7615 return NULL;
7616 }
7617 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00007618 PyUnicode_GET_SIZE(unicode),
7619 NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007620}
7621
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007622#undef NEED_RETRY
7623
Victor Stinner99b95382011-07-04 14:23:54 +02007624#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007625
Guido van Rossumd57fd912000-03-10 22:53:23 +00007626/* --- Character Mapping Codec -------------------------------------------- */
7627
Alexander Belopolsky40018472011-02-26 01:02:56 +00007628PyObject *
7629PyUnicode_DecodeCharmap(const char *s,
7630 Py_ssize_t size,
7631 PyObject *mapping,
7632 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007633{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007634 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007635 Py_ssize_t startinpos;
7636 Py_ssize_t endinpos;
7637 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007638 const char *e;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007639 PyUnicodeObject *v;
7640 Py_UNICODE *p;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007641 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007642 PyObject *errorHandler = NULL;
7643 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007644 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007645 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007646
Guido van Rossumd57fd912000-03-10 22:53:23 +00007647 /* Default to Latin-1 */
7648 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007649 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007650
7651 v = _PyUnicode_New(size);
7652 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007653 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007654 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 return (PyObject *)v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007656 p = PyUnicode_AS_UNICODE(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007657 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007658 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 mapstring = PyUnicode_AS_UNICODE(mapping);
7660 maplen = PyUnicode_GET_SIZE(mapping);
7661 while (s < e) {
7662 unsigned char ch = *s;
7663 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007664
Benjamin Peterson29060642009-01-31 22:14:21 +00007665 if (ch < maplen)
7666 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007667
Benjamin Peterson29060642009-01-31 22:14:21 +00007668 if (x == 0xfffe) {
7669 /* undefined mapping */
7670 outpos = p-PyUnicode_AS_UNICODE(v);
7671 startinpos = s-starts;
7672 endinpos = startinpos+1;
7673 if (unicode_decode_call_errorhandler(
7674 errors, &errorHandler,
7675 "charmap", "character maps to <undefined>",
7676 &starts, &e, &startinpos, &endinpos, &exc, &s,
7677 &v, &outpos, &p)) {
7678 goto onError;
7679 }
7680 continue;
7681 }
7682 *p++ = x;
7683 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007684 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007685 }
7686 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 while (s < e) {
7688 unsigned char ch = *s;
7689 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007690
Benjamin Peterson29060642009-01-31 22:14:21 +00007691 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7692 w = PyLong_FromLong((long)ch);
7693 if (w == NULL)
7694 goto onError;
7695 x = PyObject_GetItem(mapping, w);
7696 Py_DECREF(w);
7697 if (x == NULL) {
7698 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7699 /* No mapping found means: mapping is undefined. */
7700 PyErr_Clear();
7701 x = Py_None;
7702 Py_INCREF(x);
7703 } else
7704 goto onError;
7705 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007706
Benjamin Peterson29060642009-01-31 22:14:21 +00007707 /* Apply mapping */
7708 if (PyLong_Check(x)) {
7709 long value = PyLong_AS_LONG(x);
7710 if (value < 0 || value > 65535) {
7711 PyErr_SetString(PyExc_TypeError,
7712 "character mapping must be in range(65536)");
7713 Py_DECREF(x);
7714 goto onError;
7715 }
7716 *p++ = (Py_UNICODE)value;
7717 }
7718 else if (x == Py_None) {
7719 /* undefined mapping */
7720 outpos = p-PyUnicode_AS_UNICODE(v);
7721 startinpos = s-starts;
7722 endinpos = startinpos+1;
7723 if (unicode_decode_call_errorhandler(
7724 errors, &errorHandler,
7725 "charmap", "character maps to <undefined>",
7726 &starts, &e, &startinpos, &endinpos, &exc, &s,
7727 &v, &outpos, &p)) {
7728 Py_DECREF(x);
7729 goto onError;
7730 }
7731 Py_DECREF(x);
7732 continue;
7733 }
7734 else if (PyUnicode_Check(x)) {
7735 Py_ssize_t targetsize = PyUnicode_GET_SIZE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007736
Benjamin Peterson29060642009-01-31 22:14:21 +00007737 if (targetsize == 1)
7738 /* 1-1 mapping */
7739 *p++ = *PyUnicode_AS_UNICODE(x);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007740
Benjamin Peterson29060642009-01-31 22:14:21 +00007741 else if (targetsize > 1) {
7742 /* 1-n mapping */
7743 if (targetsize > extrachars) {
7744 /* resize first */
7745 Py_ssize_t oldpos = p - PyUnicode_AS_UNICODE(v);
7746 Py_ssize_t needed = (targetsize - extrachars) + \
7747 (targetsize << 2);
7748 extrachars += needed;
7749 /* XXX overflow detection missing */
Victor Stinnerfe226c02011-10-03 03:52:20 +02007750 if (PyUnicode_Resize((PyObject**)&v,
Benjamin Peterson29060642009-01-31 22:14:21 +00007751 PyUnicode_GET_SIZE(v) + needed) < 0) {
7752 Py_DECREF(x);
7753 goto onError;
7754 }
7755 p = PyUnicode_AS_UNICODE(v) + oldpos;
7756 }
7757 Py_UNICODE_COPY(p,
7758 PyUnicode_AS_UNICODE(x),
7759 targetsize);
7760 p += targetsize;
7761 extrachars -= targetsize;
7762 }
7763 /* 1-0 mapping: skip the character */
7764 }
7765 else {
7766 /* wrong return value */
7767 PyErr_SetString(PyExc_TypeError,
7768 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007769 Py_DECREF(x);
7770 goto onError;
7771 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007772 Py_DECREF(x);
7773 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007774 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007775 }
7776 if (p - PyUnicode_AS_UNICODE(v) < PyUnicode_GET_SIZE(v))
Victor Stinnerfe226c02011-10-03 03:52:20 +02007777 if (PyUnicode_Resize((PyObject**)&v, p - PyUnicode_AS_UNICODE(v)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007778 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007779 Py_XDECREF(errorHandler);
7780 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02007781#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007782 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007783 Py_DECREF(v);
7784 return NULL;
7785 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007786#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007787 assert(_PyUnicode_CheckConsistency(v, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00007788 return (PyObject *)v;
Tim Petersced69f82003-09-16 20:30:58 +00007789
Benjamin Peterson29060642009-01-31 22:14:21 +00007790 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007791 Py_XDECREF(errorHandler);
7792 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007793 Py_XDECREF(v);
7794 return NULL;
7795}
7796
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007797/* Charmap encoding: the lookup table */
7798
Alexander Belopolsky40018472011-02-26 01:02:56 +00007799struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007800 PyObject_HEAD
7801 unsigned char level1[32];
7802 int count2, count3;
7803 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007804};
7805
7806static PyObject*
7807encoding_map_size(PyObject *obj, PyObject* args)
7808{
7809 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007810 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007811 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007812}
7813
7814static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007815 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007816 PyDoc_STR("Return the size (in bytes) of this object") },
7817 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007818};
7819
7820static void
7821encoding_map_dealloc(PyObject* o)
7822{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007823 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007824}
7825
7826static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007827 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007828 "EncodingMap", /*tp_name*/
7829 sizeof(struct encoding_map), /*tp_basicsize*/
7830 0, /*tp_itemsize*/
7831 /* methods */
7832 encoding_map_dealloc, /*tp_dealloc*/
7833 0, /*tp_print*/
7834 0, /*tp_getattr*/
7835 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007836 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007837 0, /*tp_repr*/
7838 0, /*tp_as_number*/
7839 0, /*tp_as_sequence*/
7840 0, /*tp_as_mapping*/
7841 0, /*tp_hash*/
7842 0, /*tp_call*/
7843 0, /*tp_str*/
7844 0, /*tp_getattro*/
7845 0, /*tp_setattro*/
7846 0, /*tp_as_buffer*/
7847 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7848 0, /*tp_doc*/
7849 0, /*tp_traverse*/
7850 0, /*tp_clear*/
7851 0, /*tp_richcompare*/
7852 0, /*tp_weaklistoffset*/
7853 0, /*tp_iter*/
7854 0, /*tp_iternext*/
7855 encoding_map_methods, /*tp_methods*/
7856 0, /*tp_members*/
7857 0, /*tp_getset*/
7858 0, /*tp_base*/
7859 0, /*tp_dict*/
7860 0, /*tp_descr_get*/
7861 0, /*tp_descr_set*/
7862 0, /*tp_dictoffset*/
7863 0, /*tp_init*/
7864 0, /*tp_alloc*/
7865 0, /*tp_new*/
7866 0, /*tp_free*/
7867 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007868};
7869
7870PyObject*
7871PyUnicode_BuildEncodingMap(PyObject* string)
7872{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007873 PyObject *result;
7874 struct encoding_map *mresult;
7875 int i;
7876 int need_dict = 0;
7877 unsigned char level1[32];
7878 unsigned char level2[512];
7879 unsigned char *mlevel1, *mlevel2, *mlevel3;
7880 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007881 int kind;
7882 void *data;
7883 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007884
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007885 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007886 PyErr_BadArgument();
7887 return NULL;
7888 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007889 kind = PyUnicode_KIND(string);
7890 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007891 memset(level1, 0xFF, sizeof level1);
7892 memset(level2, 0xFF, sizeof level2);
7893
7894 /* If there isn't a one-to-one mapping of NULL to \0,
7895 or if there are non-BMP characters, we need to use
7896 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007897 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007898 need_dict = 1;
7899 for (i = 1; i < 256; i++) {
7900 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007901 ch = PyUnicode_READ(kind, data, i);
7902 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007903 need_dict = 1;
7904 break;
7905 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007906 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007907 /* unmapped character */
7908 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007909 l1 = ch >> 11;
7910 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007911 if (level1[l1] == 0xFF)
7912 level1[l1] = count2++;
7913 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007914 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007915 }
7916
7917 if (count2 >= 0xFF || count3 >= 0xFF)
7918 need_dict = 1;
7919
7920 if (need_dict) {
7921 PyObject *result = PyDict_New();
7922 PyObject *key, *value;
7923 if (!result)
7924 return NULL;
7925 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007926 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007927 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007928 if (!key || !value)
7929 goto failed1;
7930 if (PyDict_SetItem(result, key, value) == -1)
7931 goto failed1;
7932 Py_DECREF(key);
7933 Py_DECREF(value);
7934 }
7935 return result;
7936 failed1:
7937 Py_XDECREF(key);
7938 Py_XDECREF(value);
7939 Py_DECREF(result);
7940 return NULL;
7941 }
7942
7943 /* Create a three-level trie */
7944 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7945 16*count2 + 128*count3 - 1);
7946 if (!result)
7947 return PyErr_NoMemory();
7948 PyObject_Init(result, &EncodingMapType);
7949 mresult = (struct encoding_map*)result;
7950 mresult->count2 = count2;
7951 mresult->count3 = count3;
7952 mlevel1 = mresult->level1;
7953 mlevel2 = mresult->level23;
7954 mlevel3 = mresult->level23 + 16*count2;
7955 memcpy(mlevel1, level1, 32);
7956 memset(mlevel2, 0xFF, 16*count2);
7957 memset(mlevel3, 0, 128*count3);
7958 count3 = 0;
7959 for (i = 1; i < 256; i++) {
7960 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007961 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007962 /* unmapped character */
7963 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007964 o1 = PyUnicode_READ(kind, data, i)>>11;
7965 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007966 i2 = 16*mlevel1[o1] + o2;
7967 if (mlevel2[i2] == 0xFF)
7968 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007969 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007970 i3 = 128*mlevel2[i2] + o3;
7971 mlevel3[i3] = i;
7972 }
7973 return result;
7974}
7975
7976static int
7977encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7978{
7979 struct encoding_map *map = (struct encoding_map*)mapping;
7980 int l1 = c>>11;
7981 int l2 = (c>>7) & 0xF;
7982 int l3 = c & 0x7F;
7983 int i;
7984
7985#ifdef Py_UNICODE_WIDE
7986 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007987 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007988 }
7989#endif
7990 if (c == 0)
7991 return 0;
7992 /* level 1*/
7993 i = map->level1[l1];
7994 if (i == 0xFF) {
7995 return -1;
7996 }
7997 /* level 2*/
7998 i = map->level23[16*i+l2];
7999 if (i == 0xFF) {
8000 return -1;
8001 }
8002 /* level 3 */
8003 i = map->level23[16*map->count2 + 128*i + l3];
8004 if (i == 0) {
8005 return -1;
8006 }
8007 return i;
8008}
8009
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008010/* Lookup the character ch in the mapping. If the character
8011 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00008012 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008013static PyObject *
8014charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008015{
Christian Heimes217cfd12007-12-02 14:31:20 +00008016 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008017 PyObject *x;
8018
8019 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008020 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008021 x = PyObject_GetItem(mapping, w);
8022 Py_DECREF(w);
8023 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008024 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8025 /* No mapping found means: mapping is undefined. */
8026 PyErr_Clear();
8027 x = Py_None;
8028 Py_INCREF(x);
8029 return x;
8030 } else
8031 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008032 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00008033 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008034 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00008035 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008036 long value = PyLong_AS_LONG(x);
8037 if (value < 0 || value > 255) {
8038 PyErr_SetString(PyExc_TypeError,
8039 "character mapping must be in range(256)");
8040 Py_DECREF(x);
8041 return NULL;
8042 }
8043 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008044 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008045 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008046 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008047 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008048 /* wrong return value */
8049 PyErr_Format(PyExc_TypeError,
8050 "character mapping must return integer, bytes or None, not %.400s",
8051 x->ob_type->tp_name);
8052 Py_DECREF(x);
8053 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008054 }
8055}
8056
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008057static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00008058charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008059{
Benjamin Peterson14339b62009-01-31 16:36:08 +00008060 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
8061 /* exponentially overallocate to minimize reallocations */
8062 if (requiredsize < 2*outsize)
8063 requiredsize = 2*outsize;
8064 if (_PyBytes_Resize(outobj, requiredsize))
8065 return -1;
8066 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008067}
8068
Benjamin Peterson14339b62009-01-31 16:36:08 +00008069typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00008070 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00008071} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008072/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00008073 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008074 space is available. Return a new reference to the object that
8075 was put in the output buffer, or Py_None, if the mapping was undefined
8076 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008077 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008078static charmapencode_result
8079charmapencode_output(Py_UNICODE c, PyObject *mapping,
8080 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008081{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008082 PyObject *rep;
8083 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008084 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008085
Christian Heimes90aa7642007-12-19 02:45:37 +00008086 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008087 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008088 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008089 if (res == -1)
8090 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 if (outsize<requiredsize)
8092 if (charmapencode_resize(outobj, outpos, requiredsize))
8093 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008094 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 outstart[(*outpos)++] = (char)res;
8096 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008097 }
8098
8099 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008100 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008101 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008102 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008103 Py_DECREF(rep);
8104 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008105 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008106 if (PyLong_Check(rep)) {
8107 Py_ssize_t requiredsize = *outpos+1;
8108 if (outsize<requiredsize)
8109 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8110 Py_DECREF(rep);
8111 return enc_EXCEPTION;
8112 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008113 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008114 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008115 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008116 else {
8117 const char *repchars = PyBytes_AS_STRING(rep);
8118 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8119 Py_ssize_t requiredsize = *outpos+repsize;
8120 if (outsize<requiredsize)
8121 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8122 Py_DECREF(rep);
8123 return enc_EXCEPTION;
8124 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008125 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008126 memcpy(outstart + *outpos, repchars, repsize);
8127 *outpos += repsize;
8128 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008129 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008130 Py_DECREF(rep);
8131 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008132}
8133
8134/* handle an error in PyUnicode_EncodeCharmap
8135 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008136static int
8137charmap_encoding_error(
Martin v. Löwis18e16552006-02-15 17:27:45 +00008138 const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008139 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008140 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008141 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008142{
8143 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008144 Py_ssize_t repsize;
8145 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008146 Py_UNICODE *uni2;
8147 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008148 Py_ssize_t collstartpos = *inpos;
8149 Py_ssize_t collendpos = *inpos+1;
8150 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008151 char *encoding = "charmap";
8152 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008153 charmapencode_result x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008154
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008155 /* find all unencodable characters */
8156 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008157 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008158 if (Py_TYPE(mapping) == &EncodingMapType) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008159 int res = encoding_map_lookup(p[collendpos], mapping);
8160 if (res != -1)
8161 break;
8162 ++collendpos;
8163 continue;
8164 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008165
Benjamin Peterson29060642009-01-31 22:14:21 +00008166 rep = charmapencode_lookup(p[collendpos], mapping);
8167 if (rep==NULL)
8168 return -1;
8169 else if (rep!=Py_None) {
8170 Py_DECREF(rep);
8171 break;
8172 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008173 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008174 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008175 }
8176 /* cache callback name lookup
8177 * (if not done yet, i.e. it's the first error) */
8178 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008179 if ((errors==NULL) || (!strcmp(errors, "strict")))
8180 *known_errorHandler = 1;
8181 else if (!strcmp(errors, "replace"))
8182 *known_errorHandler = 2;
8183 else if (!strcmp(errors, "ignore"))
8184 *known_errorHandler = 3;
8185 else if (!strcmp(errors, "xmlcharrefreplace"))
8186 *known_errorHandler = 4;
8187 else
8188 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008189 }
8190 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008191 case 1: /* strict */
8192 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8193 return -1;
8194 case 2: /* replace */
8195 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 x = charmapencode_output('?', mapping, res, respos);
8197 if (x==enc_EXCEPTION) {
8198 return -1;
8199 }
8200 else if (x==enc_FAILED) {
8201 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8202 return -1;
8203 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008204 }
8205 /* fall through */
8206 case 3: /* ignore */
8207 *inpos = collendpos;
8208 break;
8209 case 4: /* xmlcharrefreplace */
8210 /* generate replacement (temporarily (mis)uses p) */
8211 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008212 char buffer[2+29+1+1];
8213 char *cp;
8214 sprintf(buffer, "&#%d;", (int)p[collpos]);
8215 for (cp = buffer; *cp; ++cp) {
8216 x = charmapencode_output(*cp, mapping, res, respos);
8217 if (x==enc_EXCEPTION)
8218 return -1;
8219 else if (x==enc_FAILED) {
8220 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8221 return -1;
8222 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008223 }
8224 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008225 *inpos = collendpos;
8226 break;
8227 default:
8228 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Benjamin Peterson29060642009-01-31 22:14:21 +00008229 encoding, reason, p, size, exceptionObject,
8230 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008231 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008232 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008233 if (PyBytes_Check(repunicode)) {
8234 /* Directly copy bytes result to output. */
8235 Py_ssize_t outsize = PyBytes_Size(*res);
8236 Py_ssize_t requiredsize;
8237 repsize = PyBytes_Size(repunicode);
8238 requiredsize = *respos + repsize;
8239 if (requiredsize > outsize)
8240 /* Make room for all additional bytes. */
8241 if (charmapencode_resize(res, respos, requiredsize)) {
8242 Py_DECREF(repunicode);
8243 return -1;
8244 }
8245 memcpy(PyBytes_AsString(*res) + *respos,
8246 PyBytes_AsString(repunicode), repsize);
8247 *respos += repsize;
8248 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008249 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008250 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008251 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008252 /* generate replacement */
8253 repsize = PyUnicode_GET_SIZE(repunicode);
8254 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 x = charmapencode_output(*uni2, mapping, res, respos);
8256 if (x==enc_EXCEPTION) {
8257 return -1;
8258 }
8259 else if (x==enc_FAILED) {
8260 Py_DECREF(repunicode);
8261 raise_encode_exception(exceptionObject, encoding, p, size, collstartpos, collendpos, reason);
8262 return -1;
8263 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008264 }
8265 *inpos = newpos;
8266 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008267 }
8268 return 0;
8269}
8270
Alexander Belopolsky40018472011-02-26 01:02:56 +00008271PyObject *
8272PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8273 Py_ssize_t size,
8274 PyObject *mapping,
8275 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008277 /* output object */
8278 PyObject *res = NULL;
8279 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008280 Py_ssize_t inpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008281 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008282 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283 PyObject *errorHandler = NULL;
8284 PyObject *exc = NULL;
8285 /* the following variable is used for caching string comparisons
8286 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8287 * 3=ignore, 4=xmlcharrefreplace */
8288 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008289
8290 /* Default to Latin-1 */
8291 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008292 return PyUnicode_EncodeLatin1(p, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008293
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294 /* allocate enough for a simple encoding without
8295 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008296 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008297 if (res == NULL)
8298 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008299 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008300 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008302 while (inpos<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 /* try to encode it */
8304 charmapencode_result x = charmapencode_output(p[inpos], mapping, &res, &respos);
8305 if (x==enc_EXCEPTION) /* error */
8306 goto onError;
8307 if (x==enc_FAILED) { /* unencodable character */
8308 if (charmap_encoding_error(p, size, &inpos, mapping,
8309 &exc,
8310 &known_errorHandler, &errorHandler, errors,
8311 &res, &respos)) {
8312 goto onError;
8313 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008314 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 else
8316 /* done with this character => adjust input position */
8317 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008318 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008321 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008322 if (_PyBytes_Resize(&res, respos) < 0)
8323 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008324
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008325 Py_XDECREF(exc);
8326 Py_XDECREF(errorHandler);
8327 return res;
8328
Benjamin Peterson29060642009-01-31 22:14:21 +00008329 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330 Py_XDECREF(res);
8331 Py_XDECREF(exc);
8332 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008333 return NULL;
8334}
8335
Alexander Belopolsky40018472011-02-26 01:02:56 +00008336PyObject *
8337PyUnicode_AsCharmapString(PyObject *unicode,
8338 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008339{
8340 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 PyErr_BadArgument();
8342 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008343 }
8344 return PyUnicode_EncodeCharmap(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00008345 PyUnicode_GET_SIZE(unicode),
8346 mapping,
8347 NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008348}
8349
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008351static void
8352make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008353 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008354 Py_ssize_t startpos, Py_ssize_t endpos,
8355 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008356{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008358 *exceptionObject = _PyUnicodeTranslateError_Create(
8359 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008360 }
8361 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008362 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8363 goto onError;
8364 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8365 goto onError;
8366 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8367 goto onError;
8368 return;
8369 onError:
8370 Py_DECREF(*exceptionObject);
8371 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008372 }
8373}
8374
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008376static void
8377raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008378 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008379 Py_ssize_t startpos, Py_ssize_t endpos,
8380 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008381{
8382 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386}
8387
8388/* error handling callback helper:
8389 build arguments, call the callback and check the arguments,
8390 put the result into newpos and return the replacement string, which
8391 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008392static PyObject *
8393unicode_translate_call_errorhandler(const char *errors,
8394 PyObject **errorHandler,
8395 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008396 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008397 Py_ssize_t startpos, Py_ssize_t endpos,
8398 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008400 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008402 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008403 PyObject *restuple;
8404 PyObject *resunicode;
8405
8406 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008407 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008408 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008409 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008410 }
8411
8412 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008413 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008414 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008415 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008416
8417 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008420 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008421 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008422 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008423 Py_DECREF(restuple);
8424 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 }
8426 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 &resunicode, &i_newpos)) {
8428 Py_DECREF(restuple);
8429 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008430 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008431 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008432 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008433 else
8434 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008435 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8437 Py_DECREF(restuple);
8438 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008439 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 Py_INCREF(resunicode);
8441 Py_DECREF(restuple);
8442 return resunicode;
8443}
8444
8445/* Lookup the character ch in the mapping and put the result in result,
8446 which must be decrefed by the caller.
8447 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008448static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008449charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450{
Christian Heimes217cfd12007-12-02 14:31:20 +00008451 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008452 PyObject *x;
8453
8454 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008456 x = PyObject_GetItem(mapping, w);
8457 Py_DECREF(w);
8458 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8460 /* No mapping found means: use 1:1 mapping. */
8461 PyErr_Clear();
8462 *result = NULL;
8463 return 0;
8464 } else
8465 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 }
8467 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 *result = x;
8469 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008471 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008472 long value = PyLong_AS_LONG(x);
8473 long max = PyUnicode_GetMax();
8474 if (value < 0 || value > max) {
8475 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008476 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 Py_DECREF(x);
8478 return -1;
8479 }
8480 *result = x;
8481 return 0;
8482 }
8483 else if (PyUnicode_Check(x)) {
8484 *result = x;
8485 return 0;
8486 }
8487 else {
8488 /* wrong return value */
8489 PyErr_SetString(PyExc_TypeError,
8490 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008491 Py_DECREF(x);
8492 return -1;
8493 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008494}
8495/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 if not reallocate and adjust various state variables.
8497 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008498static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008500 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008501{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008503 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 /* exponentially overallocate to minimize reallocations */
8505 if (requiredsize < 2 * oldsize)
8506 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008507 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8508 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008509 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008510 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 }
8512 return 0;
8513}
8514/* lookup the character, put the result in the output string and adjust
8515 various state variables. Return a new reference to the object that
8516 was put in the output buffer in *result, or Py_None, if the mapping was
8517 undefined (in which case no character was written).
8518 The called must decref result.
8519 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008520static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008521charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8522 PyObject *mapping, Py_UCS4 **output,
8523 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008524 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008525{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8527 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008530 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008531 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008532 }
8533 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008535 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008536 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008537 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008538 }
8539 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008540 Py_ssize_t repsize;
8541 if (PyUnicode_READY(*res) == -1)
8542 return -1;
8543 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 if (repsize==1) {
8545 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008546 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 }
8548 else if (repsize!=0) {
8549 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008550 Py_ssize_t requiredsize = *opos +
8551 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008552 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008553 Py_ssize_t i;
8554 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008555 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008556 for(i = 0; i < repsize; i++)
8557 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008559 }
8560 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008562 return 0;
8563}
8564
Alexander Belopolsky40018472011-02-26 01:02:56 +00008565PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566_PyUnicode_TranslateCharmap(PyObject *input,
8567 PyObject *mapping,
8568 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008570 /* input object */
8571 char *idata;
8572 Py_ssize_t size, i;
8573 int kind;
8574 /* output buffer */
8575 Py_UCS4 *output = NULL;
8576 Py_ssize_t osize;
8577 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008578 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008580 char *reason = "character maps to <undefined>";
8581 PyObject *errorHandler = NULL;
8582 PyObject *exc = NULL;
8583 /* the following variable is used for caching string comparisons
8584 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8585 * 3=ignore, 4=xmlcharrefreplace */
8586 int known_errorHandler = -1;
8587
Guido van Rossumd57fd912000-03-10 22:53:23 +00008588 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008589 PyErr_BadArgument();
8590 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008591 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008592
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008593 if (PyUnicode_READY(input) == -1)
8594 return NULL;
8595 idata = (char*)PyUnicode_DATA(input);
8596 kind = PyUnicode_KIND(input);
8597 size = PyUnicode_GET_LENGTH(input);
8598 i = 0;
8599
8600 if (size == 0) {
8601 Py_INCREF(input);
8602 return input;
8603 }
8604
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008605 /* allocate enough for a simple 1:1 translation without
8606 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 osize = size;
8608 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8609 opos = 0;
8610 if (output == NULL) {
8611 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008612 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008613 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008614
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008616 /* try to encode it */
8617 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 if (charmaptranslate_output(input, i, mapping,
8619 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 Py_XDECREF(x);
8621 goto onError;
8622 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008623 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008626 else { /* untranslatable character */
8627 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8628 Py_ssize_t repsize;
8629 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008630 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008631 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 Py_ssize_t collstart = i;
8633 Py_ssize_t collend = i+1;
8634 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008635
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 while (collend < size) {
8638 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 goto onError;
8640 Py_XDECREF(x);
8641 if (x!=Py_None)
8642 break;
8643 ++collend;
8644 }
8645 /* cache callback name lookup
8646 * (if not done yet, i.e. it's the first error) */
8647 if (known_errorHandler==-1) {
8648 if ((errors==NULL) || (!strcmp(errors, "strict")))
8649 known_errorHandler = 1;
8650 else if (!strcmp(errors, "replace"))
8651 known_errorHandler = 2;
8652 else if (!strcmp(errors, "ignore"))
8653 known_errorHandler = 3;
8654 else if (!strcmp(errors, "xmlcharrefreplace"))
8655 known_errorHandler = 4;
8656 else
8657 known_errorHandler = 0;
8658 }
8659 switch (known_errorHandler) {
8660 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661 raise_translate_exception(&exc, input, collstart,
8662 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008663 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008664 case 2: /* replace */
8665 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008666 for (coll = collstart; coll<collend; coll++)
8667 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008668 /* fall through */
8669 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008671 break;
8672 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008673 /* generate replacement (temporarily (mis)uses i) */
8674 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008675 char buffer[2+29+1+1];
8676 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008677 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8678 if (charmaptranslate_makespace(&output, &osize,
8679 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008680 goto onError;
8681 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008682 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008683 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008684 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008685 break;
8686 default:
8687 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008688 reason, input, &exc,
8689 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008690 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008691 goto onError;
8692 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 repsize = PyUnicode_GET_LENGTH(repunicode);
8694 if (charmaptranslate_makespace(&output, &osize,
8695 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008696 Py_DECREF(repunicode);
8697 goto onError;
8698 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008699 for (uni2 = 0; repsize-->0; ++uni2)
8700 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8701 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008703 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008704 }
8705 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008706 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8707 if (!res)
8708 goto onError;
8709 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008710 Py_XDECREF(exc);
8711 Py_XDECREF(errorHandler);
8712 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008713
Benjamin Peterson29060642009-01-31 22:14:21 +00008714 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008715 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008716 Py_XDECREF(exc);
8717 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008718 return NULL;
8719}
8720
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008721/* Deprecated. Use PyUnicode_Translate instead. */
8722PyObject *
8723PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8724 Py_ssize_t size,
8725 PyObject *mapping,
8726 const char *errors)
8727{
8728 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8729 if (!unicode)
8730 return NULL;
8731 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8732}
8733
Alexander Belopolsky40018472011-02-26 01:02:56 +00008734PyObject *
8735PyUnicode_Translate(PyObject *str,
8736 PyObject *mapping,
8737 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008738{
8739 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008740
Guido van Rossumd57fd912000-03-10 22:53:23 +00008741 str = PyUnicode_FromObject(str);
8742 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008743 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008744 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008745 Py_DECREF(str);
8746 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008747
Benjamin Peterson29060642009-01-31 22:14:21 +00008748 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008749 Py_XDECREF(str);
8750 return NULL;
8751}
Tim Petersced69f82003-09-16 20:30:58 +00008752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008753static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008754fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008755{
8756 /* No need to call PyUnicode_READY(self) because this function is only
8757 called as a callback from fixup() which does it already. */
8758 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8759 const int kind = PyUnicode_KIND(self);
8760 void *data = PyUnicode_DATA(self);
8761 Py_UCS4 maxchar = 0, ch, fixed;
8762 Py_ssize_t i;
8763
8764 for (i = 0; i < len; ++i) {
8765 ch = PyUnicode_READ(kind, data, i);
8766 fixed = 0;
8767 if (ch > 127) {
8768 if (Py_UNICODE_ISSPACE(ch))
8769 fixed = ' ';
8770 else {
8771 const int decimal = Py_UNICODE_TODECIMAL(ch);
8772 if (decimal >= 0)
8773 fixed = '0' + decimal;
8774 }
8775 if (fixed != 0) {
8776 if (fixed > maxchar)
8777 maxchar = fixed;
8778 PyUnicode_WRITE(kind, data, i, fixed);
8779 }
8780 else if (ch > maxchar)
8781 maxchar = ch;
8782 }
8783 else if (ch > maxchar)
8784 maxchar = ch;
8785 }
8786
8787 return maxchar;
8788}
8789
8790PyObject *
8791_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8792{
8793 if (!PyUnicode_Check(unicode)) {
8794 PyErr_BadInternalCall();
8795 return NULL;
8796 }
8797 if (PyUnicode_READY(unicode) == -1)
8798 return NULL;
8799 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8800 /* If the string is already ASCII, just return the same string */
8801 Py_INCREF(unicode);
8802 return unicode;
8803 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008804 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008805}
8806
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008807PyObject *
8808PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8809 Py_ssize_t length)
8810{
8811 PyObject *result;
8812 Py_UNICODE *p; /* write pointer into result */
8813 Py_ssize_t i;
8814 /* Copy to a new string */
8815 result = (PyObject *)_PyUnicode_New(length);
8816 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8817 if (result == NULL)
8818 return result;
8819 p = PyUnicode_AS_UNICODE(result);
8820 /* Iterate over code points */
8821 for (i = 0; i < length; i++) {
8822 Py_UNICODE ch =s[i];
8823 if (ch > 127) {
8824 int decimal = Py_UNICODE_TODECIMAL(ch);
8825 if (decimal >= 0)
8826 p[i] = '0' + decimal;
8827 }
8828 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008829#ifndef DONT_MAKE_RESULT_READY
8830 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008831 Py_DECREF(result);
8832 return NULL;
8833 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008834#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008835 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008836 return result;
8837}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008838/* --- Decimal Encoder ---------------------------------------------------- */
8839
Alexander Belopolsky40018472011-02-26 01:02:56 +00008840int
8841PyUnicode_EncodeDecimal(Py_UNICODE *s,
8842 Py_ssize_t length,
8843 char *output,
8844 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008845{
8846 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008847 PyObject *errorHandler = NULL;
8848 PyObject *exc = NULL;
8849 const char *encoding = "decimal";
8850 const char *reason = "invalid decimal Unicode string";
8851 /* the following variable is used for caching string comparisons
8852 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8853 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008854
8855 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008856 PyErr_BadArgument();
8857 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008858 }
8859
8860 p = s;
8861 end = s + length;
8862 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008863 register Py_UNICODE ch = *p;
8864 int decimal;
8865 PyObject *repunicode;
8866 Py_ssize_t repsize;
8867 Py_ssize_t newpos;
8868 Py_UNICODE *uni2;
8869 Py_UNICODE *collstart;
8870 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008871
Benjamin Peterson29060642009-01-31 22:14:21 +00008872 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008873 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008874 ++p;
8875 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008876 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008877 decimal = Py_UNICODE_TODECIMAL(ch);
8878 if (decimal >= 0) {
8879 *output++ = '0' + decimal;
8880 ++p;
8881 continue;
8882 }
8883 if (0 < ch && ch < 256) {
8884 *output++ = (char)ch;
8885 ++p;
8886 continue;
8887 }
8888 /* All other characters are considered unencodable */
8889 collstart = p;
8890 collend = p+1;
8891 while (collend < end) {
8892 if ((0 < *collend && *collend < 256) ||
8893 !Py_UNICODE_ISSPACE(*collend) ||
8894 Py_UNICODE_TODECIMAL(*collend))
8895 break;
8896 }
8897 /* cache callback name lookup
8898 * (if not done yet, i.e. it's the first error) */
8899 if (known_errorHandler==-1) {
8900 if ((errors==NULL) || (!strcmp(errors, "strict")))
8901 known_errorHandler = 1;
8902 else if (!strcmp(errors, "replace"))
8903 known_errorHandler = 2;
8904 else if (!strcmp(errors, "ignore"))
8905 known_errorHandler = 3;
8906 else if (!strcmp(errors, "xmlcharrefreplace"))
8907 known_errorHandler = 4;
8908 else
8909 known_errorHandler = 0;
8910 }
8911 switch (known_errorHandler) {
8912 case 1: /* strict */
8913 raise_encode_exception(&exc, encoding, s, length, collstart-s, collend-s, reason);
8914 goto onError;
8915 case 2: /* replace */
8916 for (p = collstart; p < collend; ++p)
8917 *output++ = '?';
8918 /* fall through */
8919 case 3: /* ignore */
8920 p = collend;
8921 break;
8922 case 4: /* xmlcharrefreplace */
8923 /* generate replacement (temporarily (mis)uses p) */
8924 for (p = collstart; p < collend; ++p)
8925 output += sprintf(output, "&#%d;", (int)*p);
8926 p = collend;
8927 break;
8928 default:
8929 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
8930 encoding, reason, s, length, &exc,
8931 collstart-s, collend-s, &newpos);
8932 if (repunicode == NULL)
8933 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008934 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008935 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008936 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8937 Py_DECREF(repunicode);
8938 goto onError;
8939 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008940 /* generate replacement */
8941 repsize = PyUnicode_GET_SIZE(repunicode);
8942 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8943 Py_UNICODE ch = *uni2;
8944 if (Py_UNICODE_ISSPACE(ch))
8945 *output++ = ' ';
8946 else {
8947 decimal = Py_UNICODE_TODECIMAL(ch);
8948 if (decimal >= 0)
8949 *output++ = '0' + decimal;
8950 else if (0 < ch && ch < 256)
8951 *output++ = (char)ch;
8952 else {
8953 Py_DECREF(repunicode);
8954 raise_encode_exception(&exc, encoding,
8955 s, length, collstart-s, collend-s, reason);
8956 goto onError;
8957 }
8958 }
8959 }
8960 p = s + newpos;
8961 Py_DECREF(repunicode);
8962 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008963 }
8964 /* 0-terminate the output string */
8965 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008966 Py_XDECREF(exc);
8967 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008968 return 0;
8969
Benjamin Peterson29060642009-01-31 22:14:21 +00008970 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008971 Py_XDECREF(exc);
8972 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008973 return -1;
8974}
8975
Guido van Rossumd57fd912000-03-10 22:53:23 +00008976/* --- Helpers ------------------------------------------------------------ */
8977
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008978static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008979any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008980 Py_ssize_t start,
8981 Py_ssize_t end)
8982{
8983 int kind1, kind2, kind;
8984 void *buf1, *buf2;
8985 Py_ssize_t len1, len2, result;
8986
8987 kind1 = PyUnicode_KIND(s1);
8988 kind2 = PyUnicode_KIND(s2);
8989 kind = kind1 > kind2 ? kind1 : kind2;
8990 buf1 = PyUnicode_DATA(s1);
8991 buf2 = PyUnicode_DATA(s2);
8992 if (kind1 != kind)
8993 buf1 = _PyUnicode_AsKind(s1, kind);
8994 if (!buf1)
8995 return -2;
8996 if (kind2 != kind)
8997 buf2 = _PyUnicode_AsKind(s2, kind);
8998 if (!buf2) {
8999 if (kind1 != kind) PyMem_Free(buf1);
9000 return -2;
9001 }
9002 len1 = PyUnicode_GET_LENGTH(s1);
9003 len2 = PyUnicode_GET_LENGTH(s2);
9004
Victor Stinner794d5672011-10-10 03:21:36 +02009005 if (direction > 0) {
9006 switch(kind) {
9007 case PyUnicode_1BYTE_KIND:
9008 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9009 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
9010 else
9011 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
9012 break;
9013 case PyUnicode_2BYTE_KIND:
9014 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
9015 break;
9016 case PyUnicode_4BYTE_KIND:
9017 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
9018 break;
9019 default:
9020 assert(0); result = -2;
9021 }
9022 }
9023 else {
9024 switch(kind) {
9025 case PyUnicode_1BYTE_KIND:
9026 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
9027 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9028 else
9029 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9030 break;
9031 case PyUnicode_2BYTE_KIND:
9032 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9033 break;
9034 case PyUnicode_4BYTE_KIND:
9035 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9036 break;
9037 default:
9038 assert(0); result = -2;
9039 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 }
9041
9042 if (kind1 != kind)
9043 PyMem_Free(buf1);
9044 if (kind2 != kind)
9045 PyMem_Free(buf2);
9046
9047 return result;
9048}
9049
9050Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009051_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009052 Py_ssize_t n_buffer,
9053 void *digits, Py_ssize_t n_digits,
9054 Py_ssize_t min_width,
9055 const char *grouping,
9056 const char *thousands_sep)
9057{
9058 switch(kind) {
9059 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009060 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9061 return _PyUnicode_ascii_InsertThousandsGrouping(
9062 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9063 min_width, grouping, thousands_sep);
9064 else
9065 return _PyUnicode_ucs1_InsertThousandsGrouping(
9066 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9067 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 case PyUnicode_2BYTE_KIND:
9069 return _PyUnicode_ucs2_InsertThousandsGrouping(
9070 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9071 min_width, grouping, thousands_sep);
9072 case PyUnicode_4BYTE_KIND:
9073 return _PyUnicode_ucs4_InsertThousandsGrouping(
9074 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9075 min_width, grouping, thousands_sep);
9076 }
9077 assert(0);
9078 return -1;
9079}
9080
9081
Thomas Wouters477c8d52006-05-27 19:21:47 +00009082/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009083#define ADJUST_INDICES(start, end, len) \
9084 if (end > len) \
9085 end = len; \
9086 else if (end < 0) { \
9087 end += len; \
9088 if (end < 0) \
9089 end = 0; \
9090 } \
9091 if (start < 0) { \
9092 start += len; \
9093 if (start < 0) \
9094 start = 0; \
9095 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009096
Alexander Belopolsky40018472011-02-26 01:02:56 +00009097Py_ssize_t
9098PyUnicode_Count(PyObject *str,
9099 PyObject *substr,
9100 Py_ssize_t start,
9101 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009102{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009103 Py_ssize_t result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009104 PyUnicodeObject* str_obj;
9105 PyUnicodeObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009106 int kind1, kind2, kind;
9107 void *buf1 = NULL, *buf2 = NULL;
9108 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009109
Thomas Wouters477c8d52006-05-27 19:21:47 +00009110 str_obj = (PyUnicodeObject*) PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009111 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009112 return -1;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009113 sub_obj = (PyUnicodeObject*) PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009114 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009115 Py_DECREF(str_obj);
9116 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009117 }
Tim Petersced69f82003-09-16 20:30:58 +00009118
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009119 kind1 = PyUnicode_KIND(str_obj);
9120 kind2 = PyUnicode_KIND(sub_obj);
9121 kind = kind1 > kind2 ? kind1 : kind2;
9122 buf1 = PyUnicode_DATA(str_obj);
9123 if (kind1 != kind)
9124 buf1 = _PyUnicode_AsKind((PyObject*)str_obj, kind);
9125 if (!buf1)
9126 goto onError;
9127 buf2 = PyUnicode_DATA(sub_obj);
9128 if (kind2 != kind)
9129 buf2 = _PyUnicode_AsKind((PyObject*)sub_obj, kind);
9130 if (!buf2)
9131 goto onError;
9132 len1 = PyUnicode_GET_LENGTH(str_obj);
9133 len2 = PyUnicode_GET_LENGTH(sub_obj);
9134
9135 ADJUST_INDICES(start, end, len1);
9136 switch(kind) {
9137 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009138 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9139 result = asciilib_count(
9140 ((Py_UCS1*)buf1) + start, end - start,
9141 buf2, len2, PY_SSIZE_T_MAX
9142 );
9143 else
9144 result = ucs1lib_count(
9145 ((Py_UCS1*)buf1) + start, end - start,
9146 buf2, len2, PY_SSIZE_T_MAX
9147 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009148 break;
9149 case PyUnicode_2BYTE_KIND:
9150 result = ucs2lib_count(
9151 ((Py_UCS2*)buf1) + start, end - start,
9152 buf2, len2, PY_SSIZE_T_MAX
9153 );
9154 break;
9155 case PyUnicode_4BYTE_KIND:
9156 result = ucs4lib_count(
9157 ((Py_UCS4*)buf1) + start, end - start,
9158 buf2, len2, PY_SSIZE_T_MAX
9159 );
9160 break;
9161 default:
9162 assert(0); result = 0;
9163 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009164
9165 Py_DECREF(sub_obj);
9166 Py_DECREF(str_obj);
9167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009168 if (kind1 != kind)
9169 PyMem_Free(buf1);
9170 if (kind2 != kind)
9171 PyMem_Free(buf2);
9172
Guido van Rossumd57fd912000-03-10 22:53:23 +00009173 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174 onError:
9175 Py_DECREF(sub_obj);
9176 Py_DECREF(str_obj);
9177 if (kind1 != kind && buf1)
9178 PyMem_Free(buf1);
9179 if (kind2 != kind && buf2)
9180 PyMem_Free(buf2);
9181 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009182}
9183
Alexander Belopolsky40018472011-02-26 01:02:56 +00009184Py_ssize_t
9185PyUnicode_Find(PyObject *str,
9186 PyObject *sub,
9187 Py_ssize_t start,
9188 Py_ssize_t end,
9189 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009190{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009191 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009192
Guido van Rossumd57fd912000-03-10 22:53:23 +00009193 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009194 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009195 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009196 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009198 Py_DECREF(str);
9199 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009200 }
Tim Petersced69f82003-09-16 20:30:58 +00009201
Victor Stinner794d5672011-10-10 03:21:36 +02009202 result = any_find_slice(direction,
9203 str, sub, start, end
9204 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009205
Guido van Rossumd57fd912000-03-10 22:53:23 +00009206 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009207 Py_DECREF(sub);
9208
Guido van Rossumd57fd912000-03-10 22:53:23 +00009209 return result;
9210}
9211
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009212Py_ssize_t
9213PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9214 Py_ssize_t start, Py_ssize_t end,
9215 int direction)
9216{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009217 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009218 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 if (PyUnicode_READY(str) == -1)
9220 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009221 if (start < 0 || end < 0) {
9222 PyErr_SetString(PyExc_IndexError, "string index out of range");
9223 return -2;
9224 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 if (end > PyUnicode_GET_LENGTH(str))
9226 end = PyUnicode_GET_LENGTH(str);
9227 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009228 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9229 kind, end-start, ch, direction);
9230 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009231 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009232 else
9233 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009234}
9235
Alexander Belopolsky40018472011-02-26 01:02:56 +00009236static int
9237tailmatch(PyUnicodeObject *self,
9238 PyUnicodeObject *substring,
9239 Py_ssize_t start,
9240 Py_ssize_t end,
9241 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009242{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009243 int kind_self;
9244 int kind_sub;
9245 void *data_self;
9246 void *data_sub;
9247 Py_ssize_t offset;
9248 Py_ssize_t i;
9249 Py_ssize_t end_sub;
9250
9251 if (PyUnicode_READY(self) == -1 ||
9252 PyUnicode_READY(substring) == -1)
9253 return 0;
9254
9255 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009256 return 1;
9257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009258 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9259 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009261 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009262
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009263 kind_self = PyUnicode_KIND(self);
9264 data_self = PyUnicode_DATA(self);
9265 kind_sub = PyUnicode_KIND(substring);
9266 data_sub = PyUnicode_DATA(substring);
9267 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9268
9269 if (direction > 0)
9270 offset = end;
9271 else
9272 offset = start;
9273
9274 if (PyUnicode_READ(kind_self, data_self, offset) ==
9275 PyUnicode_READ(kind_sub, data_sub, 0) &&
9276 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9277 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9278 /* If both are of the same kind, memcmp is sufficient */
9279 if (kind_self == kind_sub) {
9280 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009281 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009282 data_sub,
9283 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009284 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009285 }
9286 /* otherwise we have to compare each character by first accesing it */
9287 else {
9288 /* We do not need to compare 0 and len(substring)-1 because
9289 the if statement above ensured already that they are equal
9290 when we end up here. */
9291 // TODO: honor direction and do a forward or backwards search
9292 for (i = 1; i < end_sub; ++i) {
9293 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9294 PyUnicode_READ(kind_sub, data_sub, i))
9295 return 0;
9296 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009297 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009299 }
9300
9301 return 0;
9302}
9303
Alexander Belopolsky40018472011-02-26 01:02:56 +00009304Py_ssize_t
9305PyUnicode_Tailmatch(PyObject *str,
9306 PyObject *substr,
9307 Py_ssize_t start,
9308 Py_ssize_t end,
9309 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009310{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009311 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009312
Guido van Rossumd57fd912000-03-10 22:53:23 +00009313 str = PyUnicode_FromObject(str);
9314 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009315 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316 substr = PyUnicode_FromObject(substr);
9317 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009318 Py_DECREF(str);
9319 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320 }
Tim Petersced69f82003-09-16 20:30:58 +00009321
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322 result = tailmatch((PyUnicodeObject *)str,
Benjamin Peterson29060642009-01-31 22:14:21 +00009323 (PyUnicodeObject *)substr,
9324 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009325 Py_DECREF(str);
9326 Py_DECREF(substr);
9327 return result;
9328}
9329
Guido van Rossumd57fd912000-03-10 22:53:23 +00009330/* Apply fixfct filter to the Unicode object self and return a
9331 reference to the modified object */
9332
Alexander Belopolsky40018472011-02-26 01:02:56 +00009333static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009334fixup(PyObject *self,
9335 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009336{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009337 PyObject *u;
9338 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009339
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009340 if (PyUnicode_READY(self) == -1)
9341 return NULL;
9342 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9343 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9344 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009346 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009347
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009348 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009349 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009350
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009351 /* fix functions return the new maximum character in a string,
9352 if the kind of the resulting unicode object does not change,
9353 everything is fine. Otherwise we need to change the string kind
9354 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009355 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009356 if (maxchar_new == 0)
9357 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9358 else if (maxchar_new <= 127)
9359 maxchar_new = 127;
9360 else if (maxchar_new <= 255)
9361 maxchar_new = 255;
9362 else if (maxchar_new <= 65535)
9363 maxchar_new = 65535;
9364 else
9365 maxchar_new = 1114111; /* 0x10ffff */
9366
9367 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009368 /* fixfct should return TRUE if it modified the buffer. If
9369 FALSE, return a reference to the original buffer instead
9370 (to save space, not time) */
9371 Py_INCREF(self);
9372 Py_DECREF(u);
9373 return (PyObject*) self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 else if (maxchar_new == maxchar_old) {
9376 return u;
9377 }
9378 else {
9379 /* In case the maximum character changed, we need to
9380 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009381 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009382 if (v == NULL) {
9383 Py_DECREF(u);
9384 return NULL;
9385 }
9386 if (maxchar_new > maxchar_old) {
9387 /* If the maxchar increased so that the kind changed, not all
9388 characters are representable anymore and we need to fix the
9389 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009390 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009391 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9393 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009394 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009395 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009396 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009397
9398 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009399 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 return v;
9401 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009402}
9403
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009404static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009405fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009406{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 /* No need to call PyUnicode_READY(self) because this function is only
9408 called as a callback from fixup() which does it already. */
9409 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9410 const int kind = PyUnicode_KIND(self);
9411 void *data = PyUnicode_DATA(self);
9412 int touched = 0;
9413 Py_UCS4 maxchar = 0;
9414 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009415
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 for (i = 0; i < len; ++i) {
9417 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9418 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9419 if (up != ch) {
9420 if (up > maxchar)
9421 maxchar = up;
9422 PyUnicode_WRITE(kind, data, i, up);
9423 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009424 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009425 else if (ch > maxchar)
9426 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009427 }
9428
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 if (touched)
9430 return maxchar;
9431 else
9432 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009433}
9434
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009435static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009436fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009437{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009438 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9439 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9440 const int kind = PyUnicode_KIND(self);
9441 void *data = PyUnicode_DATA(self);
9442 int touched = 0;
9443 Py_UCS4 maxchar = 0;
9444 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009446 for(i = 0; i < len; ++i) {
9447 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9448 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9449 if (lo != ch) {
9450 if (lo > maxchar)
9451 maxchar = lo;
9452 PyUnicode_WRITE(kind, data, i, lo);
9453 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455 else if (ch > maxchar)
9456 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009457 }
9458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009459 if (touched)
9460 return maxchar;
9461 else
9462 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009463}
9464
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009466fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9469 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9470 const int kind = PyUnicode_KIND(self);
9471 void *data = PyUnicode_DATA(self);
9472 int touched = 0;
9473 Py_UCS4 maxchar = 0;
9474 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476 for(i = 0; i < len; ++i) {
9477 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9478 Py_UCS4 nu = 0;
9479
9480 if (Py_UNICODE_ISUPPER(ch))
9481 nu = Py_UNICODE_TOLOWER(ch);
9482 else if (Py_UNICODE_ISLOWER(ch))
9483 nu = Py_UNICODE_TOUPPER(ch);
9484
9485 if (nu != 0) {
9486 if (nu > maxchar)
9487 maxchar = nu;
9488 PyUnicode_WRITE(kind, data, i, nu);
9489 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 else if (ch > maxchar)
9492 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009493 }
9494
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009495 if (touched)
9496 return maxchar;
9497 else
9498 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009499}
9500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009501static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009502fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009504 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9505 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9506 const int kind = PyUnicode_KIND(self);
9507 void *data = PyUnicode_DATA(self);
9508 int touched = 0;
9509 Py_UCS4 maxchar = 0;
9510 Py_ssize_t i = 0;
9511 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009512
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009513 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009514 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515
9516 ch = PyUnicode_READ(kind, data, i);
9517 if (!Py_UNICODE_ISUPPER(ch)) {
9518 maxchar = Py_UNICODE_TOUPPER(ch);
9519 PyUnicode_WRITE(kind, data, i, maxchar);
9520 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009521 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009522 ++i;
9523 for(; i < len; ++i) {
9524 ch = PyUnicode_READ(kind, data, i);
9525 if (!Py_UNICODE_ISLOWER(ch)) {
9526 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9527 if (lo > maxchar)
9528 maxchar = lo;
9529 PyUnicode_WRITE(kind, data, i, lo);
9530 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009531 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009532 else if (ch > maxchar)
9533 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009534 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009535
9536 if (touched)
9537 return maxchar;
9538 else
9539 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009540}
9541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009542static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009543fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009544{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009545 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9546 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9547 const int kind = PyUnicode_KIND(self);
9548 void *data = PyUnicode_DATA(self);
9549 Py_UCS4 maxchar = 0;
9550 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551 int previous_is_cased;
9552
9553 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 if (len == 1) {
9555 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9556 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9557 if (ti != ch) {
9558 PyUnicode_WRITE(kind, data, i, ti);
9559 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009560 }
9561 else
9562 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009563 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009564 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009565 for(; i < len; ++i) {
9566 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9567 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009568
Benjamin Peterson29060642009-01-31 22:14:21 +00009569 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009570 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009571 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009572 nu = Py_UNICODE_TOTITLE(ch);
9573
9574 if (nu > maxchar)
9575 maxchar = nu;
9576 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009577
Benjamin Peterson29060642009-01-31 22:14:21 +00009578 if (Py_UNICODE_ISLOWER(ch) ||
9579 Py_UNICODE_ISUPPER(ch) ||
9580 Py_UNICODE_ISTITLE(ch))
9581 previous_is_cased = 1;
9582 else
9583 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009584 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009585 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009586}
9587
Tim Peters8ce9f162004-08-27 01:49:32 +00009588PyObject *
9589PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009590{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009591 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009592 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009593 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009594 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009595 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9596 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009597 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009598 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009599 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009600 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009601 int use_memcpy;
9602 unsigned char *res_data = NULL, *sep_data = NULL;
9603 PyObject *last_obj;
9604 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009605
Tim Peters05eba1f2004-08-27 21:32:02 +00009606 fseq = PySequence_Fast(seq, "");
9607 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009608 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009609 }
9610
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009611 /* NOTE: the following code can't call back into Python code,
9612 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009613 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009614
Tim Peters05eba1f2004-08-27 21:32:02 +00009615 seqlen = PySequence_Fast_GET_SIZE(fseq);
9616 /* If empty sequence, return u"". */
9617 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009618 Py_DECREF(fseq);
9619 Py_INCREF(unicode_empty);
9620 res = unicode_empty;
9621 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009622 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009623
Tim Peters05eba1f2004-08-27 21:32:02 +00009624 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009625 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009626 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009627 if (seqlen == 1) {
9628 if (PyUnicode_CheckExact(items[0])) {
9629 res = items[0];
9630 Py_INCREF(res);
9631 Py_DECREF(fseq);
9632 return res;
9633 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009634 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009635 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009636 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009637 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009638 /* Set up sep and seplen */
9639 if (separator == NULL) {
9640 /* fall back to a blank space separator */
9641 sep = PyUnicode_FromOrdinal(' ');
9642 if (!sep)
9643 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009644 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009645 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009646 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009647 else {
9648 if (!PyUnicode_Check(separator)) {
9649 PyErr_Format(PyExc_TypeError,
9650 "separator: expected str instance,"
9651 " %.80s found",
9652 Py_TYPE(separator)->tp_name);
9653 goto onError;
9654 }
9655 if (PyUnicode_READY(separator))
9656 goto onError;
9657 sep = separator;
9658 seplen = PyUnicode_GET_LENGTH(separator);
9659 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9660 /* inc refcount to keep this code path symmetric with the
9661 above case of a blank separator */
9662 Py_INCREF(sep);
9663 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009664 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009665 }
9666
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009667 /* There are at least two things to join, or else we have a subclass
9668 * of str in the sequence.
9669 * Do a pre-pass to figure out the total amount of space we'll
9670 * need (sz), and see whether all argument are strings.
9671 */
9672 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009673#ifdef Py_DEBUG
9674 use_memcpy = 0;
9675#else
9676 use_memcpy = 1;
9677#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009678 for (i = 0; i < seqlen; i++) {
9679 const Py_ssize_t old_sz = sz;
9680 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009681 if (!PyUnicode_Check(item)) {
9682 PyErr_Format(PyExc_TypeError,
9683 "sequence item %zd: expected str instance,"
9684 " %.80s found",
9685 i, Py_TYPE(item)->tp_name);
9686 goto onError;
9687 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009688 if (PyUnicode_READY(item) == -1)
9689 goto onError;
9690 sz += PyUnicode_GET_LENGTH(item);
9691 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009692 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009693 if (i != 0)
9694 sz += seplen;
9695 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9696 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009697 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009698 goto onError;
9699 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009700 if (use_memcpy && last_obj != NULL) {
9701 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9702 use_memcpy = 0;
9703 }
9704 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009705 }
Tim Petersced69f82003-09-16 20:30:58 +00009706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009708 if (res == NULL)
9709 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009710
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009711 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009712#ifdef Py_DEBUG
9713 use_memcpy = 0;
9714#else
9715 if (use_memcpy) {
9716 res_data = PyUnicode_1BYTE_DATA(res);
9717 kind = PyUnicode_KIND(res);
9718 if (seplen != 0)
9719 sep_data = PyUnicode_1BYTE_DATA(sep);
9720 }
9721#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009722 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009723 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009724 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009725 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009726 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009727 if (use_memcpy) {
9728 Py_MEMCPY(res_data,
9729 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009730 kind * seplen);
9731 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009732 }
9733 else {
9734 copy_characters(res, res_offset, sep, 0, seplen);
9735 res_offset += seplen;
9736 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009737 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009738 itemlen = PyUnicode_GET_LENGTH(item);
9739 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009740 if (use_memcpy) {
9741 Py_MEMCPY(res_data,
9742 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009743 kind * itemlen);
9744 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009745 }
9746 else {
9747 copy_characters(res, res_offset, item, 0, itemlen);
9748 res_offset += itemlen;
9749 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009750 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009751 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009752 if (use_memcpy)
9753 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009754 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009755 else
9756 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009757
Tim Peters05eba1f2004-08-27 21:32:02 +00009758 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009759 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009760 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009761 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762
Benjamin Peterson29060642009-01-31 22:14:21 +00009763 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009764 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009766 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009767 return NULL;
9768}
9769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770#define FILL(kind, data, value, start, length) \
9771 do { \
9772 Py_ssize_t i_ = 0; \
9773 assert(kind != PyUnicode_WCHAR_KIND); \
9774 switch ((kind)) { \
9775 case PyUnicode_1BYTE_KIND: { \
9776 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9777 memset(to_, (unsigned char)value, length); \
9778 break; \
9779 } \
9780 case PyUnicode_2BYTE_KIND: { \
9781 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9782 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9783 break; \
9784 } \
9785 default: { \
9786 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9787 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9788 break; \
9789 } \
9790 } \
9791 } while (0)
9792
Victor Stinner9310abb2011-10-05 00:59:23 +02009793static PyObject *
9794pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009795 Py_ssize_t left,
9796 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009799 PyObject *u;
9800 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009801 int kind;
9802 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803
9804 if (left < 0)
9805 left = 0;
9806 if (right < 0)
9807 right = 0;
9808
Tim Peters7a29bd52001-09-12 03:03:31 +00009809 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009810 Py_INCREF(self);
9811 return self;
9812 }
9813
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009814 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9815 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009816 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9817 return NULL;
9818 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009819 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9820 if (fill > maxchar)
9821 maxchar = fill;
9822 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009823 if (!u)
9824 return NULL;
9825
9826 kind = PyUnicode_KIND(u);
9827 data = PyUnicode_DATA(u);
9828 if (left)
9829 FILL(kind, data, fill, 0, left);
9830 if (right)
9831 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009832 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009833 assert(_PyUnicode_CheckConsistency(u, 1));
9834 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009836#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009837
Alexander Belopolsky40018472011-02-26 01:02:56 +00009838PyObject *
9839PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009840{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009841 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009842
9843 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009844 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009845 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009847 switch(PyUnicode_KIND(string)) {
9848 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009849 if (PyUnicode_IS_ASCII(string))
9850 list = asciilib_splitlines(
9851 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9852 PyUnicode_GET_LENGTH(string), keepends);
9853 else
9854 list = ucs1lib_splitlines(
9855 (PyObject*) string, PyUnicode_1BYTE_DATA(string),
9856 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009857 break;
9858 case PyUnicode_2BYTE_KIND:
9859 list = ucs2lib_splitlines(
9860 (PyObject*) string, PyUnicode_2BYTE_DATA(string),
9861 PyUnicode_GET_LENGTH(string), keepends);
9862 break;
9863 case PyUnicode_4BYTE_KIND:
9864 list = ucs4lib_splitlines(
9865 (PyObject*) string, PyUnicode_4BYTE_DATA(string),
9866 PyUnicode_GET_LENGTH(string), keepends);
9867 break;
9868 default:
9869 assert(0);
9870 list = 0;
9871 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009872 Py_DECREF(string);
9873 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009874}
9875
Alexander Belopolsky40018472011-02-26 01:02:56 +00009876static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009877split(PyObject *self,
9878 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009879 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009880{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009881 int kind1, kind2, kind;
9882 void *buf1, *buf2;
9883 Py_ssize_t len1, len2;
9884 PyObject* out;
9885
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009887 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009888
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009889 if (PyUnicode_READY(self) == -1)
9890 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009892 if (substring == NULL)
9893 switch(PyUnicode_KIND(self)) {
9894 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009895 if (PyUnicode_IS_ASCII(self))
9896 return asciilib_split_whitespace(
9897 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9898 PyUnicode_GET_LENGTH(self), maxcount
9899 );
9900 else
9901 return ucs1lib_split_whitespace(
9902 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9903 PyUnicode_GET_LENGTH(self), maxcount
9904 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 case PyUnicode_2BYTE_KIND:
9906 return ucs2lib_split_whitespace(
9907 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
9908 PyUnicode_GET_LENGTH(self), maxcount
9909 );
9910 case PyUnicode_4BYTE_KIND:
9911 return ucs4lib_split_whitespace(
9912 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
9913 PyUnicode_GET_LENGTH(self), maxcount
9914 );
9915 default:
9916 assert(0);
9917 return NULL;
9918 }
9919
9920 if (PyUnicode_READY(substring) == -1)
9921 return NULL;
9922
9923 kind1 = PyUnicode_KIND(self);
9924 kind2 = PyUnicode_KIND(substring);
9925 kind = kind1 > kind2 ? kind1 : kind2;
9926 buf1 = PyUnicode_DATA(self);
9927 buf2 = PyUnicode_DATA(substring);
9928 if (kind1 != kind)
9929 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
9930 if (!buf1)
9931 return NULL;
9932 if (kind2 != kind)
9933 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
9934 if (!buf2) {
9935 if (kind1 != kind) PyMem_Free(buf1);
9936 return NULL;
9937 }
9938 len1 = PyUnicode_GET_LENGTH(self);
9939 len2 = PyUnicode_GET_LENGTH(substring);
9940
9941 switch(kind) {
9942 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009943 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9944 out = asciilib_split(
9945 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9946 else
9947 out = ucs1lib_split(
9948 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009949 break;
9950 case PyUnicode_2BYTE_KIND:
9951 out = ucs2lib_split(
9952 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9953 break;
9954 case PyUnicode_4BYTE_KIND:
9955 out = ucs4lib_split(
9956 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
9957 break;
9958 default:
9959 out = NULL;
9960 }
9961 if (kind1 != kind)
9962 PyMem_Free(buf1);
9963 if (kind2 != kind)
9964 PyMem_Free(buf2);
9965 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009966}
9967
Alexander Belopolsky40018472011-02-26 01:02:56 +00009968static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009969rsplit(PyObject *self,
9970 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009971 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009972{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009973 int kind1, kind2, kind;
9974 void *buf1, *buf2;
9975 Py_ssize_t len1, len2;
9976 PyObject* out;
9977
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009978 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009979 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009980
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009981 if (PyUnicode_READY(self) == -1)
9982 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009984 if (substring == NULL)
9985 switch(PyUnicode_KIND(self)) {
9986 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009987 if (PyUnicode_IS_ASCII(self))
9988 return asciilib_rsplit_whitespace(
9989 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9990 PyUnicode_GET_LENGTH(self), maxcount
9991 );
9992 else
9993 return ucs1lib_rsplit_whitespace(
9994 (PyObject*) self, PyUnicode_1BYTE_DATA(self),
9995 PyUnicode_GET_LENGTH(self), maxcount
9996 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 case PyUnicode_2BYTE_KIND:
9998 return ucs2lib_rsplit_whitespace(
9999 (PyObject*) self, PyUnicode_2BYTE_DATA(self),
10000 PyUnicode_GET_LENGTH(self), maxcount
10001 );
10002 case PyUnicode_4BYTE_KIND:
10003 return ucs4lib_rsplit_whitespace(
10004 (PyObject*) self, PyUnicode_4BYTE_DATA(self),
10005 PyUnicode_GET_LENGTH(self), maxcount
10006 );
10007 default:
10008 assert(0);
10009 return NULL;
10010 }
10011
10012 if (PyUnicode_READY(substring) == -1)
10013 return NULL;
10014
10015 kind1 = PyUnicode_KIND(self);
10016 kind2 = PyUnicode_KIND(substring);
10017 kind = kind1 > kind2 ? kind1 : kind2;
10018 buf1 = PyUnicode_DATA(self);
10019 buf2 = PyUnicode_DATA(substring);
10020 if (kind1 != kind)
10021 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10022 if (!buf1)
10023 return NULL;
10024 if (kind2 != kind)
10025 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10026 if (!buf2) {
10027 if (kind1 != kind) PyMem_Free(buf1);
10028 return NULL;
10029 }
10030 len1 = PyUnicode_GET_LENGTH(self);
10031 len2 = PyUnicode_GET_LENGTH(substring);
10032
10033 switch(kind) {
10034 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010035 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10036 out = asciilib_rsplit(
10037 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10038 else
10039 out = ucs1lib_rsplit(
10040 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 break;
10042 case PyUnicode_2BYTE_KIND:
10043 out = ucs2lib_rsplit(
10044 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10045 break;
10046 case PyUnicode_4BYTE_KIND:
10047 out = ucs4lib_rsplit(
10048 (PyObject*) self, buf1, len1, buf2, len2, maxcount);
10049 break;
10050 default:
10051 out = NULL;
10052 }
10053 if (kind1 != kind)
10054 PyMem_Free(buf1);
10055 if (kind2 != kind)
10056 PyMem_Free(buf2);
10057 return out;
10058}
10059
10060static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010061anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10062 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063{
10064 switch(kind) {
10065 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010066 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10067 return asciilib_find(buf1, len1, buf2, len2, offset);
10068 else
10069 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 case PyUnicode_2BYTE_KIND:
10071 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10072 case PyUnicode_4BYTE_KIND:
10073 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10074 }
10075 assert(0);
10076 return -1;
10077}
10078
10079static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010080anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10081 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010082{
10083 switch(kind) {
10084 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010085 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10086 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10087 else
10088 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 case PyUnicode_2BYTE_KIND:
10090 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10091 case PyUnicode_4BYTE_KIND:
10092 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10093 }
10094 assert(0);
10095 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010096}
10097
Alexander Belopolsky40018472011-02-26 01:02:56 +000010098static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010099replace(PyObject *self, PyObject *str1,
10100 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010101{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010102 PyObject *u;
10103 char *sbuf = PyUnicode_DATA(self);
10104 char *buf1 = PyUnicode_DATA(str1);
10105 char *buf2 = PyUnicode_DATA(str2);
10106 int srelease = 0, release1 = 0, release2 = 0;
10107 int skind = PyUnicode_KIND(self);
10108 int kind1 = PyUnicode_KIND(str1);
10109 int kind2 = PyUnicode_KIND(str2);
10110 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10111 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10112 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010113 int mayshrink;
10114 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010115
10116 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010117 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010119 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010120
Victor Stinner59de0ee2011-10-07 10:01:28 +020010121 if (str1 == str2)
10122 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 if (skind < kind1)
10124 /* substring too wide to be present */
10125 goto nothing;
10126
Victor Stinner49a0a212011-10-12 23:46:10 +020010127 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10128 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10129 /* Replacing str1 with str2 may cause a maxchar reduction in the
10130 result string. */
10131 mayshrink = (maxchar_str2 < maxchar);
10132 maxchar = Py_MAX(maxchar, maxchar_str2);
10133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010135 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010136 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010138 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010139 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010140 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010141 Py_UCS4 u1, u2;
10142 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010143 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010144 if (findchar(sbuf, PyUnicode_KIND(self),
10145 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010146 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010148 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010149 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010150 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010151 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010152 rkind = PyUnicode_KIND(u);
10153 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10154 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010155 if (--maxcount < 0)
10156 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010158 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010159 }
10160 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010161 int rkind = skind;
10162 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010163
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010164 if (kind1 < rkind) {
10165 /* widen substring */
10166 buf1 = _PyUnicode_AsKind(str1, rkind);
10167 if (!buf1) goto error;
10168 release1 = 1;
10169 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010170 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010171 if (i < 0)
10172 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 if (rkind > kind2) {
10174 /* widen replacement */
10175 buf2 = _PyUnicode_AsKind(str2, rkind);
10176 if (!buf2) goto error;
10177 release2 = 1;
10178 }
10179 else if (rkind < kind2) {
10180 /* widen self and buf1 */
10181 rkind = kind2;
10182 if (release1) PyMem_Free(buf1);
10183 sbuf = _PyUnicode_AsKind(self, rkind);
10184 if (!sbuf) goto error;
10185 srelease = 1;
10186 buf1 = _PyUnicode_AsKind(str1, rkind);
10187 if (!buf1) goto error;
10188 release1 = 1;
10189 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010190 u = PyUnicode_New(slen, maxchar);
10191 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010193 assert(PyUnicode_KIND(u) == rkind);
10194 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010195
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010196 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010197 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010198 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010199 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010200 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010201 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010202
10203 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010204 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010205 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010206 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010207 if (i == -1)
10208 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010209 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010211 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010212 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010213 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010214 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010215 }
10216 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 Py_ssize_t n, i, j, ires;
10218 Py_ssize_t product, new_size;
10219 int rkind = skind;
10220 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010222 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010223 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010224 buf1 = _PyUnicode_AsKind(str1, rkind);
10225 if (!buf1) goto error;
10226 release1 = 1;
10227 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010228 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229 if (n == 0)
10230 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010231 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010232 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 buf2 = _PyUnicode_AsKind(str2, rkind);
10234 if (!buf2) goto error;
10235 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010236 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010238 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 rkind = kind2;
10240 sbuf = _PyUnicode_AsKind(self, rkind);
10241 if (!sbuf) goto error;
10242 srelease = 1;
10243 if (release1) PyMem_Free(buf1);
10244 buf1 = _PyUnicode_AsKind(str1, rkind);
10245 if (!buf1) goto error;
10246 release1 = 1;
10247 }
10248 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10249 PyUnicode_GET_LENGTH(str1))); */
10250 product = n * (len2-len1);
10251 if ((product / (len2-len1)) != n) {
10252 PyErr_SetString(PyExc_OverflowError,
10253 "replace string is too long");
10254 goto error;
10255 }
10256 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010257 if (new_size == 0) {
10258 Py_INCREF(unicode_empty);
10259 u = unicode_empty;
10260 goto done;
10261 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10263 PyErr_SetString(PyExc_OverflowError,
10264 "replace string is too long");
10265 goto error;
10266 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010267 u = PyUnicode_New(new_size, maxchar);
10268 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010269 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010270 assert(PyUnicode_KIND(u) == rkind);
10271 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010272 ires = i = 0;
10273 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010274 while (n-- > 0) {
10275 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010276 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010278 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010279 if (j == -1)
10280 break;
10281 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010283 memcpy(res + rkind * ires,
10284 sbuf + rkind * i,
10285 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010287 }
10288 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010289 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010290 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010291 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010292 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010293 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010294 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010295 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010296 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010297 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010298 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010299 memcpy(res + rkind * ires,
10300 sbuf + rkind * i,
10301 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010302 }
10303 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010304 /* interleave */
10305 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010306 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010307 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010308 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010310 if (--n <= 0)
10311 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010312 memcpy(res + rkind * ires,
10313 sbuf + rkind * i,
10314 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010315 ires++;
10316 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010317 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010318 memcpy(res + rkind * ires,
10319 sbuf + rkind * i,
10320 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010321 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010322 }
10323
10324 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010325 unicode_adjust_maxchar(&u);
10326 if (u == NULL)
10327 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010328 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010329
10330 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010331 if (srelease)
10332 PyMem_FREE(sbuf);
10333 if (release1)
10334 PyMem_FREE(buf1);
10335 if (release2)
10336 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010337 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010338 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010339
Benjamin Peterson29060642009-01-31 22:14:21 +000010340 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010341 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010342 if (srelease)
10343 PyMem_FREE(sbuf);
10344 if (release1)
10345 PyMem_FREE(buf1);
10346 if (release2)
10347 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010348 if (PyUnicode_CheckExact(self)) {
10349 Py_INCREF(self);
10350 return (PyObject *) self;
10351 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010352 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010353 error:
10354 if (srelease && sbuf)
10355 PyMem_FREE(sbuf);
10356 if (release1 && buf1)
10357 PyMem_FREE(buf1);
10358 if (release2 && buf2)
10359 PyMem_FREE(buf2);
10360 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010361}
10362
10363/* --- Unicode Object Methods --------------------------------------------- */
10364
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010365PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010366 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010367\n\
10368Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010369characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370
10371static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010372unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374 return fixup(self, fixtitle);
10375}
10376
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010377PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010378 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010379\n\
10380Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010381have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010382
10383static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010384unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010386 return fixup(self, fixcapitalize);
10387}
10388
10389#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010390PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010391 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392\n\
10393Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010394normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395
10396static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000010397unicode_capwords(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010398{
10399 PyObject *list;
10400 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010401 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010402
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403 /* Split into words */
10404 list = split(self, NULL, -1);
10405 if (!list)
10406 return NULL;
10407
10408 /* Capitalize each word */
10409 for (i = 0; i < PyList_GET_SIZE(list); i++) {
10410 item = fixup((PyUnicodeObject *)PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010411 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010412 if (item == NULL)
10413 goto onError;
10414 Py_DECREF(PyList_GET_ITEM(list, i));
10415 PyList_SET_ITEM(list, i, item);
10416 }
10417
10418 /* Join the words to form a new string */
10419 item = PyUnicode_Join(NULL, list);
10420
Benjamin Peterson29060642009-01-31 22:14:21 +000010421 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010422 Py_DECREF(list);
10423 return (PyObject *)item;
10424}
10425#endif
10426
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010427/* Argument converter. Coerces to a single unicode character */
10428
10429static int
10430convert_uc(PyObject *obj, void *addr)
10431{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010433 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010434
Benjamin Peterson14339b62009-01-31 16:36:08 +000010435 uniobj = PyUnicode_FromObject(obj);
10436 if (uniobj == NULL) {
10437 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010438 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010439 return 0;
10440 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010441 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010442 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010443 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010444 Py_DECREF(uniobj);
10445 return 0;
10446 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010448 Py_DECREF(uniobj);
10449 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010450}
10451
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010452PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010453 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010454\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010455Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010456done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010457
10458static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010459unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010460{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010461 Py_ssize_t marg, left;
10462 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010463 Py_UCS4 fillchar = ' ';
10464
Victor Stinnere9a29352011-10-01 02:14:59 +020010465 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010466 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010467
Victor Stinnere9a29352011-10-01 02:14:59 +020010468 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469 return NULL;
10470
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010471 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010472 Py_INCREF(self);
10473 return (PyObject*) self;
10474 }
10475
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010476 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010477 left = marg / 2 + (marg & width & 1);
10478
Victor Stinner9310abb2011-10-05 00:59:23 +020010479 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010480}
10481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010482/* This function assumes that str1 and str2 are readied by the caller. */
10483
Marc-André Lemburge5034372000-08-08 08:04:29 +000010484static int
10485unicode_compare(PyUnicodeObject *str1, PyUnicodeObject *str2)
10486{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010487 int kind1, kind2;
10488 void *data1, *data2;
10489 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010490
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 kind1 = PyUnicode_KIND(str1);
10492 kind2 = PyUnicode_KIND(str2);
10493 data1 = PyUnicode_DATA(str1);
10494 data2 = PyUnicode_DATA(str2);
10495 len1 = PyUnicode_GET_LENGTH(str1);
10496 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010497
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010498 for (i = 0; i < len1 && i < len2; ++i) {
10499 Py_UCS4 c1, c2;
10500 c1 = PyUnicode_READ(kind1, data1, i);
10501 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010502
10503 if (c1 != c2)
10504 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010505 }
10506
10507 return (len1 < len2) ? -1 : (len1 != len2);
10508}
10509
Alexander Belopolsky40018472011-02-26 01:02:56 +000010510int
10511PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010512{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010513 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10514 if (PyUnicode_READY(left) == -1 ||
10515 PyUnicode_READY(right) == -1)
10516 return -1;
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010517 return unicode_compare((PyUnicodeObject *)left,
10518 (PyUnicodeObject *)right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010519 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010520 PyErr_Format(PyExc_TypeError,
10521 "Can't compare %.100s and %.100s",
10522 left->ob_type->tp_name,
10523 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010524 return -1;
10525}
10526
Martin v. Löwis5b222132007-06-10 09:51:05 +000010527int
10528PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10529{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010530 Py_ssize_t i;
10531 int kind;
10532 void *data;
10533 Py_UCS4 chr;
10534
Victor Stinner910337b2011-10-03 03:20:16 +020010535 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010536 if (PyUnicode_READY(uni) == -1)
10537 return -1;
10538 kind = PyUnicode_KIND(uni);
10539 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010540 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010541 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10542 if (chr != str[i])
10543 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010544 /* This check keeps Python strings that end in '\0' from comparing equal
10545 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010546 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010547 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010548 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010549 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010550 return 0;
10551}
10552
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010553
Benjamin Peterson29060642009-01-31 22:14:21 +000010554#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010555 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010556
Alexander Belopolsky40018472011-02-26 01:02:56 +000010557PyObject *
10558PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010559{
10560 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010561
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010562 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10563 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010564 if (PyUnicode_READY(left) == -1 ||
10565 PyUnicode_READY(right) == -1)
10566 return NULL;
10567 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10568 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010569 if (op == Py_EQ) {
10570 Py_INCREF(Py_False);
10571 return Py_False;
10572 }
10573 if (op == Py_NE) {
10574 Py_INCREF(Py_True);
10575 return Py_True;
10576 }
10577 }
10578 if (left == right)
10579 result = 0;
10580 else
10581 result = unicode_compare((PyUnicodeObject *)left,
10582 (PyUnicodeObject *)right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010583
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010584 /* Convert the return value to a Boolean */
10585 switch (op) {
10586 case Py_EQ:
10587 v = TEST_COND(result == 0);
10588 break;
10589 case Py_NE:
10590 v = TEST_COND(result != 0);
10591 break;
10592 case Py_LE:
10593 v = TEST_COND(result <= 0);
10594 break;
10595 case Py_GE:
10596 v = TEST_COND(result >= 0);
10597 break;
10598 case Py_LT:
10599 v = TEST_COND(result == -1);
10600 break;
10601 case Py_GT:
10602 v = TEST_COND(result == 1);
10603 break;
10604 default:
10605 PyErr_BadArgument();
10606 return NULL;
10607 }
10608 Py_INCREF(v);
10609 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010610 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010611
Brian Curtindfc80e32011-08-10 20:28:54 -050010612 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010613}
10614
Alexander Belopolsky40018472011-02-26 01:02:56 +000010615int
10616PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010617{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010618 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010619 int kind1, kind2, kind;
10620 void *buf1, *buf2;
10621 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010622 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010623
10624 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010625 sub = PyUnicode_FromObject(element);
10626 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010627 PyErr_Format(PyExc_TypeError,
10628 "'in <string>' requires string as left operand, not %s",
10629 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010630 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010631 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 if (PyUnicode_READY(sub) == -1)
10633 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010634
Thomas Wouters477c8d52006-05-27 19:21:47 +000010635 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010636 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010637 Py_DECREF(sub);
10638 return -1;
10639 }
10640
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 kind1 = PyUnicode_KIND(str);
10642 kind2 = PyUnicode_KIND(sub);
10643 kind = kind1 > kind2 ? kind1 : kind2;
10644 buf1 = PyUnicode_DATA(str);
10645 buf2 = PyUnicode_DATA(sub);
10646 if (kind1 != kind)
10647 buf1 = _PyUnicode_AsKind((PyObject*)str, kind);
10648 if (!buf1) {
10649 Py_DECREF(sub);
10650 return -1;
10651 }
10652 if (kind2 != kind)
10653 buf2 = _PyUnicode_AsKind((PyObject*)sub, kind);
10654 if (!buf2) {
10655 Py_DECREF(sub);
10656 if (kind1 != kind) PyMem_Free(buf1);
10657 return -1;
10658 }
10659 len1 = PyUnicode_GET_LENGTH(str);
10660 len2 = PyUnicode_GET_LENGTH(sub);
10661
10662 switch(kind) {
10663 case PyUnicode_1BYTE_KIND:
10664 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10665 break;
10666 case PyUnicode_2BYTE_KIND:
10667 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10668 break;
10669 case PyUnicode_4BYTE_KIND:
10670 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10671 break;
10672 default:
10673 result = -1;
10674 assert(0);
10675 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010676
10677 Py_DECREF(str);
10678 Py_DECREF(sub);
10679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 if (kind1 != kind)
10681 PyMem_Free(buf1);
10682 if (kind2 != kind)
10683 PyMem_Free(buf2);
10684
Guido van Rossum403d68b2000-03-13 15:55:09 +000010685 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010686}
10687
Guido van Rossumd57fd912000-03-10 22:53:23 +000010688/* Concat to string or Unicode object giving a new Unicode object. */
10689
Alexander Belopolsky40018472011-02-26 01:02:56 +000010690PyObject *
10691PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010692{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010693 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010694 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010695
10696 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010697 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010698 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010699 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010700 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010702 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010703
10704 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010705 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010706 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010707 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010708 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010709 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010710 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010711 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010712 }
10713
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010714 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010715 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10716 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010717
Guido van Rossumd57fd912000-03-10 22:53:23 +000010718 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010719 w = PyUnicode_New(
10720 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10721 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010722 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010723 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010724 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10725 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010726 Py_DECREF(u);
10727 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010728 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010729 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010730
Benjamin Peterson29060642009-01-31 22:14:21 +000010731 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010732 Py_XDECREF(u);
10733 Py_XDECREF(v);
10734 return NULL;
10735}
10736
Victor Stinnerb0923652011-10-04 01:17:31 +020010737static void
10738unicode_append_inplace(PyObject **p_left, PyObject *right)
10739{
10740 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010741
10742 assert(PyUnicode_IS_READY(*p_left));
10743 assert(PyUnicode_IS_READY(right));
10744
10745 left_len = PyUnicode_GET_LENGTH(*p_left);
10746 right_len = PyUnicode_GET_LENGTH(right);
10747 if (left_len > PY_SSIZE_T_MAX - right_len) {
10748 PyErr_SetString(PyExc_OverflowError,
10749 "strings are too large to concat");
10750 goto error;
10751 }
10752 new_len = left_len + right_len;
10753
10754 /* Now we own the last reference to 'left', so we can resize it
10755 * in-place.
10756 */
10757 if (unicode_resize(p_left, new_len) != 0) {
10758 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10759 * deallocated so it cannot be put back into
10760 * 'variable'. The MemoryError is raised when there
10761 * is no value in 'variable', which might (very
10762 * remotely) be a cause of incompatibilities.
10763 */
10764 goto error;
10765 }
10766 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010767 copy_characters(*p_left, left_len, right, 0, right_len);
10768 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010769 return;
10770
10771error:
10772 Py_DECREF(*p_left);
10773 *p_left = NULL;
10774}
10775
Walter Dörwald1ab83302007-05-18 17:15:44 +000010776void
Victor Stinner23e56682011-10-03 03:54:37 +020010777PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010778{
Victor Stinner23e56682011-10-03 03:54:37 +020010779 PyObject *left, *res;
10780
10781 if (p_left == NULL) {
10782 if (!PyErr_Occurred())
10783 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010784 return;
10785 }
Victor Stinner23e56682011-10-03 03:54:37 +020010786 left = *p_left;
10787 if (right == NULL || !PyUnicode_Check(left)) {
10788 if (!PyErr_Occurred())
10789 PyErr_BadInternalCall();
10790 goto error;
10791 }
10792
Victor Stinnere1335c72011-10-04 20:53:03 +020010793 if (PyUnicode_READY(left))
10794 goto error;
10795 if (PyUnicode_READY(right))
10796 goto error;
10797
Victor Stinner23e56682011-10-03 03:54:37 +020010798 if (PyUnicode_CheckExact(left) && left != unicode_empty
10799 && PyUnicode_CheckExact(right) && right != unicode_empty
10800 && unicode_resizable(left)
10801 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10802 || _PyUnicode_WSTR(left) != NULL))
10803 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010804 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10805 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010806 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010807 not so different than duplicating the string. */
10808 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010809 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010810 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010811 if (p_left != NULL)
10812 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010813 return;
10814 }
10815 }
10816
10817 res = PyUnicode_Concat(left, right);
10818 if (res == NULL)
10819 goto error;
10820 Py_DECREF(left);
10821 *p_left = res;
10822 return;
10823
10824error:
10825 Py_DECREF(*p_left);
10826 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010827}
10828
10829void
10830PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10831{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010832 PyUnicode_Append(pleft, right);
10833 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010834}
10835
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010836PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010837 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010838\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010839Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010840string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010841interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842
10843static PyObject *
10844unicode_count(PyUnicodeObject *self, PyObject *args)
10845{
10846 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010847 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010848 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010849 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010850 int kind1, kind2, kind;
10851 void *buf1, *buf2;
10852 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853
Jesus Ceaac451502011-04-20 17:09:23 +020010854 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10855 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010856 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010857
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010858 kind1 = PyUnicode_KIND(self);
10859 kind2 = PyUnicode_KIND(substring);
10860 kind = kind1 > kind2 ? kind1 : kind2;
10861 buf1 = PyUnicode_DATA(self);
10862 buf2 = PyUnicode_DATA(substring);
10863 if (kind1 != kind)
10864 buf1 = _PyUnicode_AsKind((PyObject*)self, kind);
10865 if (!buf1) {
10866 Py_DECREF(substring);
10867 return NULL;
10868 }
10869 if (kind2 != kind)
10870 buf2 = _PyUnicode_AsKind((PyObject*)substring, kind);
10871 if (!buf2) {
10872 Py_DECREF(substring);
10873 if (kind1 != kind) PyMem_Free(buf1);
10874 return NULL;
10875 }
10876 len1 = PyUnicode_GET_LENGTH(self);
10877 len2 = PyUnicode_GET_LENGTH(substring);
10878
10879 ADJUST_INDICES(start, end, len1);
10880 switch(kind) {
10881 case PyUnicode_1BYTE_KIND:
10882 iresult = ucs1lib_count(
10883 ((Py_UCS1*)buf1) + start, end - start,
10884 buf2, len2, PY_SSIZE_T_MAX
10885 );
10886 break;
10887 case PyUnicode_2BYTE_KIND:
10888 iresult = ucs2lib_count(
10889 ((Py_UCS2*)buf1) + start, end - start,
10890 buf2, len2, PY_SSIZE_T_MAX
10891 );
10892 break;
10893 case PyUnicode_4BYTE_KIND:
10894 iresult = ucs4lib_count(
10895 ((Py_UCS4*)buf1) + start, end - start,
10896 buf2, len2, PY_SSIZE_T_MAX
10897 );
10898 break;
10899 default:
10900 assert(0); iresult = 0;
10901 }
10902
10903 result = PyLong_FromSsize_t(iresult);
10904
10905 if (kind1 != kind)
10906 PyMem_Free(buf1);
10907 if (kind2 != kind)
10908 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909
10910 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010911
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912 return result;
10913}
10914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010915PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010916 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010917\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010918Encode S using the codec registered for encoding. Default encoding\n\
10919is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010920handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010921a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10922'xmlcharrefreplace' as well as any other name registered with\n\
10923codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010924
10925static PyObject *
Benjamin Peterson308d6372009-09-18 21:42:35 +000010926unicode_encode(PyUnicodeObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010928 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010929 char *encoding = NULL;
10930 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010931
Benjamin Peterson308d6372009-09-18 21:42:35 +000010932 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10933 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010934 return NULL;
Georg Brandl3b9406b2010-12-03 07:54:09 +000010935 return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010936}
10937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010938PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010939 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010940\n\
10941Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010942If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010943
10944static PyObject*
10945unicode_expandtabs(PyUnicodeObject *self, PyObject *args)
10946{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010947 Py_ssize_t i, j, line_pos, src_len, incr;
10948 Py_UCS4 ch;
10949 PyObject *u;
10950 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010951 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010952 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010953 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954
10955 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010956 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957
Antoine Pitrou22425222011-10-04 19:10:51 +020010958 if (PyUnicode_READY(self) == -1)
10959 return NULL;
10960
Thomas Wouters7e474022000-07-16 12:04:32 +000010961 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010962 src_len = PyUnicode_GET_LENGTH(self);
10963 i = j = line_pos = 0;
10964 kind = PyUnicode_KIND(self);
10965 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010966 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010967 for (; i < src_len; i++) {
10968 ch = PyUnicode_READ(kind, src_data, i);
10969 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010970 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010971 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010972 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010973 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010974 goto overflow;
10975 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010976 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010977 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010978 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010979 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010980 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010981 goto overflow;
10982 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010983 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010984 if (ch == '\n' || ch == '\r')
10985 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010986 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010987 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010988 if (!found && PyUnicode_CheckExact(self)) {
10989 Py_INCREF((PyObject *) self);
10990 return (PyObject *) self;
10991 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010992
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010994 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010995 if (!u)
10996 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010997 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010998
Antoine Pitroue71d5742011-10-04 15:55:09 +020010999 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000
Antoine Pitroue71d5742011-10-04 15:55:09 +020011001 for (; i < src_len; i++) {
11002 ch = PyUnicode_READ(kind, src_data, i);
11003 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000011004 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011005 incr = tabsize - (line_pos % tabsize);
11006 line_pos += incr;
11007 while (incr--) {
11008 PyUnicode_WRITE(kind, dest_data, j, ' ');
11009 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011010 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011011 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011012 }
Benjamin Peterson29060642009-01-31 22:14:21 +000011013 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020011014 line_pos++;
11015 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011016 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020011017 if (ch == '\n' || ch == '\r')
11018 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011019 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020011020 }
11021 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020011022#ifndef DONT_MAKE_RESULT_READY
11023 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011024 Py_DECREF(u);
11025 return NULL;
11026 }
Victor Stinner17efeed2011-10-04 20:05:46 +020011027#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011028 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029 return (PyObject*) u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011030
Antoine Pitroue71d5742011-10-04 15:55:09 +020011031 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011032 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11033 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011034}
11035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011036PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011037 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038\n\
11039Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011040such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011041arguments start and end are interpreted as in slice notation.\n\
11042\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011043Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044
11045static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047{
Jesus Ceaac451502011-04-20 17:09:23 +020011048 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011049 Py_ssize_t start;
11050 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011051 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
Jesus Ceaac451502011-04-20 17:09:23 +020011053 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11054 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011056
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011057 if (PyUnicode_READY(self) == -1)
11058 return NULL;
11059 if (PyUnicode_READY(substring) == -1)
11060 return NULL;
11061
Victor Stinner794d5672011-10-10 03:21:36 +020011062 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011063 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011064 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011065
11066 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011067
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011068 if (result == -2)
11069 return NULL;
11070
Christian Heimes217cfd12007-12-02 14:31:20 +000011071 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011072}
11073
11074static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011075unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011077 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11078 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011079 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011080 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081}
11082
Guido van Rossumc2504932007-09-18 19:42:40 +000011083/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011084 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011085static Py_hash_t
Neil Schemenauerf8c37d12007-09-07 20:49:04 +000011086unicode_hash(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087{
Guido van Rossumc2504932007-09-18 19:42:40 +000011088 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011089 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 if (_PyUnicode_HASH(self) != -1)
11092 return _PyUnicode_HASH(self);
11093 if (PyUnicode_READY(self) == -1)
11094 return -1;
11095 len = PyUnicode_GET_LENGTH(self);
11096
11097 /* The hash function as a macro, gets expanded three times below. */
11098#define HASH(P) \
11099 x = (Py_uhash_t)*P << 7; \
11100 while (--len >= 0) \
11101 x = (1000003*x) ^ (Py_uhash_t)*P++;
11102
11103 switch (PyUnicode_KIND(self)) {
11104 case PyUnicode_1BYTE_KIND: {
11105 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11106 HASH(c);
11107 break;
11108 }
11109 case PyUnicode_2BYTE_KIND: {
11110 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11111 HASH(s);
11112 break;
11113 }
11114 default: {
11115 Py_UCS4 *l;
11116 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11117 "Impossible switch case in unicode_hash");
11118 l = PyUnicode_4BYTE_DATA(self);
11119 HASH(l);
11120 break;
11121 }
11122 }
11123 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11124
Guido van Rossumc2504932007-09-18 19:42:40 +000011125 if (x == -1)
11126 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011127 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011128 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011129}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011130#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011132PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011133 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011135Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011136
11137static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011138unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011139{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011140 Py_ssize_t result;
Jesus Ceaac451502011-04-20 17:09:23 +020011141 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011142 Py_ssize_t start;
11143 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144
Jesus Ceaac451502011-04-20 17:09:23 +020011145 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11146 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011147 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011148
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011149 if (PyUnicode_READY(self) == -1)
11150 return NULL;
11151 if (PyUnicode_READY(substring) == -1)
11152 return NULL;
11153
Victor Stinner794d5672011-10-10 03:21:36 +020011154 result = any_find_slice(1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011155 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000011156 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157
11158 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011160 if (result == -2)
11161 return NULL;
11162
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 if (result < 0) {
11164 PyErr_SetString(PyExc_ValueError, "substring not found");
11165 return NULL;
11166 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011167
Christian Heimes217cfd12007-12-02 14:31:20 +000011168 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169}
11170
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011171PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011172 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011174Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011175at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176
11177static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011178unicode_islower(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011180 Py_ssize_t i, length;
11181 int kind;
11182 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011183 int cased;
11184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011185 if (PyUnicode_READY(self) == -1)
11186 return NULL;
11187 length = PyUnicode_GET_LENGTH(self);
11188 kind = PyUnicode_KIND(self);
11189 data = PyUnicode_DATA(self);
11190
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011192 if (length == 1)
11193 return PyBool_FromLong(
11194 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011196 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011199
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011201 for (i = 0; i < length; i++) {
11202 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011203
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11205 return PyBool_FromLong(0);
11206 else if (!cased && Py_UNICODE_ISLOWER(ch))
11207 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011208 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011209 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210}
11211
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011212PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011213 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011215Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011216at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011217
11218static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011219unicode_isupper(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011221 Py_ssize_t i, length;
11222 int kind;
11223 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011224 int cased;
11225
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011226 if (PyUnicode_READY(self) == -1)
11227 return NULL;
11228 length = PyUnicode_GET_LENGTH(self);
11229 kind = PyUnicode_KIND(self);
11230 data = PyUnicode_DATA(self);
11231
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011233 if (length == 1)
11234 return PyBool_FromLong(
11235 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011236
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011237 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011238 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011239 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011240
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011242 for (i = 0; i < length; i++) {
11243 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011244
Benjamin Peterson29060642009-01-31 22:14:21 +000011245 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11246 return PyBool_FromLong(0);
11247 else if (!cased && Py_UNICODE_ISUPPER(ch))
11248 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011249 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011250 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251}
11252
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011253PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011256Return True if S is a titlecased string and there is at least one\n\
11257character in S, i.e. upper- and titlecase characters may only\n\
11258follow uncased characters and lowercase characters only cased ones.\n\
11259Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260
11261static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011262unicode_istitle(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011263{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011264 Py_ssize_t i, length;
11265 int kind;
11266 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267 int cased, previous_is_cased;
11268
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 if (PyUnicode_READY(self) == -1)
11270 return NULL;
11271 length = PyUnicode_GET_LENGTH(self);
11272 kind = PyUnicode_KIND(self);
11273 data = PyUnicode_DATA(self);
11274
Guido van Rossumd57fd912000-03-10 22:53:23 +000011275 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011276 if (length == 1) {
11277 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11278 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11279 (Py_UNICODE_ISUPPER(ch) != 0));
11280 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011282 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011284 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011285
Guido van Rossumd57fd912000-03-10 22:53:23 +000011286 cased = 0;
11287 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011288 for (i = 0; i < length; i++) {
11289 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011290
Benjamin Peterson29060642009-01-31 22:14:21 +000011291 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11292 if (previous_is_cased)
11293 return PyBool_FromLong(0);
11294 previous_is_cased = 1;
11295 cased = 1;
11296 }
11297 else if (Py_UNICODE_ISLOWER(ch)) {
11298 if (!previous_is_cased)
11299 return PyBool_FromLong(0);
11300 previous_is_cased = 1;
11301 cased = 1;
11302 }
11303 else
11304 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011305 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011306 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011307}
11308
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011309PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011310 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011311\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011312Return True if all characters in S are whitespace\n\
11313and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011314
11315static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011316unicode_isspace(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011317{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011318 Py_ssize_t i, length;
11319 int kind;
11320 void *data;
11321
11322 if (PyUnicode_READY(self) == -1)
11323 return NULL;
11324 length = PyUnicode_GET_LENGTH(self);
11325 kind = PyUnicode_KIND(self);
11326 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011327
Guido van Rossumd57fd912000-03-10 22:53:23 +000011328 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 if (length == 1)
11330 return PyBool_FromLong(
11331 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011332
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011333 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011334 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011335 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011336
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011337 for (i = 0; i < length; i++) {
11338 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011339 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011340 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011341 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011342 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011343}
11344
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011345PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011346 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011347\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011348Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011349and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011350
11351static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011352unicode_isalpha(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 Py_ssize_t i, length;
11355 int kind;
11356 void *data;
11357
11358 if (PyUnicode_READY(self) == -1)
11359 return NULL;
11360 length = PyUnicode_GET_LENGTH(self);
11361 kind = PyUnicode_KIND(self);
11362 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011363
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 if (length == 1)
11366 return PyBool_FromLong(
11367 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011368
11369 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011370 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011371 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011372
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011373 for (i = 0; i < length; i++) {
11374 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011375 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011376 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011377 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011378}
11379
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011380PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011381 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011382\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011383Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011384and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011385
11386static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011387unicode_isalnum(PyUnicodeObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011388{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011389 int kind;
11390 void *data;
11391 Py_ssize_t len, i;
11392
11393 if (PyUnicode_READY(self) == -1)
11394 return NULL;
11395
11396 kind = PyUnicode_KIND(self);
11397 data = PyUnicode_DATA(self);
11398 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011399
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011400 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 if (len == 1) {
11402 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11403 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11404 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011405
11406 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011407 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011408 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011409
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011410 for (i = 0; i < len; i++) {
11411 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011412 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011413 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011414 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011415 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011416}
11417
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011418PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011419 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011421Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011422False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423
11424static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011425unicode_isdecimal(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 Py_ssize_t i, length;
11428 int kind;
11429 void *data;
11430
11431 if (PyUnicode_READY(self) == -1)
11432 return NULL;
11433 length = PyUnicode_GET_LENGTH(self);
11434 kind = PyUnicode_KIND(self);
11435 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 if (length == 1)
11439 return PyBool_FromLong(
11440 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011441
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011442 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011443 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011444 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 for (i = 0; i < length; i++) {
11447 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011450 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011451}
11452
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011453PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011454 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011455\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011456Return True if all characters in S are digits\n\
11457and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011458
11459static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011460unicode_isdigit(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011461{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011462 Py_ssize_t i, length;
11463 int kind;
11464 void *data;
11465
11466 if (PyUnicode_READY(self) == -1)
11467 return NULL;
11468 length = PyUnicode_GET_LENGTH(self);
11469 kind = PyUnicode_KIND(self);
11470 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011471
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011473 if (length == 1) {
11474 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11475 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11476 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011478 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 for (i = 0; i < length; i++) {
11483 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011486 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487}
11488
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011489PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011490 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011491\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011492Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011493False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011494
11495static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011496unicode_isnumeric(PyUnicodeObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011497{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011498 Py_ssize_t i, length;
11499 int kind;
11500 void *data;
11501
11502 if (PyUnicode_READY(self) == -1)
11503 return NULL;
11504 length = PyUnicode_GET_LENGTH(self);
11505 kind = PyUnicode_KIND(self);
11506 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011507
Guido van Rossumd57fd912000-03-10 22:53:23 +000011508 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011509 if (length == 1)
11510 return PyBool_FromLong(
11511 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011512
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011513 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011514 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011515 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011517 for (i = 0; i < length; i++) {
11518 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011519 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011520 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011521 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011522}
11523
Martin v. Löwis47383402007-08-15 07:32:56 +000011524int
11525PyUnicode_IsIdentifier(PyObject *self)
11526{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011527 int kind;
11528 void *data;
11529 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011530 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011532 if (PyUnicode_READY(self) == -1) {
11533 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011534 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011535 }
11536
11537 /* Special case for empty strings */
11538 if (PyUnicode_GET_LENGTH(self) == 0)
11539 return 0;
11540 kind = PyUnicode_KIND(self);
11541 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011542
11543 /* PEP 3131 says that the first character must be in
11544 XID_Start and subsequent characters in XID_Continue,
11545 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011546 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011547 letters, digits, underscore). However, given the current
11548 definition of XID_Start and XID_Continue, it is sufficient
11549 to check just for these, except that _ must be allowed
11550 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011551 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011552 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011553 return 0;
11554
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011555 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011556 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011557 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011558 return 1;
11559}
11560
11561PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011562 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011563\n\
11564Return True if S is a valid identifier according\n\
11565to the language definition.");
11566
11567static PyObject*
11568unicode_isidentifier(PyObject *self)
11569{
11570 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11571}
11572
Georg Brandl559e5d72008-06-11 18:37:52 +000011573PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011574 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011575\n\
11576Return True if all characters in S are considered\n\
11577printable in repr() or S is empty, False otherwise.");
11578
11579static PyObject*
11580unicode_isprintable(PyObject *self)
11581{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011582 Py_ssize_t i, length;
11583 int kind;
11584 void *data;
11585
11586 if (PyUnicode_READY(self) == -1)
11587 return NULL;
11588 length = PyUnicode_GET_LENGTH(self);
11589 kind = PyUnicode_KIND(self);
11590 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011591
11592 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011593 if (length == 1)
11594 return PyBool_FromLong(
11595 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011596
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011597 for (i = 0; i < length; i++) {
11598 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011599 Py_RETURN_FALSE;
11600 }
11601 }
11602 Py_RETURN_TRUE;
11603}
11604
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011605PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011606 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011607\n\
11608Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011609iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
11611static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011612unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011614 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011615}
11616
Martin v. Löwis18e16552006-02-15 17:27:45 +000011617static Py_ssize_t
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618unicode_length(PyUnicodeObject *self)
11619{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (PyUnicode_READY(self) == -1)
11621 return -1;
11622 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623}
11624
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011625PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011626 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011627\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011628Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011629done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011630
11631static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011632unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011633{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011634 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011635 Py_UCS4 fillchar = ' ';
11636
11637 if (PyUnicode_READY(self) == -1)
11638 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011639
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011640 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011641 return NULL;
11642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011643 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011644 Py_INCREF(self);
11645 return (PyObject*) self;
11646 }
11647
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648 return (PyObject*) pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011649}
11650
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011651PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011652 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011653\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011654Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011655
11656static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011657unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011658{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011659 return fixup(self, fixlower);
11660}
11661
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011662#define LEFTSTRIP 0
11663#define RIGHTSTRIP 1
11664#define BOTHSTRIP 2
11665
11666/* Arrays indexed by above */
11667static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11668
11669#define STRIPNAME(i) (stripformat[i]+3)
11670
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011671/* externally visible for str.strip(unicode) */
11672PyObject *
11673_PyUnicode_XStrip(PyUnicodeObject *self, int striptype, PyObject *sepobj)
11674{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675 void *data;
11676 int kind;
11677 Py_ssize_t i, j, len;
11678 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011680 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11681 return NULL;
11682
11683 kind = PyUnicode_KIND(self);
11684 data = PyUnicode_DATA(self);
11685 len = PyUnicode_GET_LENGTH(self);
11686 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11687 PyUnicode_DATA(sepobj),
11688 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011689
Benjamin Peterson14339b62009-01-31 16:36:08 +000011690 i = 0;
11691 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011692 while (i < len &&
11693 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011694 i++;
11695 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011696 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011697
Benjamin Peterson14339b62009-01-31 16:36:08 +000011698 j = len;
11699 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011700 do {
11701 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011702 } while (j >= i &&
11703 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011704 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011705 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011706
Victor Stinner12bab6d2011-10-01 01:53:49 +020011707 return PyUnicode_Substring((PyObject*)self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708}
11709
11710PyObject*
11711PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11712{
11713 unsigned char *data;
11714 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011715 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011716
Victor Stinnerde636f32011-10-01 03:55:54 +020011717 if (PyUnicode_READY(self) == -1)
11718 return NULL;
11719
11720 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11721
Victor Stinner12bab6d2011-10-01 01:53:49 +020011722 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011724 if (PyUnicode_CheckExact(self)) {
11725 Py_INCREF(self);
11726 return self;
11727 }
11728 else
11729 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011730 }
11731
Victor Stinner12bab6d2011-10-01 01:53:49 +020011732 length = end - start;
11733 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011734 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735
Victor Stinnerde636f32011-10-01 03:55:54 +020011736 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011737 PyErr_SetString(PyExc_IndexError, "string index out of range");
11738 return NULL;
11739 }
11740
Victor Stinnerb9275c12011-10-05 14:01:42 +020011741 if (PyUnicode_IS_ASCII(self)) {
11742 kind = PyUnicode_KIND(self);
11743 data = PyUnicode_1BYTE_DATA(self);
11744 return unicode_fromascii(data + start, length);
11745 }
11746 else {
11747 kind = PyUnicode_KIND(self);
11748 data = PyUnicode_1BYTE_DATA(self);
11749 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011750 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011751 length);
11752 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011753}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011754
11755static PyObject *
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011756do_strip(PyUnicodeObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011757{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011758 int kind;
11759 void *data;
11760 Py_ssize_t len, i, j;
11761
11762 if (PyUnicode_READY(self) == -1)
11763 return NULL;
11764
11765 kind = PyUnicode_KIND(self);
11766 data = PyUnicode_DATA(self);
11767 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768
Benjamin Peterson14339b62009-01-31 16:36:08 +000011769 i = 0;
11770 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011771 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011772 i++;
11773 }
11774 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775
Benjamin Peterson14339b62009-01-31 16:36:08 +000011776 j = len;
11777 if (striptype != LEFTSTRIP) {
11778 do {
11779 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011780 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011781 j++;
11782 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011783
Victor Stinner12bab6d2011-10-01 01:53:49 +020011784 return PyUnicode_Substring((PyObject*)self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011785}
11786
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011787
11788static PyObject *
11789do_argstrip(PyUnicodeObject *self, int striptype, PyObject *args)
11790{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011791 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792
Benjamin Peterson14339b62009-01-31 16:36:08 +000011793 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11794 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795
Benjamin Peterson14339b62009-01-31 16:36:08 +000011796 if (sep != NULL && sep != Py_None) {
11797 if (PyUnicode_Check(sep))
11798 return _PyUnicode_XStrip(self, striptype, sep);
11799 else {
11800 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011801 "%s arg must be None or str",
11802 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011803 return NULL;
11804 }
11805 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011806
Benjamin Peterson14339b62009-01-31 16:36:08 +000011807 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011808}
11809
11810
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011811PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011812 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011813\n\
11814Return a copy of the string S with leading and trailing\n\
11815whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011816If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011817
11818static PyObject *
11819unicode_strip(PyUnicodeObject *self, PyObject *args)
11820{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011821 if (PyTuple_GET_SIZE(args) == 0)
11822 return do_strip(self, BOTHSTRIP); /* Common case */
11823 else
11824 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011825}
11826
11827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011828PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011829 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011830\n\
11831Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011832If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011833
11834static PyObject *
11835unicode_lstrip(PyUnicodeObject *self, PyObject *args)
11836{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011837 if (PyTuple_GET_SIZE(args) == 0)
11838 return do_strip(self, LEFTSTRIP); /* Common case */
11839 else
11840 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011841}
11842
11843
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011844PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011845 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011846\n\
11847Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011848If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011849
11850static PyObject *
11851unicode_rstrip(PyUnicodeObject *self, PyObject *args)
11852{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011853 if (PyTuple_GET_SIZE(args) == 0)
11854 return do_strip(self, RIGHTSTRIP); /* Common case */
11855 else
11856 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011857}
11858
11859
Guido van Rossumd57fd912000-03-10 22:53:23 +000011860static PyObject*
Martin v. Löwis18e16552006-02-15 17:27:45 +000011861unicode_repeat(PyUnicodeObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011862{
11863 PyUnicodeObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011864 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011865
Georg Brandl222de0f2009-04-12 12:01:50 +000011866 if (len < 1) {
11867 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011868 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011869 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870
Tim Peters7a29bd52001-09-12 03:03:31 +000011871 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011872 /* no repeat, return original string */
11873 Py_INCREF(str);
11874 return (PyObject*) str;
11875 }
Tim Peters8f422462000-09-09 06:13:41 +000011876
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 if (PyUnicode_READY(str) == -1)
11878 return NULL;
11879
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011880 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011881 PyErr_SetString(PyExc_OverflowError,
11882 "repeated string is too long");
11883 return NULL;
11884 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011885 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011886
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011887 u = (PyUnicodeObject *)PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011888 if (!u)
11889 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011890 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011892 if (PyUnicode_GET_LENGTH(str) == 1) {
11893 const int kind = PyUnicode_KIND(str);
11894 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11895 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011896 if (kind == PyUnicode_1BYTE_KIND)
11897 memset(to, (unsigned char)fill_char, len);
11898 else {
11899 for (n = 0; n < len; ++n)
11900 PyUnicode_WRITE(kind, to, n, fill_char);
11901 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011902 }
11903 else {
11904 /* number of characters copied this far */
11905 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011906 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011907 char *to = (char *) PyUnicode_DATA(u);
11908 Py_MEMCPY(to, PyUnicode_DATA(str),
11909 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011910 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 n = (done <= nchars-done) ? done : nchars-done;
11912 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011913 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011914 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011915 }
11916
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011917 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011918 return (PyObject*) u;
11919}
11920
Alexander Belopolsky40018472011-02-26 01:02:56 +000011921PyObject *
11922PyUnicode_Replace(PyObject *obj,
11923 PyObject *subobj,
11924 PyObject *replobj,
11925 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011926{
11927 PyObject *self;
11928 PyObject *str1;
11929 PyObject *str2;
11930 PyObject *result;
11931
11932 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011933 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011934 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011936 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011937 Py_DECREF(self);
11938 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011939 }
11940 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011941 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011942 Py_DECREF(self);
11943 Py_DECREF(str1);
11944 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011946 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011947 Py_DECREF(self);
11948 Py_DECREF(str1);
11949 Py_DECREF(str2);
11950 return result;
11951}
11952
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011953PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011954 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955\n\
11956Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011957old replaced by new. If the optional argument count is\n\
11958given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011959
11960static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011961unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011962{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 PyObject *str1;
11964 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011965 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011966 PyObject *result;
11967
Martin v. Löwis18e16552006-02-15 17:27:45 +000011968 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011969 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011970 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011971 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011972 str1 = PyUnicode_FromObject(str1);
11973 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11974 return NULL;
11975 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011976 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011977 Py_DECREF(str1);
11978 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011979 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011980
11981 result = replace(self, str1, str2, maxcount);
11982
11983 Py_DECREF(str1);
11984 Py_DECREF(str2);
11985 return result;
11986}
11987
Alexander Belopolsky40018472011-02-26 01:02:56 +000011988static PyObject *
11989unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011990{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011991 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011992 Py_ssize_t isize;
11993 Py_ssize_t osize, squote, dquote, i, o;
11994 Py_UCS4 max, quote;
11995 int ikind, okind;
11996 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011997
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011998 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011999 return NULL;
12000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012001 isize = PyUnicode_GET_LENGTH(unicode);
12002 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012003
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012004 /* Compute length of output, quote characters, and
12005 maximum character */
12006 osize = 2; /* quotes */
12007 max = 127;
12008 squote = dquote = 0;
12009 ikind = PyUnicode_KIND(unicode);
12010 for (i = 0; i < isize; i++) {
12011 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
12012 switch (ch) {
12013 case '\'': squote++; osize++; break;
12014 case '"': dquote++; osize++; break;
12015 case '\\': case '\t': case '\r': case '\n':
12016 osize += 2; break;
12017 default:
12018 /* Fast-path ASCII */
12019 if (ch < ' ' || ch == 0x7f)
12020 osize += 4; /* \xHH */
12021 else if (ch < 0x7f)
12022 osize++;
12023 else if (Py_UNICODE_ISPRINTABLE(ch)) {
12024 osize++;
12025 max = ch > max ? ch : max;
12026 }
12027 else if (ch < 0x100)
12028 osize += 4; /* \xHH */
12029 else if (ch < 0x10000)
12030 osize += 6; /* \uHHHH */
12031 else
12032 osize += 10; /* \uHHHHHHHH */
12033 }
12034 }
12035
12036 quote = '\'';
12037 if (squote) {
12038 if (dquote)
12039 /* Both squote and dquote present. Use squote,
12040 and escape them */
12041 osize += squote;
12042 else
12043 quote = '"';
12044 }
12045
12046 repr = PyUnicode_New(osize, max);
12047 if (repr == NULL)
12048 return NULL;
12049 okind = PyUnicode_KIND(repr);
12050 odata = PyUnicode_DATA(repr);
12051
12052 PyUnicode_WRITE(okind, odata, 0, quote);
12053 PyUnicode_WRITE(okind, odata, osize-1, quote);
12054
12055 for (i = 0, o = 1; i < isize; i++) {
12056 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012057
12058 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012059 if ((ch == quote) || (ch == '\\')) {
12060 PyUnicode_WRITE(okind, odata, o++, '\\');
12061 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012062 continue;
12063 }
12064
Benjamin Peterson29060642009-01-31 22:14:21 +000012065 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012066 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012067 PyUnicode_WRITE(okind, odata, o++, '\\');
12068 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012069 }
12070 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012071 PyUnicode_WRITE(okind, odata, o++, '\\');
12072 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012073 }
12074 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 PyUnicode_WRITE(okind, odata, o++, '\\');
12076 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012077 }
12078
12079 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012080 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012081 PyUnicode_WRITE(okind, odata, o++, '\\');
12082 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012083 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12084 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012085 }
12086
Georg Brandl559e5d72008-06-11 18:37:52 +000012087 /* Copy ASCII characters as-is */
12088 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012090 }
12091
Benjamin Peterson29060642009-01-31 22:14:21 +000012092 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012093 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012094 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012095 (categories Z* and C* except ASCII space)
12096 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012097 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012098 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 if (ch <= 0xff) {
12100 PyUnicode_WRITE(okind, odata, o++, '\\');
12101 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012102 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12103 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012104 }
12105 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012106 else if (ch >= 0x10000) {
12107 PyUnicode_WRITE(okind, odata, o++, '\\');
12108 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012109 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12110 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12111 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12112 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12113 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12114 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12115 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12116 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012117 }
12118 /* Map 16-bit characters to '\uxxxx' */
12119 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012120 PyUnicode_WRITE(okind, odata, o++, '\\');
12121 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012122 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12123 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12124 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12125 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012126 }
12127 }
12128 /* Copy characters as-is */
12129 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012130 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012131 }
12132 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012133 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012135 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012136 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137}
12138
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012139PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012140 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012141\n\
12142Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012143such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144arguments start and end are interpreted as in slice notation.\n\
12145\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012146Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147
12148static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012149unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150{
Jesus Ceaac451502011-04-20 17:09:23 +020012151 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012152 Py_ssize_t start;
12153 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012154 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012155
Jesus Ceaac451502011-04-20 17:09:23 +020012156 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12157 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012158 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012160 if (PyUnicode_READY(self) == -1)
12161 return NULL;
12162 if (PyUnicode_READY(substring) == -1)
12163 return NULL;
12164
Victor Stinner794d5672011-10-10 03:21:36 +020012165 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012167 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168
12169 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012170
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012171 if (result == -2)
12172 return NULL;
12173
Christian Heimes217cfd12007-12-02 14:31:20 +000012174 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175}
12176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012177PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012178 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012180Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012181
12182static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012183unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012184{
Jesus Ceaac451502011-04-20 17:09:23 +020012185 PyUnicodeObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012186 Py_ssize_t start;
12187 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012188 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189
Jesus Ceaac451502011-04-20 17:09:23 +020012190 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12191 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012192 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012194 if (PyUnicode_READY(self) == -1)
12195 return NULL;
12196 if (PyUnicode_READY(substring) == -1)
12197 return NULL;
12198
Victor Stinner794d5672011-10-10 03:21:36 +020012199 result = any_find_slice(-1,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012200 self, (PyObject*)substring, start, end
Thomas Wouters477c8d52006-05-27 19:21:47 +000012201 );
Guido van Rossumd57fd912000-03-10 22:53:23 +000012202
12203 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012205 if (result == -2)
12206 return NULL;
12207
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208 if (result < 0) {
12209 PyErr_SetString(PyExc_ValueError, "substring not found");
12210 return NULL;
12211 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012212
Christian Heimes217cfd12007-12-02 14:31:20 +000012213 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012214}
12215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012216PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012217 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012219Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012220done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221
12222static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012223unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012225 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 Py_UCS4 fillchar = ' ';
12227
Victor Stinnere9a29352011-10-01 02:14:59 +020012228 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012229 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012230
Victor Stinnere9a29352011-10-01 02:14:59 +020012231 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 return NULL;
12233
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012234 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012235 Py_INCREF(self);
12236 return (PyObject*) self;
12237 }
12238
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012239 return (PyObject*) pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240}
12241
Alexander Belopolsky40018472011-02-26 01:02:56 +000012242PyObject *
12243PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012244{
12245 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012246
Guido van Rossumd57fd912000-03-10 22:53:23 +000012247 s = PyUnicode_FromObject(s);
12248 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012249 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012250 if (sep != NULL) {
12251 sep = PyUnicode_FromObject(sep);
12252 if (sep == NULL) {
12253 Py_DECREF(s);
12254 return NULL;
12255 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012256 }
12257
Victor Stinner9310abb2011-10-05 00:59:23 +020012258 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012259
12260 Py_DECREF(s);
12261 Py_XDECREF(sep);
12262 return result;
12263}
12264
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012265PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012266 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012267\n\
12268Return a list of the words in S, using sep as the\n\
12269delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012270splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012271whitespace string is a separator and empty strings are\n\
12272removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012273
12274static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012275unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012276{
12277 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012278 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012279
Martin v. Löwis18e16552006-02-15 17:27:45 +000012280 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012281 return NULL;
12282
12283 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012284 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012285 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012286 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012287 else
Benjamin Peterson29060642009-01-31 22:14:21 +000012288 return PyUnicode_Split((PyObject *)self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012289}
12290
Thomas Wouters477c8d52006-05-27 19:21:47 +000012291PyObject *
12292PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12293{
12294 PyObject* str_obj;
12295 PyObject* sep_obj;
12296 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 int kind1, kind2, kind;
12298 void *buf1 = NULL, *buf2 = NULL;
12299 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012300
12301 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012302 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012303 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012304 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012306 Py_DECREF(str_obj);
12307 return NULL;
12308 }
12309
Victor Stinner14f8f022011-10-05 20:58:25 +020012310 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012311 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012312 kind = Py_MAX(kind1, kind2);
12313 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012315 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012316 if (!buf1)
12317 goto onError;
12318 buf2 = PyUnicode_DATA(sep_obj);
12319 if (kind2 != kind)
12320 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12321 if (!buf2)
12322 goto onError;
12323 len1 = PyUnicode_GET_LENGTH(str_obj);
12324 len2 = PyUnicode_GET_LENGTH(sep_obj);
12325
Victor Stinner14f8f022011-10-05 20:58:25 +020012326 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012327 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012328 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12329 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12330 else
12331 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012332 break;
12333 case PyUnicode_2BYTE_KIND:
12334 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12335 break;
12336 case PyUnicode_4BYTE_KIND:
12337 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12338 break;
12339 default:
12340 assert(0);
12341 out = 0;
12342 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012343
12344 Py_DECREF(sep_obj);
12345 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 if (kind1 != kind)
12347 PyMem_Free(buf1);
12348 if (kind2 != kind)
12349 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012350
12351 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012352 onError:
12353 Py_DECREF(sep_obj);
12354 Py_DECREF(str_obj);
12355 if (kind1 != kind && buf1)
12356 PyMem_Free(buf1);
12357 if (kind2 != kind && buf2)
12358 PyMem_Free(buf2);
12359 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012360}
12361
12362
12363PyObject *
12364PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12365{
12366 PyObject* str_obj;
12367 PyObject* sep_obj;
12368 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 int kind1, kind2, kind;
12370 void *buf1 = NULL, *buf2 = NULL;
12371 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372
12373 str_obj = PyUnicode_FromObject(str_in);
12374 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012375 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376 sep_obj = PyUnicode_FromObject(sep_in);
12377 if (!sep_obj) {
12378 Py_DECREF(str_obj);
12379 return NULL;
12380 }
12381
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012382 kind1 = PyUnicode_KIND(str_in);
12383 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012384 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 buf1 = PyUnicode_DATA(str_in);
12386 if (kind1 != kind)
12387 buf1 = _PyUnicode_AsKind(str_in, kind);
12388 if (!buf1)
12389 goto onError;
12390 buf2 = PyUnicode_DATA(sep_obj);
12391 if (kind2 != kind)
12392 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12393 if (!buf2)
12394 goto onError;
12395 len1 = PyUnicode_GET_LENGTH(str_obj);
12396 len2 = PyUnicode_GET_LENGTH(sep_obj);
12397
12398 switch(PyUnicode_KIND(str_in)) {
12399 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012400 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12401 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12402 else
12403 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012404 break;
12405 case PyUnicode_2BYTE_KIND:
12406 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12407 break;
12408 case PyUnicode_4BYTE_KIND:
12409 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12410 break;
12411 default:
12412 assert(0);
12413 out = 0;
12414 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012415
12416 Py_DECREF(sep_obj);
12417 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012418 if (kind1 != kind)
12419 PyMem_Free(buf1);
12420 if (kind2 != kind)
12421 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012422
12423 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012424 onError:
12425 Py_DECREF(sep_obj);
12426 Py_DECREF(str_obj);
12427 if (kind1 != kind && buf1)
12428 PyMem_Free(buf1);
12429 if (kind2 != kind && buf2)
12430 PyMem_Free(buf2);
12431 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012432}
12433
12434PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012435 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012436\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012437Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012438the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012439found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012440
12441static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012442unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012443{
Victor Stinner9310abb2011-10-05 00:59:23 +020012444 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012445}
12446
12447PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012448 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012449\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012450Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012451the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012452separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012453
12454static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012455unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012456{
Victor Stinner9310abb2011-10-05 00:59:23 +020012457 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012458}
12459
Alexander Belopolsky40018472011-02-26 01:02:56 +000012460PyObject *
12461PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012462{
12463 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012464
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012465 s = PyUnicode_FromObject(s);
12466 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012467 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012468 if (sep != NULL) {
12469 sep = PyUnicode_FromObject(sep);
12470 if (sep == NULL) {
12471 Py_DECREF(s);
12472 return NULL;
12473 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012474 }
12475
Victor Stinner9310abb2011-10-05 00:59:23 +020012476 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012477
12478 Py_DECREF(s);
12479 Py_XDECREF(sep);
12480 return result;
12481}
12482
12483PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012484 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012485\n\
12486Return a list of the words in S, using sep as the\n\
12487delimiter string, starting at the end of the string and\n\
12488working to the front. If maxsplit is given, at most maxsplit\n\
12489splits are done. If sep is not specified, any whitespace string\n\
12490is a separator.");
12491
12492static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012493unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012494{
12495 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012496 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012497
Martin v. Löwis18e16552006-02-15 17:27:45 +000012498 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012499 return NULL;
12500
12501 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012502 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012503 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012504 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012505 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012506 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012507}
12508
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012509PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012510 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012511\n\
12512Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012513Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012514is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012515
12516static PyObject*
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012517unicode_splitlines(PyUnicodeObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012518{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012519 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012520 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012521
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012522 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12523 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012524 return NULL;
12525
Guido van Rossum86662912000-04-11 15:38:46 +000012526 return PyUnicode_Splitlines((PyObject *)self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012527}
12528
12529static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012530PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012531{
Walter Dörwald346737f2007-05-31 10:44:43 +000012532 if (PyUnicode_CheckExact(self)) {
12533 Py_INCREF(self);
12534 return self;
12535 } else
12536 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012537 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012538}
12539
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012540PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012541 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012542\n\
12543Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012544and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012545
12546static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012547unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012548{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012549 return fixup(self, fixswapcase);
12550}
12551
Georg Brandlceee0772007-11-27 23:48:05 +000012552PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012553 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012554\n\
12555Return a translation table usable for str.translate().\n\
12556If there is only one argument, it must be a dictionary mapping Unicode\n\
12557ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012558Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012559If there are two arguments, they must be strings of equal length, and\n\
12560in the resulting dictionary, each character in x will be mapped to the\n\
12561character at the same position in y. If there is a third argument, it\n\
12562must be a string, whose characters will be mapped to None in the result.");
12563
12564static PyObject*
12565unicode_maketrans(PyUnicodeObject *null, PyObject *args)
12566{
12567 PyObject *x, *y = NULL, *z = NULL;
12568 PyObject *new = NULL, *key, *value;
12569 Py_ssize_t i = 0;
12570 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012571
Georg Brandlceee0772007-11-27 23:48:05 +000012572 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12573 return NULL;
12574 new = PyDict_New();
12575 if (!new)
12576 return NULL;
12577 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 int x_kind, y_kind, z_kind;
12579 void *x_data, *y_data, *z_data;
12580
Georg Brandlceee0772007-11-27 23:48:05 +000012581 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012582 if (!PyUnicode_Check(x)) {
12583 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12584 "be a string if there is a second argument");
12585 goto err;
12586 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012587 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012588 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12589 "arguments must have equal length");
12590 goto err;
12591 }
12592 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 x_kind = PyUnicode_KIND(x);
12594 y_kind = PyUnicode_KIND(y);
12595 x_data = PyUnicode_DATA(x);
12596 y_data = PyUnicode_DATA(y);
12597 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12598 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12599 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012600 if (!key || !value)
12601 goto err;
12602 res = PyDict_SetItem(new, key, value);
12603 Py_DECREF(key);
12604 Py_DECREF(value);
12605 if (res < 0)
12606 goto err;
12607 }
12608 /* create entries for deleting chars in z */
12609 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012610 z_kind = PyUnicode_KIND(z);
12611 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012612 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012613 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012614 if (!key)
12615 goto err;
12616 res = PyDict_SetItem(new, key, Py_None);
12617 Py_DECREF(key);
12618 if (res < 0)
12619 goto err;
12620 }
12621 }
12622 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012623 int kind;
12624 void *data;
12625
Georg Brandlceee0772007-11-27 23:48:05 +000012626 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012627 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012628 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12629 "to maketrans it must be a dict");
12630 goto err;
12631 }
12632 /* copy entries into the new dict, converting string keys to int keys */
12633 while (PyDict_Next(x, &i, &key, &value)) {
12634 if (PyUnicode_Check(key)) {
12635 /* convert string keys to integer keys */
12636 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012637 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012638 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12639 "table must be of length 1");
12640 goto err;
12641 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642 kind = PyUnicode_KIND(key);
12643 data = PyUnicode_DATA(key);
12644 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012645 if (!newkey)
12646 goto err;
12647 res = PyDict_SetItem(new, newkey, value);
12648 Py_DECREF(newkey);
12649 if (res < 0)
12650 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012651 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012652 /* just keep integer keys */
12653 if (PyDict_SetItem(new, key, value) < 0)
12654 goto err;
12655 } else {
12656 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12657 "be strings or integers");
12658 goto err;
12659 }
12660 }
12661 }
12662 return new;
12663 err:
12664 Py_DECREF(new);
12665 return NULL;
12666}
12667
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012668PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012669 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012670\n\
12671Return a copy of the string S, where all characters have been mapped\n\
12672through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012673Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012674Unmapped characters are left untouched. Characters mapped to None\n\
12675are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676
12677static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012678unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012679{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012680 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681}
12682
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012683PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012684 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012685\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012686Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687
12688static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012689unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012690{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691 return fixup(self, fixupper);
12692}
12693
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012694PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012695 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012697Pad a numeric string S with zeros on the left, to fill a field\n\
12698of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012699
12700static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012701unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012702{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012703 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012704 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012705 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012706 int kind;
12707 void *data;
12708 Py_UCS4 chr;
12709
12710 if (PyUnicode_READY(self) == -1)
12711 return NULL;
12712
Martin v. Löwis18e16552006-02-15 17:27:45 +000012713 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714 return NULL;
12715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012716 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012717 if (PyUnicode_CheckExact(self)) {
12718 Py_INCREF(self);
12719 return (PyObject*) self;
12720 }
12721 else
Victor Stinner2219e0a2011-10-01 01:16:59 +020012722 return PyUnicode_Copy((PyObject*)self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723 }
12724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012725 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726
12727 u = pad(self, fill, 0, '0');
12728
Walter Dörwald068325e2002-04-15 13:36:47 +000012729 if (u == NULL)
12730 return NULL;
12731
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012732 kind = PyUnicode_KIND(u);
12733 data = PyUnicode_DATA(u);
12734 chr = PyUnicode_READ(kind, data, fill);
12735
12736 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012737 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012738 PyUnicode_WRITE(kind, data, 0, chr);
12739 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740 }
12741
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012742 assert(_PyUnicode_CheckConsistency(u, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +000012743 return (PyObject*) u;
12744}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
12746#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012747static PyObject *
12748unicode__decimal2ascii(PyObject *self)
12749{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012750 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012751}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012752#endif
12753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012754PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012755 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012756\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012757Return True if S starts with the specified prefix, False otherwise.\n\
12758With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012759With optional end, stop comparing S at that position.\n\
12760prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012761
12762static PyObject *
12763unicode_startswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012765{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012766 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012767 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012768 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012769 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012770 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012771
Jesus Ceaac451502011-04-20 17:09:23 +020012772 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012774 if (PyTuple_Check(subobj)) {
12775 Py_ssize_t i;
12776 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12777 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012779 if (substring == NULL)
12780 return NULL;
12781 result = tailmatch(self, substring, start, end, -1);
12782 Py_DECREF(substring);
12783 if (result) {
12784 Py_RETURN_TRUE;
12785 }
12786 }
12787 /* nothing matched */
12788 Py_RETURN_FALSE;
12789 }
12790 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012791 if (substring == NULL) {
12792 if (PyErr_ExceptionMatches(PyExc_TypeError))
12793 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12794 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012795 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012796 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012797 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012799 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012800}
12801
12802
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012803PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012804 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012805\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012806Return True if S ends with the specified suffix, False otherwise.\n\
12807With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012808With optional end, stop comparing S at that position.\n\
12809suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012810
12811static PyObject *
12812unicode_endswith(PyUnicodeObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012813 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012814{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012815 PyObject *subobj;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012816 PyUnicodeObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012817 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012818 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012819 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012820
Jesus Ceaac451502011-04-20 17:09:23 +020012821 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012823 if (PyTuple_Check(subobj)) {
12824 Py_ssize_t i;
12825 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
12826 substring = (PyUnicodeObject *)PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012827 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012828 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012829 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012830 result = tailmatch(self, substring, start, end, +1);
12831 Py_DECREF(substring);
12832 if (result) {
12833 Py_RETURN_TRUE;
12834 }
12835 }
12836 Py_RETURN_FALSE;
12837 }
12838 substring = (PyUnicodeObject *)PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012839 if (substring == NULL) {
12840 if (PyErr_ExceptionMatches(PyExc_TypeError))
12841 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12842 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012843 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012844 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012845 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012846 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012847 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012848}
12849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012850#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012851
12852PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012853 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012854\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012855Return a formatted version of S, using substitutions from args and kwargs.\n\
12856The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012857
Eric Smith27bbca62010-11-04 17:06:58 +000012858PyDoc_STRVAR(format_map__doc__,
12859 "S.format_map(mapping) -> str\n\
12860\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012861Return a formatted version of S, using substitutions from mapping.\n\
12862The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012863
Eric Smith4a7d76d2008-05-30 18:10:19 +000012864static PyObject *
12865unicode__format__(PyObject* self, PyObject* args)
12866{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012867 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012868
12869 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12870 return NULL;
12871
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012872 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012873 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012874 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012875}
12876
Eric Smith8c663262007-08-25 02:26:07 +000012877PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012878 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012879\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012880Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012881
12882static PyObject *
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012883unicode__sizeof__(PyUnicodeObject *v)
12884{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012885 Py_ssize_t size;
12886
12887 /* If it's a compact object, account for base structure +
12888 character data. */
12889 if (PyUnicode_IS_COMPACT_ASCII(v))
12890 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12891 else if (PyUnicode_IS_COMPACT(v))
12892 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012893 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012894 else {
12895 /* If it is a two-block object, account for base object, and
12896 for character block if present. */
12897 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012898 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012899 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012900 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012901 }
12902 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012903 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012904 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012905 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012906 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012907 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012908
12909 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012910}
12911
12912PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012913 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012914
12915static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012916unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012917{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012918 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012919 if (!copy)
12920 return NULL;
12921 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012922}
12923
Guido van Rossumd57fd912000-03-10 22:53:23 +000012924static PyMethodDef unicode_methods[] = {
12925
12926 /* Order is according to common usage: often used methods should
12927 appear first, since lookup is done sequentially. */
12928
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012929 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012930 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12931 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012932 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012933 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12934 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12935 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12936 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12937 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12938 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12939 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012940 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012941 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12942 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12943 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012944 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012945 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12946 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12947 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012948 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012949 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012950 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012951 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012952 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12953 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12954 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12955 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12956 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12957 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12958 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12959 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12960 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12961 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12962 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12963 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12964 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12965 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012966 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012967 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012968 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012969 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012970 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012971 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012972 {"maketrans", (PyCFunction) unicode_maketrans,
12973 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012974 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012975#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012976 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012977#endif
12978
12979#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012980 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012981 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012982#endif
12983
Benjamin Peterson14339b62009-01-31 16:36:08 +000012984 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012985 {NULL, NULL}
12986};
12987
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012988static PyObject *
12989unicode_mod(PyObject *v, PyObject *w)
12990{
Brian Curtindfc80e32011-08-10 20:28:54 -050012991 if (!PyUnicode_Check(v))
12992 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012993 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012994}
12995
12996static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012997 0, /*nb_add*/
12998 0, /*nb_subtract*/
12999 0, /*nb_multiply*/
13000 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000013001};
13002
Guido van Rossumd57fd912000-03-10 22:53:23 +000013003static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013004 (lenfunc) unicode_length, /* sq_length */
13005 PyUnicode_Concat, /* sq_concat */
13006 (ssizeargfunc) unicode_repeat, /* sq_repeat */
13007 (ssizeargfunc) unicode_getitem, /* sq_item */
13008 0, /* sq_slice */
13009 0, /* sq_ass_item */
13010 0, /* sq_ass_slice */
13011 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013012};
13013
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013014static PyObject*
13015unicode_subscript(PyUnicodeObject* self, PyObject* item)
13016{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013017 if (PyUnicode_READY(self) == -1)
13018 return NULL;
13019
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013020 if (PyIndex_Check(item)) {
13021 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013022 if (i == -1 && PyErr_Occurred())
13023 return NULL;
13024 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013025 i += PyUnicode_GET_LENGTH(self);
Victor Stinner2fe5ced2011-10-02 00:25:40 +020013026 return unicode_getitem((PyObject*)self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013027 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000013028 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013029 PyObject *result;
13030 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013031 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013032 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013033
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013034 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000013035 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013036 return NULL;
13037 }
13038
13039 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013040 return PyUnicode_New(0, 0);
13041 } else if (start == 0 && step == 1 &&
13042 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013043 PyUnicode_CheckExact(self)) {
13044 Py_INCREF(self);
13045 return (PyObject *)self;
13046 } else if (step == 1) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020013047 return PyUnicode_Substring((PyObject*)self,
13048 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013049 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013050 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013051 src_kind = PyUnicode_KIND(self);
13052 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013053 if (!PyUnicode_IS_ASCII(self)) {
13054 kind_limit = kind_maxchar_limit(src_kind);
13055 max_char = 0;
13056 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13057 ch = PyUnicode_READ(src_kind, src_data, cur);
13058 if (ch > max_char) {
13059 max_char = ch;
13060 if (max_char >= kind_limit)
13061 break;
13062 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013063 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013064 }
Victor Stinner55c99112011-10-13 01:17:06 +020013065 else
13066 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013067 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013068 if (result == NULL)
13069 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013070 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013071 dest_data = PyUnicode_DATA(result);
13072
13073 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013074 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13075 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013076 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013077 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013078 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013079 } else {
13080 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13081 return NULL;
13082 }
13083}
13084
13085static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013086 (lenfunc)unicode_length, /* mp_length */
13087 (binaryfunc)unicode_subscript, /* mp_subscript */
13088 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013089};
13090
Guido van Rossumd57fd912000-03-10 22:53:23 +000013091
Guido van Rossumd57fd912000-03-10 22:53:23 +000013092/* Helpers for PyUnicode_Format() */
13093
13094static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013095getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013096{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013097 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013098 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013099 (*p_argidx)++;
13100 if (arglen < 0)
13101 return args;
13102 else
13103 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013104 }
13105 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013106 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013107 return NULL;
13108}
13109
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013110/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013111
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013112static PyObject *
13113formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013114{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013115 char *p;
13116 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013118
Guido van Rossumd57fd912000-03-10 22:53:23 +000013119 x = PyFloat_AsDouble(v);
13120 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013121 return NULL;
13122
Guido van Rossumd57fd912000-03-10 22:53:23 +000013123 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013124 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013125
Eric Smith0923d1d2009-04-16 20:16:10 +000013126 p = PyOS_double_to_string(x, type, prec,
13127 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013128 if (p == NULL)
13129 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013130 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013131 PyMem_Free(p);
13132 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013133}
13134
Tim Peters38fd5b62000-09-21 05:43:11 +000013135static PyObject*
13136formatlong(PyObject *val, int flags, int prec, int type)
13137{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013138 char *buf;
13139 int len;
13140 PyObject *str; /* temporary string object. */
13141 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013142
Benjamin Peterson14339b62009-01-31 16:36:08 +000013143 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13144 if (!str)
13145 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013146 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013147 Py_DECREF(str);
13148 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013149}
13150
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013151static Py_UCS4
13152formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013153{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013154 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013155 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013156 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013157 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013158 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013159 goto onError;
13160 }
13161 else {
13162 /* Integer input truncated to a character */
13163 long x;
13164 x = PyLong_AsLong(v);
13165 if (x == -1 && PyErr_Occurred())
13166 goto onError;
13167
13168 if (x < 0 || x > 0x10ffff) {
13169 PyErr_SetString(PyExc_OverflowError,
13170 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013171 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013172 }
13173
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013174 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013175 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013176
Benjamin Peterson29060642009-01-31 22:14:21 +000013177 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013178 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013179 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013180 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013181}
13182
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013183static int
13184repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13185{
13186 int r;
13187 assert(count > 0);
13188 assert(PyUnicode_Check(obj));
13189 if (count > 5) {
13190 PyObject *repeated = unicode_repeat((PyUnicodeObject *) obj, count);
13191 if (repeated == NULL)
13192 return -1;
13193 r = _PyAccu_Accumulate(acc, repeated);
13194 Py_DECREF(repeated);
13195 return r;
13196 }
13197 else {
13198 do {
13199 if (_PyAccu_Accumulate(acc, obj))
13200 return -1;
13201 } while (--count);
13202 return 0;
13203 }
13204}
13205
Alexander Belopolsky40018472011-02-26 01:02:56 +000013206PyObject *
13207PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013209 void *fmt;
13210 int fmtkind;
13211 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013212 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013213 int r;
13214 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013216 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013217 PyObject *temp = NULL;
13218 PyObject *second = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013219 PyUnicodeObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013220 _PyAccu acc;
13221 static PyObject *plus, *minus, *blank, *zero, *percent;
13222
13223 if (!plus && !(plus = get_latin1_char('+')))
13224 return NULL;
13225 if (!minus && !(minus = get_latin1_char('-')))
13226 return NULL;
13227 if (!blank && !(blank = get_latin1_char(' ')))
13228 return NULL;
13229 if (!zero && !(zero = get_latin1_char('0')))
13230 return NULL;
13231 if (!percent && !(percent = get_latin1_char('%')))
13232 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013233
Guido van Rossumd57fd912000-03-10 22:53:23 +000013234 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013235 PyErr_BadInternalCall();
13236 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013238 uformat = (PyUnicodeObject*)PyUnicode_FromObject(format);
13239 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013240 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013241 if (_PyAccu_Init(&acc))
13242 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 fmt = PyUnicode_DATA(uformat);
13244 fmtkind = PyUnicode_KIND(uformat);
13245 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13246 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013247
Guido van Rossumd57fd912000-03-10 22:53:23 +000013248 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013249 arglen = PyTuple_Size(args);
13250 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013251 }
13252 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013253 arglen = -1;
13254 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013255 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013256 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013257 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013259
13260 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013261 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013262 PyObject *nonfmt;
13263 Py_ssize_t nonfmtpos;
13264 nonfmtpos = fmtpos++;
13265 while (fmtcnt >= 0 &&
13266 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13267 fmtpos++;
13268 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013269 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013270 nonfmt = PyUnicode_Substring((PyObject *) uformat, nonfmtpos, fmtpos);
13271 if (nonfmt == NULL)
13272 goto onError;
13273 r = _PyAccu_Accumulate(&acc, nonfmt);
13274 Py_DECREF(nonfmt);
13275 if (r)
13276 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013277 }
13278 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 /* Got a format specifier */
13280 int flags = 0;
13281 Py_ssize_t width = -1;
13282 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013283 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013284 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 int isnumok;
13286 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013287 void *pbuf = NULL;
13288 Py_ssize_t pindex, len;
13289 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013290
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013291 fmtpos++;
13292 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13293 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013294 Py_ssize_t keylen;
13295 PyObject *key;
13296 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013297
Benjamin Peterson29060642009-01-31 22:14:21 +000013298 if (dict == NULL) {
13299 PyErr_SetString(PyExc_TypeError,
13300 "format requires a mapping");
13301 goto onError;
13302 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013303 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013304 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013305 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013306 /* Skip over balanced parentheses */
13307 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013310 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013311 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013312 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013313 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013314 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013315 if (fmtcnt < 0 || pcount > 0) {
13316 PyErr_SetString(PyExc_ValueError,
13317 "incomplete format key");
13318 goto onError;
13319 }
Victor Stinner12bab6d2011-10-01 01:53:49 +020013320 key = PyUnicode_Substring((PyObject*)uformat,
13321 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013322 if (key == NULL)
13323 goto onError;
13324 if (args_owned) {
13325 Py_DECREF(args);
13326 args_owned = 0;
13327 }
13328 args = PyObject_GetItem(dict, key);
13329 Py_DECREF(key);
13330 if (args == NULL) {
13331 goto onError;
13332 }
13333 args_owned = 1;
13334 arglen = -1;
13335 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013336 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013337 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013338 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013339 case '-': flags |= F_LJUST; continue;
13340 case '+': flags |= F_SIGN; continue;
13341 case ' ': flags |= F_BLANK; continue;
13342 case '#': flags |= F_ALT; continue;
13343 case '0': flags |= F_ZERO; continue;
13344 }
13345 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013346 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013347 if (c == '*') {
13348 v = getnextarg(args, arglen, &argidx);
13349 if (v == NULL)
13350 goto onError;
13351 if (!PyLong_Check(v)) {
13352 PyErr_SetString(PyExc_TypeError,
13353 "* wants int");
13354 goto onError;
13355 }
13356 width = PyLong_AsLong(v);
13357 if (width == -1 && PyErr_Occurred())
13358 goto onError;
13359 if (width < 0) {
13360 flags |= F_LJUST;
13361 width = -width;
13362 }
13363 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013364 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013365 }
13366 else if (c >= '0' && c <= '9') {
13367 width = c - '0';
13368 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013369 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013370 if (c < '0' || c > '9')
13371 break;
13372 if ((width*10) / 10 != width) {
13373 PyErr_SetString(PyExc_ValueError,
13374 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013375 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013376 }
13377 width = width*10 + (c - '0');
13378 }
13379 }
13380 if (c == '.') {
13381 prec = 0;
13382 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013383 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 if (c == '*') {
13385 v = getnextarg(args, arglen, &argidx);
13386 if (v == NULL)
13387 goto onError;
13388 if (!PyLong_Check(v)) {
13389 PyErr_SetString(PyExc_TypeError,
13390 "* wants int");
13391 goto onError;
13392 }
13393 prec = PyLong_AsLong(v);
13394 if (prec == -1 && PyErr_Occurred())
13395 goto onError;
13396 if (prec < 0)
13397 prec = 0;
13398 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013399 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013400 }
13401 else if (c >= '0' && c <= '9') {
13402 prec = c - '0';
13403 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013404 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 if (c < '0' || c > '9')
13406 break;
13407 if ((prec*10) / 10 != prec) {
13408 PyErr_SetString(PyExc_ValueError,
13409 "prec too big");
13410 goto onError;
13411 }
13412 prec = prec*10 + (c - '0');
13413 }
13414 }
13415 } /* prec */
13416 if (fmtcnt >= 0) {
13417 if (c == 'h' || c == 'l' || c == 'L') {
13418 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013419 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013420 }
13421 }
13422 if (fmtcnt < 0) {
13423 PyErr_SetString(PyExc_ValueError,
13424 "incomplete format");
13425 goto onError;
13426 }
13427 if (c != '%') {
13428 v = getnextarg(args, arglen, &argidx);
13429 if (v == NULL)
13430 goto onError;
13431 }
13432 sign = 0;
13433 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013434 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013435 switch (c) {
13436
13437 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013438 _PyAccu_Accumulate(&acc, percent);
13439 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013440
13441 case 's':
13442 case 'r':
13443 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013444 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013445 temp = v;
13446 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013447 }
13448 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013449 if (c == 's')
13450 temp = PyObject_Str(v);
13451 else if (c == 'r')
13452 temp = PyObject_Repr(v);
13453 else
13454 temp = PyObject_ASCII(v);
13455 if (temp == NULL)
13456 goto onError;
13457 if (PyUnicode_Check(temp))
13458 /* nothing to do */;
13459 else {
13460 Py_DECREF(temp);
13461 PyErr_SetString(PyExc_TypeError,
13462 "%s argument has non-string str()");
13463 goto onError;
13464 }
13465 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013466 if (PyUnicode_READY(temp) == -1) {
13467 Py_CLEAR(temp);
13468 goto onError;
13469 }
13470 pbuf = PyUnicode_DATA(temp);
13471 kind = PyUnicode_KIND(temp);
13472 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013473 if (prec >= 0 && len > prec)
13474 len = prec;
13475 break;
13476
13477 case 'i':
13478 case 'd':
13479 case 'u':
13480 case 'o':
13481 case 'x':
13482 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013483 isnumok = 0;
13484 if (PyNumber_Check(v)) {
13485 PyObject *iobj=NULL;
13486
13487 if (PyLong_Check(v)) {
13488 iobj = v;
13489 Py_INCREF(iobj);
13490 }
13491 else {
13492 iobj = PyNumber_Long(v);
13493 }
13494 if (iobj!=NULL) {
13495 if (PyLong_Check(iobj)) {
13496 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013497 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 Py_DECREF(iobj);
13499 if (!temp)
13500 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013501 if (PyUnicode_READY(temp) == -1) {
13502 Py_CLEAR(temp);
13503 goto onError;
13504 }
13505 pbuf = PyUnicode_DATA(temp);
13506 kind = PyUnicode_KIND(temp);
13507 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 sign = 1;
13509 }
13510 else {
13511 Py_DECREF(iobj);
13512 }
13513 }
13514 }
13515 if (!isnumok) {
13516 PyErr_Format(PyExc_TypeError,
13517 "%%%c format: a number is required, "
13518 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13519 goto onError;
13520 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013521 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013522 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013523 fillobj = zero;
13524 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 break;
13526
13527 case 'e':
13528 case 'E':
13529 case 'f':
13530 case 'F':
13531 case 'g':
13532 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013533 temp = formatfloat(v, flags, prec, c);
13534 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013536 if (PyUnicode_READY(temp) == -1) {
13537 Py_CLEAR(temp);
13538 goto onError;
13539 }
13540 pbuf = PyUnicode_DATA(temp);
13541 kind = PyUnicode_KIND(temp);
13542 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013544 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013546 fillobj = zero;
13547 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 break;
13549
13550 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013551 {
13552 Py_UCS4 ch = formatchar(v);
13553 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013554 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013555 temp = _PyUnicode_FromUCS4(&ch, 1);
13556 if (temp == NULL)
13557 goto onError;
13558 pbuf = PyUnicode_DATA(temp);
13559 kind = PyUnicode_KIND(temp);
13560 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013562 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013563
13564 default:
13565 PyErr_Format(PyExc_ValueError,
13566 "unsupported format character '%c' (0x%x) "
13567 "at index %zd",
13568 (31<=c && c<=126) ? (char)c : '?',
13569 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013571 goto onError;
13572 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013573 /* pbuf is initialized here. */
13574 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013575 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013576 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13577 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 pindex++;
13580 }
13581 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13582 signobj = plus;
13583 len--;
13584 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013585 }
13586 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013587 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013588 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013589 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013590 else
13591 sign = 0;
13592 }
13593 if (width < len)
13594 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013595 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013596 if (fill != ' ') {
13597 assert(signobj != NULL);
13598 if (_PyAccu_Accumulate(&acc, signobj))
13599 goto onError;
13600 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013601 if (width > len)
13602 width--;
13603 }
13604 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013605 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013606 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013608 second = get_latin1_char(
13609 PyUnicode_READ(kind, pbuf, pindex + 1));
13610 pindex += 2;
13611 if (second == NULL ||
13612 _PyAccu_Accumulate(&acc, zero) ||
13613 _PyAccu_Accumulate(&acc, second))
13614 goto onError;
13615 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013616 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 width -= 2;
13618 if (width < 0)
13619 width = 0;
13620 len -= 2;
13621 }
13622 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013623 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013624 if (repeat_accumulate(&acc, fillobj, width - len))
13625 goto onError;
13626 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013627 }
13628 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013629 if (sign) {
13630 assert(signobj != NULL);
13631 if (_PyAccu_Accumulate(&acc, signobj))
13632 goto onError;
13633 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013634 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013635 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13636 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013637 second = get_latin1_char(
13638 PyUnicode_READ(kind, pbuf, pindex + 1));
13639 pindex += 2;
13640 if (second == NULL ||
13641 _PyAccu_Accumulate(&acc, zero) ||
13642 _PyAccu_Accumulate(&acc, second))
13643 goto onError;
13644 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013645 }
13646 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013647 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013648 if (temp != NULL) {
13649 assert(pbuf == PyUnicode_DATA(temp));
13650 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013651 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013652 else {
13653 const char *p = (const char *) pbuf;
13654 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013655 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013656 v = PyUnicode_FromKindAndData(kind, p, len);
13657 }
13658 if (v == NULL)
13659 goto onError;
13660 r = _PyAccu_Accumulate(&acc, v);
13661 Py_DECREF(v);
13662 if (r)
13663 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013664 if (width > len && repeat_accumulate(&acc, blank, width - len))
13665 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 if (dict && (argidx < arglen) && c != '%') {
13667 PyErr_SetString(PyExc_TypeError,
13668 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013669 goto onError;
13670 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013671 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013672 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013673 } /* until end */
13674 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013675 PyErr_SetString(PyExc_TypeError,
13676 "not all arguments converted during string formatting");
13677 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013678 }
13679
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013680 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013681 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013682 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013683 }
13684 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013685 Py_XDECREF(temp);
13686 Py_XDECREF(second);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013687 return (PyObject *)result;
13688
Benjamin Peterson29060642009-01-31 22:14:21 +000013689 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013690 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013691 Py_XDECREF(temp);
13692 Py_XDECREF(second);
13693 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013694 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013695 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013696 }
13697 return NULL;
13698}
13699
Jeremy Hylton938ace62002-07-17 16:30:39 +000013700static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013701unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13702
Tim Peters6d6c1a32001-08-02 04:15:00 +000013703static PyObject *
13704unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13705{
Benjamin Peterson29060642009-01-31 22:14:21 +000013706 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013707 static char *kwlist[] = {"object", "encoding", "errors", 0};
13708 char *encoding = NULL;
13709 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013710
Benjamin Peterson14339b62009-01-31 16:36:08 +000013711 if (type != &PyUnicode_Type)
13712 return unicode_subtype_new(type, args, kwds);
13713 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013714 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013715 return NULL;
13716 if (x == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013717 return (PyObject *)PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013718 if (encoding == NULL && errors == NULL)
13719 return PyObject_Str(x);
13720 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013721 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013722}
13723
Guido van Rossume023fe02001-08-30 03:12:59 +000013724static PyObject *
13725unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13726{
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013727 PyUnicodeObject *unicode, *self;
13728 Py_ssize_t length, char_size;
13729 int share_wstr, share_utf8;
13730 unsigned int kind;
13731 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013732
Benjamin Peterson14339b62009-01-31 16:36:08 +000013733 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013734
13735 unicode = (PyUnicodeObject *)unicode_new(&PyUnicode_Type, args, kwds);
13736 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013737 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013738 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013739 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013740 return NULL;
13741
13742 self = (PyUnicodeObject *) type->tp_alloc(type, 0);
13743 if (self == NULL) {
13744 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013745 return NULL;
13746 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013747 kind = PyUnicode_KIND(unicode);
13748 length = PyUnicode_GET_LENGTH(unicode);
13749
13750 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013751#ifdef Py_DEBUG
13752 _PyUnicode_HASH(self) = -1;
13753#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013754 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013755#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013756 _PyUnicode_STATE(self).interned = 0;
13757 _PyUnicode_STATE(self).kind = kind;
13758 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013759 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013760 _PyUnicode_STATE(self).ready = 1;
13761 _PyUnicode_WSTR(self) = NULL;
13762 _PyUnicode_UTF8_LENGTH(self) = 0;
13763 _PyUnicode_UTF8(self) = NULL;
13764 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013765 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013766
13767 share_utf8 = 0;
13768 share_wstr = 0;
13769 if (kind == PyUnicode_1BYTE_KIND) {
13770 char_size = 1;
13771 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13772 share_utf8 = 1;
13773 }
13774 else if (kind == PyUnicode_2BYTE_KIND) {
13775 char_size = 2;
13776 if (sizeof(wchar_t) == 2)
13777 share_wstr = 1;
13778 }
13779 else {
13780 assert(kind == PyUnicode_4BYTE_KIND);
13781 char_size = 4;
13782 if (sizeof(wchar_t) == 4)
13783 share_wstr = 1;
13784 }
13785
13786 /* Ensure we won't overflow the length. */
13787 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13788 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013789 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013790 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013791 data = PyObject_MALLOC((length + 1) * char_size);
13792 if (data == NULL) {
13793 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013794 goto onError;
13795 }
13796
Victor Stinnerc3c74152011-10-02 20:39:55 +020013797 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013798 if (share_utf8) {
13799 _PyUnicode_UTF8_LENGTH(self) = length;
13800 _PyUnicode_UTF8(self) = data;
13801 }
13802 if (share_wstr) {
13803 _PyUnicode_WSTR_LENGTH(self) = length;
13804 _PyUnicode_WSTR(self) = (wchar_t *)data;
13805 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013807 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013808 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013809 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013810#ifdef Py_DEBUG
13811 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13812#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013813 Py_DECREF(unicode);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013814 return (PyObject *)self;
13815
13816onError:
13817 Py_DECREF(unicode);
13818 Py_DECREF(self);
13819 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013820}
13821
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013822PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013823 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013824\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013825Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013826encoding defaults to the current default string encoding.\n\
13827errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013828
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013829static PyObject *unicode_iter(PyObject *seq);
13830
Guido van Rossumd57fd912000-03-10 22:53:23 +000013831PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013832 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013833 "str", /* tp_name */
13834 sizeof(PyUnicodeObject), /* tp_size */
13835 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013836 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013837 (destructor)unicode_dealloc, /* tp_dealloc */
13838 0, /* tp_print */
13839 0, /* tp_getattr */
13840 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013841 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013842 unicode_repr, /* tp_repr */
13843 &unicode_as_number, /* tp_as_number */
13844 &unicode_as_sequence, /* tp_as_sequence */
13845 &unicode_as_mapping, /* tp_as_mapping */
13846 (hashfunc) unicode_hash, /* tp_hash*/
13847 0, /* tp_call*/
13848 (reprfunc) unicode_str, /* tp_str */
13849 PyObject_GenericGetAttr, /* tp_getattro */
13850 0, /* tp_setattro */
13851 0, /* tp_as_buffer */
13852 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013853 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013854 unicode_doc, /* tp_doc */
13855 0, /* tp_traverse */
13856 0, /* tp_clear */
13857 PyUnicode_RichCompare, /* tp_richcompare */
13858 0, /* tp_weaklistoffset */
13859 unicode_iter, /* tp_iter */
13860 0, /* tp_iternext */
13861 unicode_methods, /* tp_methods */
13862 0, /* tp_members */
13863 0, /* tp_getset */
13864 &PyBaseObject_Type, /* tp_base */
13865 0, /* tp_dict */
13866 0, /* tp_descr_get */
13867 0, /* tp_descr_set */
13868 0, /* tp_dictoffset */
13869 0, /* tp_init */
13870 0, /* tp_alloc */
13871 unicode_new, /* tp_new */
13872 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013873};
13874
13875/* Initialize the Unicode implementation */
13876
Victor Stinner3a50e702011-10-18 21:21:00 +020013877int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013878{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013879 int i;
13880
Thomas Wouters477c8d52006-05-27 19:21:47 +000013881 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013882 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013883 0x000A, /* LINE FEED */
13884 0x000D, /* CARRIAGE RETURN */
13885 0x001C, /* FILE SEPARATOR */
13886 0x001D, /* GROUP SEPARATOR */
13887 0x001E, /* RECORD SEPARATOR */
13888 0x0085, /* NEXT LINE */
13889 0x2028, /* LINE SEPARATOR */
13890 0x2029, /* PARAGRAPH SEPARATOR */
13891 };
13892
Fred Drakee4315f52000-05-09 19:53:39 +000013893 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013894 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013895 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013896 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013897 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013898
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013899 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013900 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013901 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013902 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013903
13904 /* initialize the linebreak bloom filter */
13905 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013906 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013907 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013908
13909 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013910
13911#ifdef HAVE_MBCS
13912 winver.dwOSVersionInfoSize = sizeof(winver);
13913 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13914 PyErr_SetFromWindowsErr(0);
13915 return -1;
13916 }
13917#endif
13918 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013919}
13920
13921/* Finalize the Unicode implementation */
13922
Christian Heimesa156e092008-02-16 07:38:31 +000013923int
13924PyUnicode_ClearFreeList(void)
13925{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013926 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013927}
13928
Guido van Rossumd57fd912000-03-10 22:53:23 +000013929void
Thomas Wouters78890102000-07-22 19:25:51 +000013930_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013931{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013932 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013933
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013934 Py_XDECREF(unicode_empty);
13935 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013936
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013937 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013938 if (unicode_latin1[i]) {
13939 Py_DECREF(unicode_latin1[i]);
13940 unicode_latin1[i] = NULL;
13941 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013942 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013943 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013944 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013945}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013946
Walter Dörwald16807132007-05-25 13:52:07 +000013947void
13948PyUnicode_InternInPlace(PyObject **p)
13949{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013950 register PyUnicodeObject *s = (PyUnicodeObject *)(*p);
13951 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013952#ifdef Py_DEBUG
13953 assert(s != NULL);
13954 assert(_PyUnicode_CHECK(s));
13955#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013956 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013957 return;
13958#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013959 /* If it's a subclass, we don't really know what putting
13960 it in the interned dict might do. */
13961 if (!PyUnicode_CheckExact(s))
13962 return;
13963 if (PyUnicode_CHECK_INTERNED(s))
13964 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013965 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013966 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013967 return;
13968 }
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013969 s = (PyUnicodeObject *)(*p);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 if (interned == NULL) {
13971 interned = PyDict_New();
13972 if (interned == NULL) {
13973 PyErr_Clear(); /* Don't leave an exception */
13974 return;
13975 }
13976 }
13977 /* It might be that the GetItem call fails even
13978 though the key is present in the dictionary,
13979 namely when this happens during a stack overflow. */
13980 Py_ALLOW_RECURSION
Benjamin Peterson29060642009-01-31 22:14:21 +000013981 t = PyDict_GetItem(interned, (PyObject *)s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013982 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013983
Benjamin Peterson29060642009-01-31 22:14:21 +000013984 if (t) {
13985 Py_INCREF(t);
13986 Py_DECREF(*p);
13987 *p = t;
13988 return;
13989 }
Walter Dörwald16807132007-05-25 13:52:07 +000013990
Benjamin Peterson14339b62009-01-31 16:36:08 +000013991 PyThreadState_GET()->recursion_critical = 1;
13992 if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
13993 PyErr_Clear();
13994 PyThreadState_GET()->recursion_critical = 0;
13995 return;
13996 }
13997 PyThreadState_GET()->recursion_critical = 0;
13998 /* The two references in interned are not counted by refcnt.
13999 The deallocator will take care of this */
14000 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014001 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000014002}
14003
14004void
14005PyUnicode_InternImmortal(PyObject **p)
14006{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014007 PyUnicodeObject *u = (PyUnicodeObject *)*p;
14008
Benjamin Peterson14339b62009-01-31 16:36:08 +000014009 PyUnicode_InternInPlace(p);
14010 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014011 _PyUnicode_STATE(u).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014012 Py_INCREF(*p);
14013 }
Walter Dörwald16807132007-05-25 13:52:07 +000014014}
14015
14016PyObject *
14017PyUnicode_InternFromString(const char *cp)
14018{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 PyObject *s = PyUnicode_FromString(cp);
14020 if (s == NULL)
14021 return NULL;
14022 PyUnicode_InternInPlace(&s);
14023 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000014024}
14025
Alexander Belopolsky40018472011-02-26 01:02:56 +000014026void
14027_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000014028{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014029 PyObject *keys;
14030 PyUnicodeObject *s;
14031 Py_ssize_t i, n;
14032 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000014033
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 if (interned == NULL || !PyDict_Check(interned))
14035 return;
14036 keys = PyDict_Keys(interned);
14037 if (keys == NULL || !PyList_Check(keys)) {
14038 PyErr_Clear();
14039 return;
14040 }
Walter Dörwald16807132007-05-25 13:52:07 +000014041
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14043 detector, interned unicode strings are not forcibly deallocated;
14044 rather, we give them their stolen references back, and then clear
14045 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014046
Benjamin Peterson14339b62009-01-31 16:36:08 +000014047 n = PyList_GET_SIZE(keys);
14048 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014049 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014050 for (i = 0; i < n; i++) {
14051 s = (PyUnicodeObject *) PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014052 if (PyUnicode_READY(s) == -1) {
14053 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014054 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014055 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014056 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 case SSTATE_NOT_INTERNED:
14058 /* XXX Shouldn't happen */
14059 break;
14060 case SSTATE_INTERNED_IMMORTAL:
14061 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014062 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014063 break;
14064 case SSTATE_INTERNED_MORTAL:
14065 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014066 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014067 break;
14068 default:
14069 Py_FatalError("Inconsistent interned string state.");
14070 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014071 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014072 }
14073 fprintf(stderr, "total size of all interned strings: "
14074 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14075 "mortal/immortal\n", mortal_size, immortal_size);
14076 Py_DECREF(keys);
14077 PyDict_Clear(interned);
14078 Py_DECREF(interned);
14079 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014080}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014081
14082
14083/********************* Unicode Iterator **************************/
14084
14085typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 PyObject_HEAD
14087 Py_ssize_t it_index;
14088 PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014089} unicodeiterobject;
14090
14091static void
14092unicodeiter_dealloc(unicodeiterobject *it)
14093{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 _PyObject_GC_UNTRACK(it);
14095 Py_XDECREF(it->it_seq);
14096 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014097}
14098
14099static int
14100unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14101{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014102 Py_VISIT(it->it_seq);
14103 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014104}
14105
14106static PyObject *
14107unicodeiter_next(unicodeiterobject *it)
14108{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014109 PyUnicodeObject *seq;
14110 PyObject *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014111
Benjamin Peterson14339b62009-01-31 16:36:08 +000014112 assert(it != NULL);
14113 seq = it->it_seq;
14114 if (seq == NULL)
14115 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014116 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014117
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014118 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14119 int kind = PyUnicode_KIND(seq);
14120 void *data = PyUnicode_DATA(seq);
14121 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14122 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014123 if (item != NULL)
14124 ++it->it_index;
14125 return item;
14126 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014127
Benjamin Peterson14339b62009-01-31 16:36:08 +000014128 Py_DECREF(seq);
14129 it->it_seq = NULL;
14130 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014131}
14132
14133static PyObject *
14134unicodeiter_len(unicodeiterobject *it)
14135{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014136 Py_ssize_t len = 0;
14137 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014138 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014139 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014140}
14141
14142PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14143
14144static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014145 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014146 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014148};
14149
14150PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014151 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14152 "str_iterator", /* tp_name */
14153 sizeof(unicodeiterobject), /* tp_basicsize */
14154 0, /* tp_itemsize */
14155 /* methods */
14156 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14157 0, /* tp_print */
14158 0, /* tp_getattr */
14159 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014160 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014161 0, /* tp_repr */
14162 0, /* tp_as_number */
14163 0, /* tp_as_sequence */
14164 0, /* tp_as_mapping */
14165 0, /* tp_hash */
14166 0, /* tp_call */
14167 0, /* tp_str */
14168 PyObject_GenericGetAttr, /* tp_getattro */
14169 0, /* tp_setattro */
14170 0, /* tp_as_buffer */
14171 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14172 0, /* tp_doc */
14173 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14174 0, /* tp_clear */
14175 0, /* tp_richcompare */
14176 0, /* tp_weaklistoffset */
14177 PyObject_SelfIter, /* tp_iter */
14178 (iternextfunc)unicodeiter_next, /* tp_iternext */
14179 unicodeiter_methods, /* tp_methods */
14180 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014181};
14182
14183static PyObject *
14184unicode_iter(PyObject *seq)
14185{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014186 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014187
Benjamin Peterson14339b62009-01-31 16:36:08 +000014188 if (!PyUnicode_Check(seq)) {
14189 PyErr_BadInternalCall();
14190 return NULL;
14191 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014192 if (PyUnicode_READY(seq) == -1)
14193 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014194 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14195 if (it == NULL)
14196 return NULL;
14197 it->it_index = 0;
14198 Py_INCREF(seq);
14199 it->it_seq = (PyUnicodeObject *)seq;
14200 _PyObject_GC_TRACK(it);
14201 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014202}
14203
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014204#define UNIOP(x) Py_UNICODE_##x
14205#define UNIOP_t Py_UNICODE
14206#include "uniops.h"
14207#undef UNIOP
14208#undef UNIOP_t
14209#define UNIOP(x) Py_UCS4_##x
14210#define UNIOP_t Py_UCS4
14211#include "uniops.h"
14212#undef UNIOP
14213#undef UNIOP_t
Victor Stinner331ea922010-08-10 16:37:20 +000014214
Victor Stinner71133ff2010-09-01 23:43:53 +000014215Py_UNICODE*
Victor Stinner46408602010-09-03 16:18:00 +000014216PyUnicode_AsUnicodeCopy(PyObject *object)
Victor Stinner71133ff2010-09-01 23:43:53 +000014217{
14218 PyUnicodeObject *unicode = (PyUnicodeObject *)object;
Victor Stinner577db2c2011-10-11 22:12:48 +020014219 Py_UNICODE *u, *copy;
Victor Stinner71133ff2010-09-01 23:43:53 +000014220 Py_ssize_t size;
14221
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014222 if (!PyUnicode_Check(unicode)) {
14223 PyErr_BadArgument();
14224 return NULL;
14225 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014226 u = PyUnicode_AsUnicode(object);
14227 if (u == NULL)
14228 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014229 /* Ensure we won't overflow the size. */
14230 if (PyUnicode_GET_SIZE(unicode) > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
14231 PyErr_NoMemory();
14232 return NULL;
14233 }
14234 size = PyUnicode_GET_SIZE(unicode) + 1; /* copy the nul character */
14235 size *= sizeof(Py_UNICODE);
14236 copy = PyMem_Malloc(size);
14237 if (copy == NULL) {
14238 PyErr_NoMemory();
14239 return NULL;
14240 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014241 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014242 return copy;
14243}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014244
Georg Brandl66c221e2010-10-14 07:04:07 +000014245/* A _string module, to export formatter_parser and formatter_field_name_split
14246 to the string.Formatter class implemented in Python. */
14247
14248static PyMethodDef _string_methods[] = {
14249 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14250 METH_O, PyDoc_STR("split the argument as a field name")},
14251 {"formatter_parser", (PyCFunction) formatter_parser,
14252 METH_O, PyDoc_STR("parse the argument as a format string")},
14253 {NULL, NULL}
14254};
14255
14256static struct PyModuleDef _string_module = {
14257 PyModuleDef_HEAD_INIT,
14258 "_string",
14259 PyDoc_STR("string helper module"),
14260 0,
14261 _string_methods,
14262 NULL,
14263 NULL,
14264 NULL,
14265 NULL
14266};
14267
14268PyMODINIT_FUNC
14269PyInit__string(void)
14270{
14271 return PyModule_Create(&_string_module);
14272}
14273
14274
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014275#ifdef __cplusplus
14276}
14277#endif