blob: 8a353071dd47dd09ec7467b75fcba46e2fd06099 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
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 Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100405 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Victor Stinner3a50e702011-10-18 21:21:00 +0200411#ifdef HAVE_MBCS
412static OSVERSIONINFOEX winver;
413#endif
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415/* --- Bloom Filters ----------------------------------------------------- */
416
417/* stuff to implement simple "bloom filters" for Unicode characters.
418 to keep things simple, we use a single bitmask, using the least 5
419 bits from each unicode characters as the bit index. */
420
421/* the linebreak mask is set up by Unicode_Init below */
422
Antoine Pitrouf068f942010-01-13 14:19:12 +0000423#if LONG_BIT >= 128
424#define BLOOM_WIDTH 128
425#elif LONG_BIT >= 64
426#define BLOOM_WIDTH 64
427#elif LONG_BIT >= 32
428#define BLOOM_WIDTH 32
429#else
430#error "LONG_BIT is smaller than 32"
431#endif
432
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433#define BLOOM_MASK unsigned long
434
435static BLOOM_MASK bloom_linebreak;
436
Antoine Pitrouf068f942010-01-13 14:19:12 +0000437#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
438#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Benjamin Peterson29060642009-01-31 22:14:21 +0000440#define BLOOM_LINEBREAK(ch) \
441 ((ch) < 128U ? ascii_linebreak[(ch)] : \
442 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Alexander Belopolsky40018472011-02-26 01:02:56 +0000444Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446{
447 /* calculate simple bloom-style bitmask for a given unicode string */
448
Antoine Pitrouf068f942010-01-13 14:19:12 +0000449 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 Py_ssize_t i;
451
452 mask = 0;
453 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455
456 return mask;
457}
458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200459#define BLOOM_MEMBER(mask, chr, str) \
460 (BLOOM(mask, chr) \
461 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200463/* Compilation of templated routines */
464
465#include "stringlib/asciilib.h"
466#include "stringlib/fastsearch.h"
467#include "stringlib/partition.h"
468#include "stringlib/split.h"
469#include "stringlib/count.h"
470#include "stringlib/find.h"
471#include "stringlib/find_max_char.h"
472#include "stringlib/localeutil.h"
473#include "stringlib/undef.h"
474
475#include "stringlib/ucs1lib.h"
476#include "stringlib/fastsearch.h"
477#include "stringlib/partition.h"
478#include "stringlib/split.h"
479#include "stringlib/count.h"
480#include "stringlib/find.h"
481#include "stringlib/find_max_char.h"
482#include "stringlib/localeutil.h"
483#include "stringlib/undef.h"
484
485#include "stringlib/ucs2lib.h"
486#include "stringlib/fastsearch.h"
487#include "stringlib/partition.h"
488#include "stringlib/split.h"
489#include "stringlib/count.h"
490#include "stringlib/find.h"
491#include "stringlib/find_max_char.h"
492#include "stringlib/localeutil.h"
493#include "stringlib/undef.h"
494
495#include "stringlib/ucs4lib.h"
496#include "stringlib/fastsearch.h"
497#include "stringlib/partition.h"
498#include "stringlib/split.h"
499#include "stringlib/count.h"
500#include "stringlib/find.h"
501#include "stringlib/find_max_char.h"
502#include "stringlib/localeutil.h"
503#include "stringlib/undef.h"
504
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200505#include "stringlib/unicodedefs.h"
506#include "stringlib/fastsearch.h"
507#include "stringlib/count.h"
508#include "stringlib/find.h"
509
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510/* --- Unicode Object ----------------------------------------------------- */
511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200513fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200515Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
516 Py_ssize_t size, Py_UCS4 ch,
517 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
520
521 switch (kind) {
522 case PyUnicode_1BYTE_KIND:
523 {
524 Py_UCS1 ch1 = (Py_UCS1) ch;
525 if (ch1 == ch)
526 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
527 else
528 return -1;
529 }
530 case PyUnicode_2BYTE_KIND:
531 {
532 Py_UCS2 ch2 = (Py_UCS2) ch;
533 if (ch2 == ch)
534 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
535 else
536 return -1;
537 }
538 case PyUnicode_4BYTE_KIND:
539 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
540 default:
541 assert(0);
542 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544}
545
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546static PyObject*
547resize_compact(PyObject *unicode, Py_ssize_t length)
548{
549 Py_ssize_t char_size;
550 Py_ssize_t struct_size;
551 Py_ssize_t new_size;
552 int share_wstr;
553
554 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200556 if (PyUnicode_IS_COMPACT_ASCII(unicode))
557 struct_size = sizeof(PyASCIIObject);
558 else
559 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200560 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200561
562 _Py_DEC_REFTOTAL;
563 _Py_ForgetReference(unicode);
564
565 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
566 PyErr_NoMemory();
567 return NULL;
568 }
569 new_size = (struct_size + (length + 1) * char_size);
570
571 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
572 if (unicode == NULL) {
573 PyObject_Del(unicode);
574 PyErr_NoMemory();
575 return NULL;
576 }
577 _Py_NewReference(unicode);
578 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200580 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200581 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
582 _PyUnicode_WSTR_LENGTH(unicode) = length;
583 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
585 length, 0);
586 return unicode;
587}
588
Alexander Belopolsky40018472011-02-26 01:02:56 +0000589static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200590resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591{
Victor Stinner95663112011-10-04 01:03:50 +0200592 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200594 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000595
Victor Stinner95663112011-10-04 01:03:50 +0200596 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597
598 if (PyUnicode_IS_READY(unicode)) {
599 Py_ssize_t char_size;
600 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200601 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 void *data;
603
604 data = _PyUnicode_DATA_ANY(unicode);
605 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200606 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200607 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
608 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200609 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
610 {
611 PyObject_DEL(_PyUnicode_UTF8(unicode));
612 _PyUnicode_UTF8(unicode) = NULL;
613 _PyUnicode_UTF8_LENGTH(unicode) = 0;
614 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 new_size = (length + 1) * char_size;
621
622 data = (PyObject *)PyObject_REALLOC(data, new_size);
623 if (data == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200629 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200630 _PyUnicode_WSTR_LENGTH(unicode) = length;
631 }
632 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200633 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_UTF8_LENGTH(unicode) = length;
635 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636 _PyUnicode_LENGTH(unicode) = length;
637 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200638 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200639 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200641 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642 }
Victor Stinner95663112011-10-04 01:03:50 +0200643 assert(_PyUnicode_WSTR(unicode) != NULL);
644
645 /* check for integer overflow */
646 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
647 PyErr_NoMemory();
648 return -1;
649 }
650 wstr = _PyUnicode_WSTR(unicode);
651 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
652 if (!wstr) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 _PyUnicode_WSTR(unicode) = wstr;
657 _PyUnicode_WSTR(unicode)[length] = 0;
658 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200659 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000660 return 0;
661}
662
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663static PyObject*
664resize_copy(PyObject *unicode, Py_ssize_t length)
665{
666 Py_ssize_t copy_length;
667 if (PyUnicode_IS_COMPACT(unicode)) {
668 PyObject *copy;
669 assert(PyUnicode_IS_READY(unicode));
670
671 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
672 if (copy == NULL)
673 return NULL;
674
675 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200676 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200678 }
679 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 assert(_PyUnicode_WSTR(unicode) != NULL);
682 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 if (w == NULL)
685 return NULL;
686 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
687 copy_length = Py_MIN(copy_length, length);
688 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
689 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200690 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200691 }
692}
693
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000695 Ux0000 terminated; some code (e.g. new_identifier)
696 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697
698 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000699 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701*/
702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200704static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#endif
706
Alexander Belopolsky40018472011-02-26 01:02:56 +0000707static PyUnicodeObject *
708_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000709{
710 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714 if (length == 0 && unicode_empty != NULL) {
715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200716 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 }
718
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000719 /* Ensure we won't overflow the size. */
720 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
721 return (PyUnicodeObject *)PyErr_NoMemory();
722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 if (length < 0) {
724 PyErr_SetString(PyExc_SystemError,
725 "Negative size passed to _PyUnicode_New");
726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727 }
728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729#ifdef Py_DEBUG
730 ++unicode_old_new_calls;
731#endif
732
733 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
734 if (unicode == NULL)
735 return NULL;
736 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
737 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
738 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000739 PyErr_NoMemory();
740 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742
Jeremy Hyltond8082792003-09-16 19:41:39 +0000743 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000744 * the caller fails before initializing str -- unicode_resize()
745 * reads str[0], and the Keep-Alive optimization can keep memory
746 * allocated for str alive across a call to unicode_dealloc(unicode).
747 * We don't want unicode_resize to read uninitialized memory in
748 * that case.
749 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 _PyUnicode_WSTR(unicode)[0] = 0;
751 _PyUnicode_WSTR(unicode)[length] = 0;
752 _PyUnicode_WSTR_LENGTH(unicode) = length;
753 _PyUnicode_HASH(unicode) = -1;
754 _PyUnicode_STATE(unicode).interned = 0;
755 _PyUnicode_STATE(unicode).kind = 0;
756 _PyUnicode_STATE(unicode).compact = 0;
757 _PyUnicode_STATE(unicode).ready = 0;
758 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200759 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200761 _PyUnicode_UTF8(unicode) = NULL;
762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100763 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000764 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000765
Benjamin Peterson29060642009-01-31 22:14:21 +0000766 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000767 /* XXX UNREF/NEWREF interface should be more symmetrical */
768 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000770 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000772}
773
Victor Stinnerf42dc442011-10-02 23:33:16 +0200774static const char*
775unicode_kind_name(PyObject *unicode)
776{
Victor Stinner42dfd712011-10-03 14:41:45 +0200777 /* don't check consistency: unicode_kind_name() is called from
778 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200779 if (!PyUnicode_IS_COMPACT(unicode))
780 {
781 if (!PyUnicode_IS_READY(unicode))
782 return "wstr";
783 switch(PyUnicode_KIND(unicode))
784 {
785 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200786 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200787 return "legacy ascii";
788 else
789 return "legacy latin1";
790 case PyUnicode_2BYTE_KIND:
791 return "legacy UCS2";
792 case PyUnicode_4BYTE_KIND:
793 return "legacy UCS4";
794 default:
795 return "<legacy invalid kind>";
796 }
797 }
798 assert(PyUnicode_IS_READY(unicode));
799 switch(PyUnicode_KIND(unicode))
800 {
801 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200802 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200803 return "ascii";
804 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 default:
811 return "<invalid compact kind>";
812 }
813}
814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200816static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817
818/* Functions wrapping macros for use in debugger */
819char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821}
822
823void *_PyUnicode_compact_data(void *unicode) {
824 return _PyUnicode_COMPACT_DATA(unicode);
825}
826void *_PyUnicode_data(void *unicode){
827 printf("obj %p\n", unicode);
828 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
829 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
830 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
831 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
832 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
833 return PyUnicode_DATA(unicode);
834}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200835
836void
837_PyUnicode_Dump(PyObject *op)
838{
839 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200840 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
841 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
842 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200843
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200845 {
846 if (ascii->state.ascii)
847 data = (ascii + 1);
848 else
849 data = (compact + 1);
850 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200851 else
852 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200853 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
854
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 if (ascii->wstr == data)
856 printf("shared ");
857 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200858
Victor Stinnera3b334d2011-10-03 13:53:37 +0200859 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200860 printf(" (%zu), ", compact->wstr_length);
861 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
862 printf("shared ");
863 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200865 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200866}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867#endif
868
869PyObject *
870PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
871{
872 PyObject *obj;
873 PyCompactUnicodeObject *unicode;
874 void *data;
875 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200876 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 Py_ssize_t char_size;
878 Py_ssize_t struct_size;
879
880 /* Optimization for empty strings */
881 if (size == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 }
885
886#ifdef Py_DEBUG
887 ++unicode_new_new_calls;
888#endif
889
Victor Stinner9e9d6892011-10-04 01:02:02 +0200890 is_ascii = 0;
891 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200892 struct_size = sizeof(PyCompactUnicodeObject);
893 if (maxchar < 128) {
894 kind_state = PyUnicode_1BYTE_KIND;
895 char_size = 1;
896 is_ascii = 1;
897 struct_size = sizeof(PyASCIIObject);
898 }
899 else if (maxchar < 256) {
900 kind_state = PyUnicode_1BYTE_KIND;
901 char_size = 1;
902 }
903 else if (maxchar < 65536) {
904 kind_state = PyUnicode_2BYTE_KIND;
905 char_size = 2;
906 if (sizeof(wchar_t) == 2)
907 is_sharing = 1;
908 }
909 else {
910 kind_state = PyUnicode_4BYTE_KIND;
911 char_size = 4;
912 if (sizeof(wchar_t) == 4)
913 is_sharing = 1;
914 }
915
916 /* Ensure we won't overflow the size. */
917 if (size < 0) {
918 PyErr_SetString(PyExc_SystemError,
919 "Negative size passed to PyUnicode_New");
920 return NULL;
921 }
922 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
923 return PyErr_NoMemory();
924
925 /* Duplicated allocation code from _PyObject_New() instead of a call to
926 * PyObject_New() so we are able to allocate space for the object and
927 * it's data buffer.
928 */
929 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
930 if (obj == NULL)
931 return PyErr_NoMemory();
932 obj = PyObject_INIT(obj, &PyUnicode_Type);
933 if (obj == NULL)
934 return NULL;
935
936 unicode = (PyCompactUnicodeObject *)obj;
937 if (is_ascii)
938 data = ((PyASCIIObject*)obj) + 1;
939 else
940 data = unicode + 1;
941 _PyUnicode_LENGTH(unicode) = size;
942 _PyUnicode_HASH(unicode) = -1;
943 _PyUnicode_STATE(unicode).interned = 0;
944 _PyUnicode_STATE(unicode).kind = kind_state;
945 _PyUnicode_STATE(unicode).compact = 1;
946 _PyUnicode_STATE(unicode).ready = 1;
947 _PyUnicode_STATE(unicode).ascii = is_ascii;
948 if (is_ascii) {
949 ((char*)data)[size] = 0;
950 _PyUnicode_WSTR(unicode) = NULL;
951 }
952 else if (kind_state == PyUnicode_1BYTE_KIND) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200957 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 }
959 else {
960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 if (kind_state == PyUnicode_2BYTE_KIND)
963 ((Py_UCS2*)data)[size] = 0;
964 else /* kind_state == PyUnicode_4BYTE_KIND */
965 ((Py_UCS4*)data)[size] = 0;
966 if (is_sharing) {
967 _PyUnicode_WSTR_LENGTH(unicode) = size;
968 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
969 }
970 else {
971 _PyUnicode_WSTR_LENGTH(unicode) = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 }
974 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100975 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return obj;
977}
978
979#if SIZEOF_WCHAR_T == 2
980/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
981 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200982 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983
984 This function assumes that unicode can hold one more code point than wstr
985 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200986static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200988 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989{
990 const wchar_t *iter;
991 Py_UCS4 *ucs4_out;
992
Victor Stinner910337b2011-10-03 03:20:16 +0200993 assert(unicode != NULL);
994 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
996 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
997
998 for (iter = begin; iter < end; ) {
999 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1000 _PyUnicode_GET_LENGTH(unicode)));
1001 if (*iter >= 0xD800 && *iter <= 0xDBFF
1002 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1003 {
1004 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1005 iter += 2;
1006 }
1007 else {
1008 *ucs4_out++ = *iter;
1009 iter++;
1010 }
1011 }
1012 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1013 _PyUnicode_GET_LENGTH(unicode)));
1014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015}
1016#endif
1017
Victor Stinnercd9950f2011-10-02 00:34:53 +02001018static int
1019_PyUnicode_Dirty(PyObject *unicode)
1020{
Victor Stinner910337b2011-10-03 03:20:16 +02001021 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001023 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001024 "Cannot modify a string having more than 1 reference");
1025 return -1;
1026 }
1027 _PyUnicode_DIRTY(unicode);
1028 return 0;
1029}
1030
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001031static int
1032_copy_characters(PyObject *to, Py_ssize_t to_start,
1033 PyObject *from, Py_ssize_t from_start,
1034 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001036 unsigned int from_kind, to_kind;
1037 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001040 assert(PyUnicode_Check(from));
1041 assert(PyUnicode_Check(to));
1042 assert(PyUnicode_IS_READY(from));
1043 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001045 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1046 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1047 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001049 if (how_many == 0)
1050 return 0;
1051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001055 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057#ifdef Py_DEBUG
1058 if (!check_maxchar
1059 && (from_kind > to_kind
1060 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001061 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1063 Py_UCS4 ch;
1064 Py_ssize_t i;
1065 for (i=0; i < how_many; i++) {
1066 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1067 assert(ch <= to_maxchar);
1068 }
1069 }
1070#endif
1071 fast = (from_kind == to_kind);
1072 if (check_maxchar
1073 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1074 {
1075 /* deny latin1 => ascii */
1076 fast = 0;
1077 }
1078
1079 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001080 Py_MEMCPY((char*)to_data + to_kind * to_start,
1081 (char*)from_data + from_kind * from_start,
1082 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
1085 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS2,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_2BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001094 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS1, Py_UCS4,
1099 PyUnicode_1BYTE_DATA(from) + from_start,
1100 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
1104 else if (from_kind == PyUnicode_2BYTE_KIND
1105 && to_kind == PyUnicode_4BYTE_KIND)
1106 {
1107 _PyUnicode_CONVERT_BYTES(
1108 Py_UCS2, Py_UCS4,
1109 PyUnicode_2BYTE_DATA(from) + from_start,
1110 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1111 PyUnicode_4BYTE_DATA(to) + to_start
1112 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001114 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001115 /* check if max_char(from substring) <= max_char(to) */
1116 if (from_kind > to_kind
1117 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001118 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001120 /* slow path to check for character overflow */
1121 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 Py_ssize_t i;
1124
Victor Stinner56c161a2011-10-06 02:47:11 +02001125#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 for (i=0; i < how_many; i++) {
1127 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001128 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1130 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001131#else
1132 if (!check_maxchar) {
1133 for (i=0; i < how_many; i++) {
1134 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1135 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1136 }
1137 }
1138 else {
1139 for (i=0; i < how_many; i++) {
1140 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1141 if (ch > to_maxchar)
1142 return 1;
1143 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1144 }
1145 }
1146#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001149 assert(0 && "inconsistent state");
1150 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
1152 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 return 0;
1154}
1155
1156static void
1157copy_characters(PyObject *to, Py_ssize_t to_start,
1158 PyObject *from, Py_ssize_t from_start,
1159 Py_ssize_t how_many)
1160{
1161 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1162}
1163
1164Py_ssize_t
1165PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1166 PyObject *from, Py_ssize_t from_start,
1167 Py_ssize_t how_many)
1168{
1169 int err;
1170
1171 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175
1176 if (PyUnicode_READY(from))
1177 return -1;
1178 if (PyUnicode_READY(to))
1179 return -1;
1180
1181 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1182 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1183 PyErr_Format(PyExc_SystemError,
1184 "Cannot write %zi characters at %zi "
1185 "in a string of %zi characters",
1186 how_many, to_start, PyUnicode_GET_LENGTH(to));
1187 return -1;
1188 }
1189
1190 if (how_many == 0)
1191 return 0;
1192
1193 if (_PyUnicode_Dirty(to))
1194 return -1;
1195
1196 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1197 if (err) {
1198 PyErr_Format(PyExc_SystemError,
1199 "Cannot copy %s characters "
1200 "into a string of %s characters",
1201 unicode_kind_name(from),
1202 unicode_kind_name(to));
1203 return -1;
1204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206}
1207
Victor Stinner17222162011-09-28 22:15:37 +02001208/* Find the maximum code point and count the number of surrogate pairs so a
1209 correct string length can be computed before converting a string to UCS4.
1210 This function counts single surrogates as a character and not as a pair.
1211
1212 Return 0 on success, or -1 on error. */
1213static int
1214find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1215 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216{
1217 const wchar_t *iter;
1218
Victor Stinnerc53be962011-10-02 21:33:54 +02001219 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 *num_surrogates = 0;
1221 *maxchar = 0;
1222
1223 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001224 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001226#if SIZEOF_WCHAR_T != 2
1227 if (*maxchar >= 0x10000)
1228 return 0;
1229#endif
1230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231#if SIZEOF_WCHAR_T == 2
1232 if (*iter >= 0xD800 && *iter <= 0xDBFF
1233 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1234 {
1235 Py_UCS4 surrogate_val;
1236 surrogate_val = (((iter[0] & 0x3FF)<<10)
1237 | (iter[1] & 0x3FF)) + 0x10000;
1238 ++(*num_surrogates);
1239 if (surrogate_val > *maxchar)
1240 *maxchar = surrogate_val;
1241 iter += 2;
1242 }
1243 else
1244 iter++;
1245#else
1246 iter++;
1247#endif
1248 }
1249 return 0;
1250}
1251
1252#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001253static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254#endif
1255
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001256static int
1257unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001259 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 wchar_t *end;
1261 Py_UCS4 maxchar = 0;
1262 Py_ssize_t num_surrogates;
1263#if SIZEOF_WCHAR_T == 2
1264 Py_ssize_t length_wo_surrogates;
1265#endif
1266
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001268 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001269
Georg Brandl7597add2011-10-05 16:36:47 +02001270 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001271 strings were created using _PyObject_New() and where no canonical
1272 representation (the str field) has been set yet aka strings
1273 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001274 assert(_PyUnicode_CHECK(unicode));
1275 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001277 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001278 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001279 /* Actually, it should neither be interned nor be anything else: */
1280 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001281
1282#ifdef Py_DEBUG
1283 ++unicode_ready_calls;
1284#endif
1285
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286#ifdef Py_DEBUG
1287 assert(!replace || Py_REFCNT(unicode) == 1);
1288#else
1289 if (replace && Py_REFCNT(unicode) != 1)
1290 replace = 0;
1291#endif
1292 if (replace) {
1293 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1294 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1295 /* Optimization for empty strings */
1296 if (len == 0) {
1297 Py_INCREF(unicode_empty);
1298 Py_DECREF(*p_obj);
1299 *p_obj = unicode_empty;
1300 return 0;
1301 }
1302 if (len == 1 && wstr[0] < 256) {
1303 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1304 if (latin1_char == NULL)
1305 return -1;
1306 Py_DECREF(*p_obj);
1307 *p_obj = latin1_char;
1308 return 0;
1309 }
1310 }
1311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001313 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001314 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001318 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1319 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 PyErr_NoMemory();
1321 return -1;
1322 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001323 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 _PyUnicode_WSTR(unicode), end,
1325 PyUnicode_1BYTE_DATA(unicode));
1326 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1327 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1328 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1329 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001330 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001331 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 }
1334 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001335 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8(unicode) = NULL;
1337 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 PyObject_FREE(_PyUnicode_WSTR(unicode));
1340 _PyUnicode_WSTR(unicode) = NULL;
1341 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1342 }
1343 /* In this case we might have to convert down from 4-byte native
1344 wchar_t to 2-byte unicode. */
1345 else if (maxchar < 65536) {
1346 assert(num_surrogates == 0 &&
1347 "FindMaxCharAndNumSurrogatePairs() messed up");
1348
Victor Stinner506f5922011-09-28 22:34:18 +02001349#if SIZEOF_WCHAR_T == 2
1350 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1353 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1354 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001355 _PyUnicode_UTF8(unicode) = NULL;
1356 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001357#else
1358 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001360 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001361 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001362 PyErr_NoMemory();
1363 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 }
Victor Stinner506f5922011-09-28 22:34:18 +02001365 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1366 _PyUnicode_WSTR(unicode), end,
1367 PyUnicode_2BYTE_DATA(unicode));
1368 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1369 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1370 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001371 _PyUnicode_UTF8(unicode) = NULL;
1372 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001373 PyObject_FREE(_PyUnicode_WSTR(unicode));
1374 _PyUnicode_WSTR(unicode) = NULL;
1375 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 }
1378 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1379 else {
1380#if SIZEOF_WCHAR_T == 2
1381 /* in case the native representation is 2-bytes, we need to allocate a
1382 new normalized 4-byte version. */
1383 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
1389 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001391 _PyUnicode_UTF8(unicode) = NULL;
1392 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001393 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1394 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001395 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 PyObject_FREE(_PyUnicode_WSTR(unicode));
1397 _PyUnicode_WSTR(unicode) = NULL;
1398 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1399#else
1400 assert(num_surrogates == 0);
1401
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1407#endif
1408 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1409 }
1410 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001411 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 return 0;
1413}
1414
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001415int
1416_PyUnicode_ReadyReplace(PyObject **op)
1417{
1418 return unicode_ready(op, 1);
1419}
1420
1421int
1422_PyUnicode_Ready(PyObject *op)
1423{
1424 return unicode_ready(&op, 0);
1425}
1426
Alexander Belopolsky40018472011-02-26 01:02:56 +00001427static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001428unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001429{
Walter Dörwald16807132007-05-25 13:52:07 +00001430 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001431 case SSTATE_NOT_INTERNED:
1432 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_INTERNED_MORTAL:
1435 /* revive dead object temporarily for DelItem */
1436 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001437 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 Py_FatalError(
1439 "deletion of interned string failed");
1440 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001441
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 case SSTATE_INTERNED_IMMORTAL:
1443 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 default:
1446 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447 }
1448
Victor Stinner03490912011-10-03 23:45:12 +02001449 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001451 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453
1454 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001456 }
1457 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 if (_PyUnicode_DATA_ANY(unicode))
1459 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001460 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001461 }
1462}
1463
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001464#ifdef Py_DEBUG
1465static int
1466unicode_is_singleton(PyObject *unicode)
1467{
1468 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1469 if (unicode == unicode_empty)
1470 return 1;
1471 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1472 {
1473 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1474 if (ch < 256 && unicode_latin1[ch] == unicode)
1475 return 1;
1476 }
1477 return 0;
1478}
1479#endif
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001483{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001484 if (Py_REFCNT(unicode) != 1)
1485 return 0;
1486 if (PyUnicode_CHECK_INTERNED(unicode))
1487 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001488#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001489 /* singleton refcount is greater than 1 */
1490 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001492 return 1;
1493}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001494
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495static int
1496unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1497{
1498 PyObject *unicode;
1499 Py_ssize_t old_length;
1500
1501 assert(p_unicode != NULL);
1502 unicode = *p_unicode;
1503
1504 assert(unicode != NULL);
1505 assert(PyUnicode_Check(unicode));
1506 assert(0 <= length);
1507
Victor Stinner910337b2011-10-03 03:20:16 +02001508 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 old_length = PyUnicode_WSTR_LENGTH(unicode);
1510 else
1511 old_length = PyUnicode_GET_LENGTH(unicode);
1512 if (old_length == length)
1513 return 0;
1514
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001515 if (length == 0) {
1516 Py_DECREF(*p_unicode);
1517 *p_unicode = unicode_empty;
1518 Py_INCREF(*p_unicode);
1519 return 0;
1520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (!unicode_resizable(unicode)) {
1523 PyObject *copy = resize_copy(unicode, length);
1524 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 Py_DECREF(*p_unicode);
1527 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001529 }
1530
Victor Stinnerfe226c02011-10-03 03:52:20 +02001531 if (PyUnicode_IS_COMPACT(unicode)) {
1532 *p_unicode = resize_compact(unicode, length);
1533 if (*p_unicode == NULL)
1534 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001535 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001537 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001538 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001539}
1540
Alexander Belopolsky40018472011-02-26 01:02:56 +00001541int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001543{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 PyObject *unicode;
1545 if (p_unicode == NULL) {
1546 PyErr_BadInternalCall();
1547 return -1;
1548 }
1549 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001550 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001551 {
1552 PyErr_BadInternalCall();
1553 return -1;
1554 }
1555 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001556}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001558static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001559unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001560{
1561 PyObject *result;
1562 assert(PyUnicode_IS_READY(*p_unicode));
1563 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1564 return 0;
1565 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1566 maxchar);
1567 if (result == NULL)
1568 return -1;
1569 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1570 PyUnicode_GET_LENGTH(*p_unicode));
1571 Py_DECREF(*p_unicode);
1572 *p_unicode = result;
1573 return 0;
1574}
1575
1576static int
1577unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1578 Py_UCS4 ch)
1579{
1580 if (unicode_widen(p_unicode, ch) < 0)
1581 return -1;
1582 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1583 PyUnicode_DATA(*p_unicode),
1584 (*pos)++, ch);
1585 return 0;
1586}
1587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588static PyObject*
1589get_latin1_char(unsigned char ch)
1590{
Victor Stinnera464fc12011-10-02 20:39:30 +02001591 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001593 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 if (!unicode)
1595 return NULL;
1596 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001597 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 unicode_latin1[ch] = unicode;
1599 }
1600 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001601 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602}
1603
Alexander Belopolsky40018472011-02-26 01:02:56 +00001604PyObject *
1605PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 Py_UCS4 maxchar = 0;
1609 Py_ssize_t num_surrogates;
1610
1611 if (u == NULL)
1612 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001613
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001614 /* If the Unicode data is known at construction time, we can apply
1615 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* Optimization for empty strings */
1618 if (size == 0 && unicode_empty != NULL) {
1619 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001620 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001621 }
Tim Petersced69f82003-09-16 20:30:58 +00001622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 /* Single character Unicode objects in the Latin-1 range are
1624 shared when using this constructor */
1625 if (size == 1 && *u < 256)
1626 return get_latin1_char((unsigned char)*u);
1627
1628 /* If not empty and not single character, copy the Unicode data
1629 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001630 if (find_maxchar_surrogates(u, u + size,
1631 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 return NULL;
1633
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636 if (!unicode)
1637 return NULL;
1638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 switch (PyUnicode_KIND(unicode)) {
1640 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001641 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1643 break;
1644 case PyUnicode_2BYTE_KIND:
1645#if Py_UNICODE_SIZE == 2
1646 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1647#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001648 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1650#endif
1651 break;
1652 case PyUnicode_4BYTE_KIND:
1653#if SIZEOF_WCHAR_T == 2
1654 /* This is the only case which has to process surrogates, thus
1655 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001656 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#else
1658 assert(num_surrogates == 0);
1659 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1660#endif
1661 break;
1662 default:
1663 assert(0 && "Impossible state");
1664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001665
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001666 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001672{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001673 if (size < 0) {
1674 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001676 return NULL;
1677 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001678
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001679 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001680 some optimizations which share commonly used objects.
1681 Also, this means the input must be UTF-8, so fall back to the
1682 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 if (u != NULL) {
1684
Benjamin Peterson29060642009-01-31 22:14:21 +00001685 /* Optimization for empty strings */
1686 if (size == 0 && unicode_empty != NULL) {
1687 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001688 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001690
1691 /* Single characters are shared when using this constructor.
1692 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001693 if (size == 1 && (unsigned char)*u < 128)
1694 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001695
1696 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 }
1698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001699 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001704{
1705 size_t size = strlen(u);
1706 if (size > PY_SSIZE_T_MAX) {
1707 PyErr_SetString(PyExc_OverflowError, "input too long");
1708 return NULL;
1709 }
1710
1711 return PyUnicode_FromStringAndSize(u, size);
1712}
1713
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001714PyObject *
1715_PyUnicode_FromId(_Py_Identifier *id)
1716{
1717 if (!id->object) {
1718 id->object = PyUnicode_FromString(id->string);
1719 if (!id->object)
1720 return NULL;
1721 PyUnicode_InternInPlace(&id->object);
1722 assert(!id->next);
1723 id->next = static_strings;
1724 static_strings = id;
1725 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001726 return id->object;
1727}
1728
1729void
1730_PyUnicode_ClearStaticStrings()
1731{
1732 _Py_Identifier *i;
1733 for (i = static_strings; i; i = i->next) {
1734 Py_DECREF(i->object);
1735 i->object = NULL;
1736 i->next = NULL;
1737 }
1738}
1739
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001741unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001742{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001743 PyObject *res;
1744#ifdef Py_DEBUG
1745 const unsigned char *p;
1746 const unsigned char *end = s + size;
1747 for (p=s; p < end; p++) {
1748 assert(*p < 128);
1749 }
1750#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001751 if (size == 1)
1752 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001753 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001754 if (!res)
1755 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001756 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001757 return res;
1758}
1759
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001760static Py_UCS4
1761kind_maxchar_limit(unsigned int kind)
1762{
1763 switch(kind) {
1764 case PyUnicode_1BYTE_KIND:
1765 return 0x80;
1766 case PyUnicode_2BYTE_KIND:
1767 return 0x100;
1768 case PyUnicode_4BYTE_KIND:
1769 return 0x10000;
1770 default:
1771 assert(0 && "invalid kind");
1772 return 0x10ffff;
1773 }
1774}
1775
Victor Stinner702c7342011-10-05 13:50:52 +02001776static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001777_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001779 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001780 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001781
1782 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001783 if (size == 1)
1784 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001785 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001786 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 if (!res)
1788 return NULL;
1789 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001790 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001792}
1793
Victor Stinnere57b1c02011-09-28 22:20:48 +02001794static PyObject*
1795_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796{
1797 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001798 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001799
1800 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001801 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001802 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001803 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001804 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 if (!res)
1806 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001807 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001809 else {
1810 _PyUnicode_CONVERT_BYTES(
1811 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1812 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001813 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814 return res;
1815}
1816
Victor Stinnere57b1c02011-09-28 22:20:48 +02001817static PyObject*
1818_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819{
1820 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822
1823 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001824 if (size == 1 && u[0] < 256)
1825 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001826 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001827 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 if (!res)
1829 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001830 if (max_char < 256)
1831 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1832 PyUnicode_1BYTE_DATA(res));
1833 else if (max_char < 0x10000)
1834 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1835 PyUnicode_2BYTE_DATA(res));
1836 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001838 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001839 return res;
1840}
1841
1842PyObject*
1843PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1844{
1845 switch(kind) {
1846 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001847 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001849 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001851 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001852 default:
1853 assert(0 && "invalid kind");
1854 PyErr_SetString(PyExc_SystemError, "invalid kind");
1855 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857}
1858
Victor Stinner25a4b292011-10-06 12:31:55 +02001859/* Ensure that a string uses the most efficient storage, if it is not the
1860 case: create a new string with of the right kind. Write NULL into *p_unicode
1861 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001862static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001863unicode_adjust_maxchar(PyObject **p_unicode)
1864{
1865 PyObject *unicode, *copy;
1866 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001867 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001868 unsigned int kind;
1869
1870 assert(p_unicode != NULL);
1871 unicode = *p_unicode;
1872 assert(PyUnicode_IS_READY(unicode));
1873 if (PyUnicode_IS_ASCII(unicode))
1874 return;
1875
1876 len = PyUnicode_GET_LENGTH(unicode);
1877 kind = PyUnicode_KIND(unicode);
1878 if (kind == PyUnicode_1BYTE_KIND) {
1879 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001880 max_char = ucs1lib_find_max_char(u, u + len);
1881 if (max_char >= 128)
1882 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001883 }
1884 else if (kind == PyUnicode_2BYTE_KIND) {
1885 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001886 max_char = ucs2lib_find_max_char(u, u + len);
1887 if (max_char >= 256)
1888 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001889 }
1890 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001891 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001892 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001893 max_char = ucs4lib_find_max_char(u, u + len);
1894 if (max_char >= 0x10000)
1895 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001896 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001897 copy = PyUnicode_New(len, max_char);
1898 copy_characters(copy, 0, unicode, 0, len);
1899 Py_DECREF(unicode);
1900 *p_unicode = copy;
1901}
1902
Victor Stinner034f6cf2011-09-30 02:26:44 +02001903PyObject*
1904PyUnicode_Copy(PyObject *unicode)
1905{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001906 Py_ssize_t size;
1907 PyObject *copy;
1908 void *data;
1909
Victor Stinner034f6cf2011-09-30 02:26:44 +02001910 if (!PyUnicode_Check(unicode)) {
1911 PyErr_BadInternalCall();
1912 return NULL;
1913 }
1914 if (PyUnicode_READY(unicode))
1915 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001916
1917 size = PyUnicode_GET_LENGTH(unicode);
1918 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1919 if (!copy)
1920 return NULL;
1921 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1922
1923 data = PyUnicode_DATA(unicode);
1924 switch (PyUnicode_KIND(unicode))
1925 {
1926 case PyUnicode_1BYTE_KIND:
1927 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1928 break;
1929 case PyUnicode_2BYTE_KIND:
1930 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1931 break;
1932 case PyUnicode_4BYTE_KIND:
1933 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1934 break;
1935 default:
1936 assert(0);
1937 break;
1938 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001939 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001940 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001941}
1942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943
Victor Stinnerbc603d12011-10-02 01:00:40 +02001944/* Widen Unicode objects to larger buffers. Don't write terminating null
1945 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946
1947void*
1948_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1949{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001950 Py_ssize_t len;
1951 void *result;
1952 unsigned int skind;
1953
1954 if (PyUnicode_READY(s))
1955 return NULL;
1956
1957 len = PyUnicode_GET_LENGTH(s);
1958 skind = PyUnicode_KIND(s);
1959 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001960 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961 return NULL;
1962 }
1963 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001964 case PyUnicode_2BYTE_KIND:
1965 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1966 if (!result)
1967 return PyErr_NoMemory();
1968 assert(skind == PyUnicode_1BYTE_KIND);
1969 _PyUnicode_CONVERT_BYTES(
1970 Py_UCS1, Py_UCS2,
1971 PyUnicode_1BYTE_DATA(s),
1972 PyUnicode_1BYTE_DATA(s) + len,
1973 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001975 case PyUnicode_4BYTE_KIND:
1976 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1977 if (!result)
1978 return PyErr_NoMemory();
1979 if (skind == PyUnicode_2BYTE_KIND) {
1980 _PyUnicode_CONVERT_BYTES(
1981 Py_UCS2, Py_UCS4,
1982 PyUnicode_2BYTE_DATA(s),
1983 PyUnicode_2BYTE_DATA(s) + len,
1984 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001986 else {
1987 assert(skind == PyUnicode_1BYTE_KIND);
1988 _PyUnicode_CONVERT_BYTES(
1989 Py_UCS1, Py_UCS4,
1990 PyUnicode_1BYTE_DATA(s),
1991 PyUnicode_1BYTE_DATA(s) + len,
1992 result);
1993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001995 default:
1996 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997 }
Victor Stinner01698042011-10-04 00:04:26 +02001998 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 return NULL;
2000}
2001
2002static Py_UCS4*
2003as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2004 int copy_null)
2005{
2006 int kind;
2007 void *data;
2008 Py_ssize_t len, targetlen;
2009 if (PyUnicode_READY(string) == -1)
2010 return NULL;
2011 kind = PyUnicode_KIND(string);
2012 data = PyUnicode_DATA(string);
2013 len = PyUnicode_GET_LENGTH(string);
2014 targetlen = len;
2015 if (copy_null)
2016 targetlen++;
2017 if (!target) {
2018 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2019 PyErr_NoMemory();
2020 return NULL;
2021 }
2022 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2023 if (!target) {
2024 PyErr_NoMemory();
2025 return NULL;
2026 }
2027 }
2028 else {
2029 if (targetsize < targetlen) {
2030 PyErr_Format(PyExc_SystemError,
2031 "string is longer than the buffer");
2032 if (copy_null && 0 < targetsize)
2033 target[0] = 0;
2034 return NULL;
2035 }
2036 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002037 if (kind == PyUnicode_1BYTE_KIND) {
2038 Py_UCS1 *start = (Py_UCS1 *) data;
2039 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002041 else if (kind == PyUnicode_2BYTE_KIND) {
2042 Py_UCS2 *start = (Py_UCS2 *) data;
2043 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2044 }
2045 else {
2046 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 if (copy_null)
2050 target[len] = 0;
2051 return target;
2052}
2053
2054Py_UCS4*
2055PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2056 int copy_null)
2057{
2058 if (target == NULL || targetsize < 1) {
2059 PyErr_BadInternalCall();
2060 return NULL;
2061 }
2062 return as_ucs4(string, target, targetsize, copy_null);
2063}
2064
2065Py_UCS4*
2066PyUnicode_AsUCS4Copy(PyObject *string)
2067{
2068 return as_ucs4(string, NULL, 0, 1);
2069}
2070
2071#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002072
Alexander Belopolsky40018472011-02-26 01:02:56 +00002073PyObject *
2074PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002075{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002076 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002077 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002079 PyErr_BadInternalCall();
2080 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081 }
2082
Martin v. Löwis790465f2008-04-05 20:41:37 +00002083 if (size == -1) {
2084 size = wcslen(w);
2085 }
2086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002087 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002088}
2089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002091
Walter Dörwald346737f2007-05-31 10:44:43 +00002092static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002093makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2094 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002095{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002096 *fmt++ = '%';
2097 if (width) {
2098 if (zeropad)
2099 *fmt++ = '0';
2100 fmt += sprintf(fmt, "%d", width);
2101 }
2102 if (precision)
2103 fmt += sprintf(fmt, ".%d", precision);
2104 if (longflag)
2105 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002106 else if (longlongflag) {
2107 /* longlongflag should only ever be nonzero on machines with
2108 HAVE_LONG_LONG defined */
2109#ifdef HAVE_LONG_LONG
2110 char *f = PY_FORMAT_LONG_LONG;
2111 while (*f)
2112 *fmt++ = *f++;
2113#else
2114 /* we shouldn't ever get here */
2115 assert(0);
2116 *fmt++ = 'l';
2117#endif
2118 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002119 else if (size_tflag) {
2120 char *f = PY_FORMAT_SIZE_T;
2121 while (*f)
2122 *fmt++ = *f++;
2123 }
2124 *fmt++ = c;
2125 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002126}
2127
Victor Stinner96865452011-03-01 23:44:09 +00002128/* helper for PyUnicode_FromFormatV() */
2129
2130static const char*
2131parse_format_flags(const char *f,
2132 int *p_width, int *p_precision,
2133 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2134{
2135 int width, precision, longflag, longlongflag, size_tflag;
2136
2137 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2138 f++;
2139 width = 0;
2140 while (Py_ISDIGIT((unsigned)*f))
2141 width = (width*10) + *f++ - '0';
2142 precision = 0;
2143 if (*f == '.') {
2144 f++;
2145 while (Py_ISDIGIT((unsigned)*f))
2146 precision = (precision*10) + *f++ - '0';
2147 if (*f == '%') {
2148 /* "%.3%s" => f points to "3" */
2149 f--;
2150 }
2151 }
2152 if (*f == '\0') {
2153 /* bogus format "%.1" => go backward, f points to "1" */
2154 f--;
2155 }
2156 if (p_width != NULL)
2157 *p_width = width;
2158 if (p_precision != NULL)
2159 *p_precision = precision;
2160
2161 /* Handle %ld, %lu, %lld and %llu. */
2162 longflag = 0;
2163 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002164 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002165
2166 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002167 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002168 longflag = 1;
2169 ++f;
2170 }
2171#ifdef HAVE_LONG_LONG
2172 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002173 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002174 longlongflag = 1;
2175 f += 2;
2176 }
2177#endif
2178 }
2179 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002180 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002181 size_tflag = 1;
2182 ++f;
2183 }
2184 if (p_longflag != NULL)
2185 *p_longflag = longflag;
2186 if (p_longlongflag != NULL)
2187 *p_longlongflag = longlongflag;
2188 if (p_size_tflag != NULL)
2189 *p_size_tflag = size_tflag;
2190 return f;
2191}
2192
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002193/* maximum number of characters required for output of %ld. 21 characters
2194 allows for 64-bit integers (in decimal) and an optional sign. */
2195#define MAX_LONG_CHARS 21
2196/* maximum number of characters required for output of %lld.
2197 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2198 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2199#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2200
Walter Dörwaldd2034312007-05-18 16:29:38 +00002201PyObject *
2202PyUnicode_FromFormatV(const char *format, va_list vargs)
2203{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002204 va_list count;
2205 Py_ssize_t callcount = 0;
2206 PyObject **callresults = NULL;
2207 PyObject **callresult = NULL;
2208 Py_ssize_t n = 0;
2209 int width = 0;
2210 int precision = 0;
2211 int zeropad;
2212 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002213 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002214 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002215 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2217 Py_UCS4 argmaxchar;
2218 Py_ssize_t numbersize = 0;
2219 char *numberresults = NULL;
2220 char *numberresult = NULL;
2221 Py_ssize_t i;
2222 int kind;
2223 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002224
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002225 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002226 /* step 1: count the number of %S/%R/%A/%s format specifications
2227 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2228 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002230 * also estimate a upper bound for all the number formats in the string,
2231 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002233 for (f = format; *f; f++) {
2234 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002235 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2237 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2238 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2239 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002242#ifdef HAVE_LONG_LONG
2243 if (longlongflag) {
2244 if (width < MAX_LONG_LONG_CHARS)
2245 width = MAX_LONG_LONG_CHARS;
2246 }
2247 else
2248#endif
2249 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2250 including sign. Decimal takes the most space. This
2251 isn't enough for octal. If a width is specified we
2252 need more (which we allocate later). */
2253 if (width < MAX_LONG_CHARS)
2254 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255
2256 /* account for the size + '\0' to separate numbers
2257 inside of the numberresults buffer */
2258 numbersize += (width + 1);
2259 }
2260 }
2261 else if ((unsigned char)*f > 127) {
2262 PyErr_Format(PyExc_ValueError,
2263 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2264 "string, got a non-ASCII byte: 0x%02x",
2265 (unsigned char)*f);
2266 return NULL;
2267 }
2268 }
2269 /* step 2: allocate memory for the results of
2270 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2271 if (callcount) {
2272 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2273 if (!callresults) {
2274 PyErr_NoMemory();
2275 return NULL;
2276 }
2277 callresult = callresults;
2278 }
2279 /* step 2.5: allocate memory for the results of formating numbers */
2280 if (numbersize) {
2281 numberresults = PyObject_Malloc(numbersize);
2282 if (!numberresults) {
2283 PyErr_NoMemory();
2284 goto fail;
2285 }
2286 numberresult = numberresults;
2287 }
2288
2289 /* step 3: format numbers and figure out how large a buffer we need */
2290 for (f = format; *f; f++) {
2291 if (*f == '%') {
2292 const char* p;
2293 int longflag;
2294 int longlongflag;
2295 int size_tflag;
2296 int numprinted;
2297
2298 p = f;
2299 zeropad = (f[1] == '0');
2300 f = parse_format_flags(f, &width, &precision,
2301 &longflag, &longlongflag, &size_tflag);
2302 switch (*f) {
2303 case 'c':
2304 {
2305 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002306 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 n++;
2308 break;
2309 }
2310 case '%':
2311 n++;
2312 break;
2313 case 'i':
2314 case 'd':
2315 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2316 width, precision, *f);
2317 if (longflag)
2318 numprinted = sprintf(numberresult, fmt,
2319 va_arg(count, long));
2320#ifdef HAVE_LONG_LONG
2321 else if (longlongflag)
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, PY_LONG_LONG));
2324#endif
2325 else if (size_tflag)
2326 numprinted = sprintf(numberresult, fmt,
2327 va_arg(count, Py_ssize_t));
2328 else
2329 numprinted = sprintf(numberresult, fmt,
2330 va_arg(count, int));
2331 n += numprinted;
2332 /* advance by +1 to skip over the '\0' */
2333 numberresult += (numprinted + 1);
2334 assert(*(numberresult - 1) == '\0');
2335 assert(*(numberresult - 2) != '\0');
2336 assert(numprinted >= 0);
2337 assert(numberresult <= numberresults + numbersize);
2338 break;
2339 case 'u':
2340 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2341 width, precision, 'u');
2342 if (longflag)
2343 numprinted = sprintf(numberresult, fmt,
2344 va_arg(count, unsigned long));
2345#ifdef HAVE_LONG_LONG
2346 else if (longlongflag)
2347 numprinted = sprintf(numberresult, fmt,
2348 va_arg(count, unsigned PY_LONG_LONG));
2349#endif
2350 else if (size_tflag)
2351 numprinted = sprintf(numberresult, fmt,
2352 va_arg(count, size_t));
2353 else
2354 numprinted = sprintf(numberresult, fmt,
2355 va_arg(count, unsigned int));
2356 n += numprinted;
2357 numberresult += (numprinted + 1);
2358 assert(*(numberresult - 1) == '\0');
2359 assert(*(numberresult - 2) != '\0');
2360 assert(numprinted >= 0);
2361 assert(numberresult <= numberresults + numbersize);
2362 break;
2363 case 'x':
2364 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2365 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2366 n += numprinted;
2367 numberresult += (numprinted + 1);
2368 assert(*(numberresult - 1) == '\0');
2369 assert(*(numberresult - 2) != '\0');
2370 assert(numprinted >= 0);
2371 assert(numberresult <= numberresults + numbersize);
2372 break;
2373 case 'p':
2374 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2375 /* %p is ill-defined: ensure leading 0x. */
2376 if (numberresult[1] == 'X')
2377 numberresult[1] = 'x';
2378 else if (numberresult[1] != 'x') {
2379 memmove(numberresult + 2, numberresult,
2380 strlen(numberresult) + 1);
2381 numberresult[0] = '0';
2382 numberresult[1] = 'x';
2383 numprinted += 2;
2384 }
2385 n += numprinted;
2386 numberresult += (numprinted + 1);
2387 assert(*(numberresult - 1) == '\0');
2388 assert(*(numberresult - 2) != '\0');
2389 assert(numprinted >= 0);
2390 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 break;
2392 case 's':
2393 {
2394 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002395 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002396 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2397 if (!str)
2398 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 /* since PyUnicode_DecodeUTF8 returns already flexible
2400 unicode objects, there is no need to call ready on them */
2401 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002402 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002404 /* Remember the str and switch to the next slot */
2405 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002406 break;
2407 }
2408 case 'U':
2409 {
2410 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002411 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 if (PyUnicode_READY(obj) == -1)
2413 goto fail;
2414 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002415 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002417 break;
2418 }
2419 case 'V':
2420 {
2421 PyObject *obj = va_arg(count, PyObject *);
2422 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002423 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002425 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002426 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 if (PyUnicode_READY(obj) == -1)
2428 goto fail;
2429 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002430 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002432 *callresult++ = NULL;
2433 }
2434 else {
2435 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2436 if (!str_obj)
2437 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002438 if (PyUnicode_READY(str_obj)) {
2439 Py_DECREF(str_obj);
2440 goto fail;
2441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002443 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002445 *callresult++ = str_obj;
2446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 break;
2448 }
2449 case 'S':
2450 {
2451 PyObject *obj = va_arg(count, PyObject *);
2452 PyObject *str;
2453 assert(obj);
2454 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002456 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002458 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 /* Remember the str and switch to the next slot */
2461 *callresult++ = str;
2462 break;
2463 }
2464 case 'R':
2465 {
2466 PyObject *obj = va_arg(count, PyObject *);
2467 PyObject *repr;
2468 assert(obj);
2469 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002473 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 /* Remember the repr and switch to the next slot */
2476 *callresult++ = repr;
2477 break;
2478 }
2479 case 'A':
2480 {
2481 PyObject *obj = va_arg(count, PyObject *);
2482 PyObject *ascii;
2483 assert(obj);
2484 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002488 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 /* Remember the repr and switch to the next slot */
2491 *callresult++ = ascii;
2492 break;
2493 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 default:
2495 /* if we stumble upon an unknown
2496 formatting code, copy the rest of
2497 the format string to the output
2498 string. (we cannot just skip the
2499 code, since there's no way to know
2500 what's in the argument list) */
2501 n += strlen(p);
2502 goto expand;
2503 }
2504 } else
2505 n++;
2506 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002507 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 we don't have to resize the string.
2511 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002512 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 if (!string)
2514 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 kind = PyUnicode_KIND(string);
2516 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002517 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002521 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002522 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002523
2524 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2526 /* checking for == because the last argument could be a empty
2527 string, which causes i to point to end, the assert at the end of
2528 the loop */
2529 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002530
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 switch (*f) {
2532 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002533 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 const int ordinal = va_arg(vargs, int);
2535 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002537 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002538 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002539 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 case 'p':
2543 /* unused, since we already have the result */
2544 if (*f == 'p')
2545 (void) va_arg(vargs, void *);
2546 else
2547 (void) va_arg(vargs, int);
2548 /* extract the result from numberresults and append. */
2549 for (; *numberresult; ++i, ++numberresult)
2550 PyUnicode_WRITE(kind, data, i, *numberresult);
2551 /* skip over the separating '\0' */
2552 assert(*numberresult == '\0');
2553 numberresult++;
2554 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 break;
2556 case 's':
2557 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002558 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002560 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 size = PyUnicode_GET_LENGTH(*callresult);
2562 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002563 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002565 /* We're done with the unicode()/repr() => forget it */
2566 Py_DECREF(*callresult);
2567 /* switch to next unicode()/repr() result */
2568 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
2570 }
2571 case 'U':
2572 {
2573 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 Py_ssize_t size;
2575 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2576 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002577 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002579 break;
2580 }
2581 case 'V':
2582 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002584 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002585 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 size = PyUnicode_GET_LENGTH(obj);
2588 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002589 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 size = PyUnicode_GET_LENGTH(*callresult);
2593 assert(PyUnicode_KIND(*callresult) <=
2594 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002595 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002597 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002599 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002600 break;
2601 }
2602 case 'S':
2603 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002604 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002606 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 /* unused, since we already have the result */
2608 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002610 copy_characters(string, i, *callresult, 0, size);
2611 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 /* We're done with the unicode()/repr() => forget it */
2613 Py_DECREF(*callresult);
2614 /* switch to next unicode()/repr() result */
2615 ++callresult;
2616 break;
2617 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002618 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 break;
2621 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 for (; *p; ++p, ++i)
2623 PyUnicode_WRITE(kind, data, i, *p);
2624 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 goto end;
2626 }
Victor Stinner1205f272010-09-11 00:54:47 +00002627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 else {
2629 assert(i < PyUnicode_GET_LENGTH(string));
2630 PyUnicode_WRITE(kind, data, i++, *f);
2631 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002634
Benjamin Peterson29060642009-01-31 22:14:21 +00002635 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 if (callresults)
2637 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 if (numberresults)
2639 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002640 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002641 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002642 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002643 if (callresults) {
2644 PyObject **callresult2 = callresults;
2645 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002646 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 ++callresult2;
2648 }
2649 PyObject_Free(callresults);
2650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 if (numberresults)
2652 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002654}
2655
Walter Dörwaldd2034312007-05-18 16:29:38 +00002656PyObject *
2657PyUnicode_FromFormat(const char *format, ...)
2658{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002659 PyObject* ret;
2660 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661
2662#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002663 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002664#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002665 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002666#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 ret = PyUnicode_FromFormatV(format, vargs);
2668 va_end(vargs);
2669 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670}
2671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672#ifdef HAVE_WCHAR_H
2673
Victor Stinner5593d8a2010-10-02 11:11:27 +00002674/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2675 convert a Unicode object to a wide character string.
2676
Victor Stinnerd88d9832011-09-06 02:00:05 +02002677 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678 character) required to convert the unicode object. Ignore size argument.
2679
Victor Stinnerd88d9832011-09-06 02:00:05 +02002680 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002681 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002682 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002683static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002684unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002685 wchar_t *w,
2686 Py_ssize_t size)
2687{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002688 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 const wchar_t *wstr;
2690
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002691 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 if (wstr == NULL)
2693 return -1;
2694
Victor Stinner5593d8a2010-10-02 11:11:27 +00002695 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002696 if (size > res)
2697 size = res + 1;
2698 else
2699 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002701 return res;
2702 }
2703 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002705}
2706
2707Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002708PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002709 wchar_t *w,
2710 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002711{
2712 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002713 PyErr_BadInternalCall();
2714 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002715 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002716 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717}
2718
Victor Stinner137c34c2010-09-29 10:25:54 +00002719wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002720PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002721 Py_ssize_t *size)
2722{
2723 wchar_t* buffer;
2724 Py_ssize_t buflen;
2725
2726 if (unicode == NULL) {
2727 PyErr_BadInternalCall();
2728 return NULL;
2729 }
2730
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002731 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (buflen == -1)
2733 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002734 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002735 PyErr_NoMemory();
2736 return NULL;
2737 }
2738
Victor Stinner137c34c2010-09-29 10:25:54 +00002739 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2740 if (buffer == NULL) {
2741 PyErr_NoMemory();
2742 return NULL;
2743 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002744 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 if (buflen == -1)
2746 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002747 if (size != NULL)
2748 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002749 return buffer;
2750}
2751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002753
Alexander Belopolsky40018472011-02-26 01:02:56 +00002754PyObject *
2755PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002758 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002759 PyErr_SetString(PyExc_ValueError,
2760 "chr() arg not in range(0x110000)");
2761 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002762 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 if (ordinal < 256)
2765 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 v = PyUnicode_New(1, ordinal);
2768 if (v == NULL)
2769 return NULL;
2770 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002771 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002773}
2774
Alexander Belopolsky40018472011-02-26 01:02:56 +00002775PyObject *
2776PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002778 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002779 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002780 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002781 if (PyUnicode_READY(obj))
2782 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 Py_INCREF(obj);
2784 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002785 }
2786 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002787 /* For a Unicode subtype that's not a Unicode object,
2788 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002789 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002790 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002791 PyErr_Format(PyExc_TypeError,
2792 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002793 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002794 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002795}
2796
Alexander Belopolsky40018472011-02-26 01:02:56 +00002797PyObject *
2798PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002799 const char *encoding,
2800 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002801{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002802 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002803 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002804
Guido van Rossumd57fd912000-03-10 22:53:23 +00002805 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002806 PyErr_BadInternalCall();
2807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002808 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002809
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002810 /* Decoding bytes objects is the most common case and should be fast */
2811 if (PyBytes_Check(obj)) {
2812 if (PyBytes_GET_SIZE(obj) == 0) {
2813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002814 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 }
2816 else {
2817 v = PyUnicode_Decode(
2818 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2819 encoding, errors);
2820 }
2821 return v;
2822 }
2823
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002824 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002825 PyErr_SetString(PyExc_TypeError,
2826 "decoding str is not supported");
2827 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002828 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002829
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002830 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2831 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2832 PyErr_Format(PyExc_TypeError,
2833 "coercing to str: need bytes, bytearray "
2834 "or buffer-like object, %.80s found",
2835 Py_TYPE(obj)->tp_name);
2836 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002837 }
Tim Petersced69f82003-09-16 20:30:58 +00002838
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002839 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002841 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002842 }
Tim Petersced69f82003-09-16 20:30:58 +00002843 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002844 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002845
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002846 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002847 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002848}
2849
Victor Stinner600d3be2010-06-10 12:00:55 +00002850/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002851 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2852 1 on success. */
2853static int
2854normalize_encoding(const char *encoding,
2855 char *lower,
2856 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002857{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002858 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002859 char *l;
2860 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002861
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002862 if (encoding == NULL) {
2863 strcpy(lower, "utf-8");
2864 return 1;
2865 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002866 e = encoding;
2867 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002868 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002869 while (*e) {
2870 if (l == l_end)
2871 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002872 if (Py_ISUPPER(*e)) {
2873 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002874 }
2875 else if (*e == '_') {
2876 *l++ = '-';
2877 e++;
2878 }
2879 else {
2880 *l++ = *e++;
2881 }
2882 }
2883 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002884 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002885}
2886
Alexander Belopolsky40018472011-02-26 01:02:56 +00002887PyObject *
2888PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002889 Py_ssize_t size,
2890 const char *encoding,
2891 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002892{
2893 PyObject *buffer = NULL, *unicode;
2894 Py_buffer info;
2895 char lower[11]; /* Enough for any encoding shortcut */
2896
Fred Drakee4315f52000-05-09 19:53:39 +00002897 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002898 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002899 if ((strcmp(lower, "utf-8") == 0) ||
2900 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002901 return PyUnicode_DecodeUTF8(s, size, errors);
2902 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002903 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002904 (strcmp(lower, "iso-8859-1") == 0))
2905 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002906#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002907 else if (strcmp(lower, "mbcs") == 0)
2908 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002909#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002910 else if (strcmp(lower, "ascii") == 0)
2911 return PyUnicode_DecodeASCII(s, size, errors);
2912 else if (strcmp(lower, "utf-16") == 0)
2913 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2914 else if (strcmp(lower, "utf-32") == 0)
2915 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2916 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002917
2918 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002919 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002920 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002921 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002922 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002923 if (buffer == NULL)
2924 goto onError;
2925 unicode = PyCodec_Decode(buffer, encoding, errors);
2926 if (unicode == NULL)
2927 goto onError;
2928 if (!PyUnicode_Check(unicode)) {
2929 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002930 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002931 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002932 Py_DECREF(unicode);
2933 goto onError;
2934 }
2935 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002936#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002937 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002938 Py_DECREF(unicode);
2939 return NULL;
2940 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002941#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002942 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002943 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002944
Benjamin Peterson29060642009-01-31 22:14:21 +00002945 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946 Py_XDECREF(buffer);
2947 return NULL;
2948}
2949
Alexander Belopolsky40018472011-02-26 01:02:56 +00002950PyObject *
2951PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002952 const char *encoding,
2953 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002954{
2955 PyObject *v;
2956
2957 if (!PyUnicode_Check(unicode)) {
2958 PyErr_BadArgument();
2959 goto onError;
2960 }
2961
2962 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002963 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002964
2965 /* Decode via the codec registry */
2966 v = PyCodec_Decode(unicode, encoding, errors);
2967 if (v == NULL)
2968 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002969 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002970 return v;
2971
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002973 return NULL;
2974}
2975
Alexander Belopolsky40018472011-02-26 01:02:56 +00002976PyObject *
2977PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002978 const char *encoding,
2979 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002980{
2981 PyObject *v;
2982
2983 if (!PyUnicode_Check(unicode)) {
2984 PyErr_BadArgument();
2985 goto onError;
2986 }
2987
2988 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002990
2991 /* Decode via the codec registry */
2992 v = PyCodec_Decode(unicode, encoding, errors);
2993 if (v == NULL)
2994 goto onError;
2995 if (!PyUnicode_Check(v)) {
2996 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002997 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002998 Py_TYPE(v)->tp_name);
2999 Py_DECREF(v);
3000 goto onError;
3001 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003002 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003003 return v;
3004
Benjamin Peterson29060642009-01-31 22:14:21 +00003005 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003006 return NULL;
3007}
3008
Alexander Belopolsky40018472011-02-26 01:02:56 +00003009PyObject *
3010PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003011 Py_ssize_t size,
3012 const char *encoding,
3013 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014{
3015 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003016
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017 unicode = PyUnicode_FromUnicode(s, size);
3018 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3021 Py_DECREF(unicode);
3022 return v;
3023}
3024
Alexander Belopolsky40018472011-02-26 01:02:56 +00003025PyObject *
3026PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003027 const char *encoding,
3028 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003029{
3030 PyObject *v;
3031
3032 if (!PyUnicode_Check(unicode)) {
3033 PyErr_BadArgument();
3034 goto onError;
3035 }
3036
3037 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003039
3040 /* Encode via the codec registry */
3041 v = PyCodec_Encode(unicode, encoding, errors);
3042 if (v == NULL)
3043 goto onError;
3044 return v;
3045
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003047 return NULL;
3048}
3049
Victor Stinnerad158722010-10-27 00:25:46 +00003050PyObject *
3051PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003052{
Victor Stinner99b95382011-07-04 14:23:54 +02003053#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003054 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3055 PyUnicode_GET_SIZE(unicode),
3056 NULL);
3057#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003058 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003059#else
Victor Stinner793b5312011-04-27 00:24:21 +02003060 PyInterpreterState *interp = PyThreadState_GET()->interp;
3061 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3062 cannot use it to encode and decode filenames before it is loaded. Load
3063 the Python codec requires to encode at least its own filename. Use the C
3064 version of the locale codec until the codec registry is initialized and
3065 the Python codec is loaded.
3066
3067 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3068 cannot only rely on it: check also interp->fscodec_initialized for
3069 subinterpreters. */
3070 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003071 return PyUnicode_AsEncodedString(unicode,
3072 Py_FileSystemDefaultEncoding,
3073 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003074 }
3075 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003076 /* locale encoding with surrogateescape */
3077 wchar_t *wchar;
3078 char *bytes;
3079 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003080 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003081
3082 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3083 if (wchar == NULL)
3084 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003085 bytes = _Py_wchar2char(wchar, &error_pos);
3086 if (bytes == NULL) {
3087 if (error_pos != (size_t)-1) {
3088 char *errmsg = strerror(errno);
3089 PyObject *exc = NULL;
3090 if (errmsg == NULL)
3091 errmsg = "Py_wchar2char() failed";
3092 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003093 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003094 error_pos, error_pos+1,
3095 errmsg);
3096 Py_XDECREF(exc);
3097 }
3098 else
3099 PyErr_NoMemory();
3100 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003101 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003102 }
3103 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003104
3105 bytes_obj = PyBytes_FromString(bytes);
3106 PyMem_Free(bytes);
3107 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003108 }
Victor Stinnerad158722010-10-27 00:25:46 +00003109#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003110}
3111
Alexander Belopolsky40018472011-02-26 01:02:56 +00003112PyObject *
3113PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003114 const char *encoding,
3115 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003116{
3117 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003118 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003119
Guido van Rossumd57fd912000-03-10 22:53:23 +00003120 if (!PyUnicode_Check(unicode)) {
3121 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003123 }
Fred Drakee4315f52000-05-09 19:53:39 +00003124
Fred Drakee4315f52000-05-09 19:53:39 +00003125 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003126 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003127 if ((strcmp(lower, "utf-8") == 0) ||
3128 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003129 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003130 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003131 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003132 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003133 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003134 }
Victor Stinner37296e82010-06-10 13:36:23 +00003135 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003136 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003137 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003138 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003139#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003140 else if (strcmp(lower, "mbcs") == 0)
3141 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3142 PyUnicode_GET_SIZE(unicode),
3143 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003144#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003145 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003146 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003147 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003148
3149 /* Encode via the codec registry */
3150 v = PyCodec_Encode(unicode, encoding, errors);
3151 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003152 return NULL;
3153
3154 /* The normal path */
3155 if (PyBytes_Check(v))
3156 return v;
3157
3158 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003159 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003160 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003161 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003162
3163 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3164 "encoder %s returned bytearray instead of bytes",
3165 encoding);
3166 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003167 Py_DECREF(v);
3168 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003169 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003170
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003171 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3172 Py_DECREF(v);
3173 return b;
3174 }
3175
3176 PyErr_Format(PyExc_TypeError,
3177 "encoder did not return a bytes object (type=%.400s)",
3178 Py_TYPE(v)->tp_name);
3179 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003180 return NULL;
3181}
3182
Alexander Belopolsky40018472011-02-26 01:02:56 +00003183PyObject *
3184PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003185 const char *encoding,
3186 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003187{
3188 PyObject *v;
3189
3190 if (!PyUnicode_Check(unicode)) {
3191 PyErr_BadArgument();
3192 goto onError;
3193 }
3194
3195 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003196 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003197
3198 /* Encode via the codec registry */
3199 v = PyCodec_Encode(unicode, encoding, errors);
3200 if (v == NULL)
3201 goto onError;
3202 if (!PyUnicode_Check(v)) {
3203 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003204 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003205 Py_TYPE(v)->tp_name);
3206 Py_DECREF(v);
3207 goto onError;
3208 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003210
Benjamin Peterson29060642009-01-31 22:14:21 +00003211 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003212 return NULL;
3213}
3214
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003215PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003216PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003217 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003218 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3219}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003220
Christian Heimes5894ba72007-11-04 11:43:14 +00003221PyObject*
3222PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3223{
Victor Stinner99b95382011-07-04 14:23:54 +02003224#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003225 return PyUnicode_DecodeMBCS(s, size, NULL);
3226#elif defined(__APPLE__)
3227 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3228#else
Victor Stinner793b5312011-04-27 00:24:21 +02003229 PyInterpreterState *interp = PyThreadState_GET()->interp;
3230 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3231 cannot use it to encode and decode filenames before it is loaded. Load
3232 the Python codec requires to encode at least its own filename. Use the C
3233 version of the locale codec until the codec registry is initialized and
3234 the Python codec is loaded.
3235
3236 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3237 cannot only rely on it: check also interp->fscodec_initialized for
3238 subinterpreters. */
3239 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003240 return PyUnicode_Decode(s, size,
3241 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003242 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003243 }
3244 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003245 /* locale encoding with surrogateescape */
3246 wchar_t *wchar;
3247 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003248 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003249
3250 if (s[size] != '\0' || size != strlen(s)) {
3251 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3252 return NULL;
3253 }
3254
Victor Stinner168e1172010-10-16 23:16:16 +00003255 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003256 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003257 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003258
Victor Stinner168e1172010-10-16 23:16:16 +00003259 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003260 PyMem_Free(wchar);
3261 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003262 }
Victor Stinnerad158722010-10-27 00:25:46 +00003263#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003264}
3265
Martin v. Löwis011e8422009-05-05 04:43:17 +00003266
3267int
3268PyUnicode_FSConverter(PyObject* arg, void* addr)
3269{
3270 PyObject *output = NULL;
3271 Py_ssize_t size;
3272 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003273 if (arg == NULL) {
3274 Py_DECREF(*(PyObject**)addr);
3275 return 1;
3276 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003277 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003278 output = arg;
3279 Py_INCREF(output);
3280 }
3281 else {
3282 arg = PyUnicode_FromObject(arg);
3283 if (!arg)
3284 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003285 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003286 Py_DECREF(arg);
3287 if (!output)
3288 return 0;
3289 if (!PyBytes_Check(output)) {
3290 Py_DECREF(output);
3291 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3292 return 0;
3293 }
3294 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003295 size = PyBytes_GET_SIZE(output);
3296 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003297 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003298 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003299 Py_DECREF(output);
3300 return 0;
3301 }
3302 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003303 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003304}
3305
3306
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003307int
3308PyUnicode_FSDecoder(PyObject* arg, void* addr)
3309{
3310 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003311 if (arg == NULL) {
3312 Py_DECREF(*(PyObject**)addr);
3313 return 1;
3314 }
3315 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003316 if (PyUnicode_READY(arg))
3317 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003318 output = arg;
3319 Py_INCREF(output);
3320 }
3321 else {
3322 arg = PyBytes_FromObject(arg);
3323 if (!arg)
3324 return 0;
3325 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3326 PyBytes_GET_SIZE(arg));
3327 Py_DECREF(arg);
3328 if (!output)
3329 return 0;
3330 if (!PyUnicode_Check(output)) {
3331 Py_DECREF(output);
3332 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3333 return 0;
3334 }
3335 }
Victor Stinner065836e2011-10-27 01:56:33 +02003336 if (PyUnicode_READY(output) < 0) {
3337 Py_DECREF(output);
3338 return 0;
3339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003340 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003341 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003342 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3343 Py_DECREF(output);
3344 return 0;
3345 }
3346 *(PyObject**)addr = output;
3347 return Py_CLEANUP_SUPPORTED;
3348}
3349
3350
Martin v. Löwis5b222132007-06-10 09:51:05 +00003351char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003353{
Christian Heimesf3863112007-11-22 07:46:41 +00003354 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003356 if (!PyUnicode_Check(unicode)) {
3357 PyErr_BadArgument();
3358 return NULL;
3359 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003360 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003361 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003363 if (PyUnicode_UTF8(unicode) == NULL) {
3364 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003365 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3366 if (bytes == NULL)
3367 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003368 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3369 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003370 Py_DECREF(bytes);
3371 return NULL;
3372 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003373 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3374 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3375 PyBytes_AS_STRING(bytes),
3376 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003377 Py_DECREF(bytes);
3378 }
3379
3380 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003381 *psize = PyUnicode_UTF8_LENGTH(unicode);
3382 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003383}
3384
3385char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3389}
3390
3391#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003392static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393#endif
3394
3395
3396Py_UNICODE *
3397PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003399 const unsigned char *one_byte;
3400#if SIZEOF_WCHAR_T == 4
3401 const Py_UCS2 *two_bytes;
3402#else
3403 const Py_UCS4 *four_bytes;
3404 const Py_UCS4 *ucs4_end;
3405 Py_ssize_t num_surrogates;
3406#endif
3407 wchar_t *w;
3408 wchar_t *wchar_end;
3409
3410 if (!PyUnicode_Check(unicode)) {
3411 PyErr_BadArgument();
3412 return NULL;
3413 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003414 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003415 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003416 assert(_PyUnicode_KIND(unicode) != 0);
3417 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003418
3419#ifdef Py_DEBUG
3420 ++unicode_as_unicode_calls;
3421#endif
3422
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003423 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003425 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3426 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003427 num_surrogates = 0;
3428
3429 for (; four_bytes < ucs4_end; ++four_bytes) {
3430 if (*four_bytes > 0xFFFF)
3431 ++num_surrogates;
3432 }
3433
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003434 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3435 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3436 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437 PyErr_NoMemory();
3438 return NULL;
3439 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003440 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003441
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 w = _PyUnicode_WSTR(unicode);
3443 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3444 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003445 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3446 if (*four_bytes > 0xFFFF) {
3447 /* encode surrogate pair in this case */
3448 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3449 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3450 }
3451 else
3452 *w = *four_bytes;
3453
3454 if (w > wchar_end) {
3455 assert(0 && "Miscalculated string end");
3456 }
3457 }
3458 *w = 0;
3459#else
3460 /* sizeof(wchar_t) == 4 */
3461 Py_FatalError("Impossible unicode object state, wstr and str "
3462 "should share memory already.");
3463 return NULL;
3464#endif
3465 }
3466 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003467 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3468 (_PyUnicode_LENGTH(unicode) + 1));
3469 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003470 PyErr_NoMemory();
3471 return NULL;
3472 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003473 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3474 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3475 w = _PyUnicode_WSTR(unicode);
3476 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003477
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003478 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3479 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003480 for (; w < wchar_end; ++one_byte, ++w)
3481 *w = *one_byte;
3482 /* null-terminate the wstr */
3483 *w = 0;
3484 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003485 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003487 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003488 for (; w < wchar_end; ++two_bytes, ++w)
3489 *w = *two_bytes;
3490 /* null-terminate the wstr */
3491 *w = 0;
3492#else
3493 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003494 PyObject_FREE(_PyUnicode_WSTR(unicode));
3495 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003496 Py_FatalError("Impossible unicode object state, wstr "
3497 "and str should share memory already.");
3498 return NULL;
3499#endif
3500 }
3501 else {
3502 assert(0 && "This should never happen.");
3503 }
3504 }
3505 }
3506 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003507 *size = PyUnicode_WSTR_LENGTH(unicode);
3508 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003509}
3510
Alexander Belopolsky40018472011-02-26 01:02:56 +00003511Py_UNICODE *
3512PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003514 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003515}
3516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517
Alexander Belopolsky40018472011-02-26 01:02:56 +00003518Py_ssize_t
3519PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003520{
3521 if (!PyUnicode_Check(unicode)) {
3522 PyErr_BadArgument();
3523 goto onError;
3524 }
3525 return PyUnicode_GET_SIZE(unicode);
3526
Benjamin Peterson29060642009-01-31 22:14:21 +00003527 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528 return -1;
3529}
3530
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531Py_ssize_t
3532PyUnicode_GetLength(PyObject *unicode)
3533{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003534 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003535 PyErr_BadArgument();
3536 return -1;
3537 }
3538
3539 return PyUnicode_GET_LENGTH(unicode);
3540}
3541
3542Py_UCS4
3543PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3544{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003545 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3546 PyErr_BadArgument();
3547 return (Py_UCS4)-1;
3548 }
3549 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3550 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003551 return (Py_UCS4)-1;
3552 }
3553 return PyUnicode_READ_CHAR(unicode, index);
3554}
3555
3556int
3557PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3558{
3559 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003560 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003561 return -1;
3562 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003563 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3564 PyErr_SetString(PyExc_IndexError, "string index out of range");
3565 return -1;
3566 }
3567 if (_PyUnicode_Dirty(unicode))
3568 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003569 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3570 index, ch);
3571 return 0;
3572}
3573
Alexander Belopolsky40018472011-02-26 01:02:56 +00003574const char *
3575PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003576{
Victor Stinner42cb4622010-09-01 19:39:01 +00003577 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003578}
3579
Victor Stinner554f3f02010-06-16 23:33:54 +00003580/* create or adjust a UnicodeDecodeError */
3581static void
3582make_decode_exception(PyObject **exceptionObject,
3583 const char *encoding,
3584 const char *input, Py_ssize_t length,
3585 Py_ssize_t startpos, Py_ssize_t endpos,
3586 const char *reason)
3587{
3588 if (*exceptionObject == NULL) {
3589 *exceptionObject = PyUnicodeDecodeError_Create(
3590 encoding, input, length, startpos, endpos, reason);
3591 }
3592 else {
3593 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3594 goto onError;
3595 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3596 goto onError;
3597 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3598 goto onError;
3599 }
3600 return;
3601
3602onError:
3603 Py_DECREF(*exceptionObject);
3604 *exceptionObject = NULL;
3605}
3606
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003607/* error handling callback helper:
3608 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003609 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003610 and adjust various state variables.
3611 return 0 on success, -1 on error
3612*/
3613
Alexander Belopolsky40018472011-02-26 01:02:56 +00003614static int
3615unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003616 const char *encoding, const char *reason,
3617 const char **input, const char **inend, Py_ssize_t *startinpos,
3618 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003619 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003620{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003621 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003622
3623 PyObject *restuple = NULL;
3624 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003625 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003626 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003627 Py_ssize_t requiredsize;
3628 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003629 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003630 int res = -1;
3631
Victor Stinner596a6c42011-11-09 00:02:18 +01003632 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3633 outsize = PyUnicode_GET_LENGTH(*output);
3634 else
3635 outsize = _PyUnicode_WSTR_LENGTH(*output);
3636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003638 *errorHandler = PyCodec_LookupError(errors);
3639 if (*errorHandler == NULL)
3640 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003641 }
3642
Victor Stinner554f3f02010-06-16 23:33:54 +00003643 make_decode_exception(exceptionObject,
3644 encoding,
3645 *input, *inend - *input,
3646 *startinpos, *endinpos,
3647 reason);
3648 if (*exceptionObject == NULL)
3649 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650
3651 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3652 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003654 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003655 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003656 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003657 }
3658 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003659 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003660 if (PyUnicode_READY(repunicode) < 0)
3661 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003662
3663 /* Copy back the bytes variables, which might have been modified by the
3664 callback */
3665 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3666 if (!inputobj)
3667 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003668 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003670 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003671 *input = PyBytes_AS_STRING(inputobj);
3672 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003673 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003674 /* we can DECREF safely, as the exception has another reference,
3675 so the object won't go away. */
3676 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003677
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003678 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003679 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003680 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003681 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3682 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003683 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003684
Victor Stinner596a6c42011-11-09 00:02:18 +01003685 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3686 /* need more space? (at least enough for what we
3687 have+the replacement+the rest of the string (starting
3688 at the new input position), so we won't have to check space
3689 when there are no errors in the rest of the string) */
3690 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3691 requiredsize = *outpos + replen + insize-newpos;
3692 if (requiredsize > outsize) {
3693 if (requiredsize<2*outsize)
3694 requiredsize = 2*outsize;
3695 if (unicode_resize(output, requiredsize) < 0)
3696 goto onError;
3697 }
3698 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003699 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003700 copy_characters(*output, *outpos, repunicode, 0, replen);
3701 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003702 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003703 else {
3704 wchar_t *repwstr;
3705 Py_ssize_t repwlen;
3706 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3707 if (repwstr == NULL)
3708 goto onError;
3709 /* need more space? (at least enough for what we
3710 have+the replacement+the rest of the string (starting
3711 at the new input position), so we won't have to check space
3712 when there are no errors in the rest of the string) */
3713 requiredsize = *outpos + repwlen + insize-newpos;
3714 if (requiredsize > outsize) {
3715 if (requiredsize < 2*outsize)
3716 requiredsize = 2*outsize;
3717 if (unicode_resize(output, requiredsize) < 0)
3718 goto onError;
3719 }
3720 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3721 *outpos += repwlen;
3722 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003723 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003724 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003725
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003726 /* we made it! */
3727 res = 0;
3728
Benjamin Peterson29060642009-01-31 22:14:21 +00003729 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003730 Py_XDECREF(restuple);
3731 return res;
3732}
3733
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003734/* --- UTF-7 Codec -------------------------------------------------------- */
3735
Antoine Pitrou244651a2009-05-04 18:56:13 +00003736/* See RFC2152 for details. We encode conservatively and decode liberally. */
3737
3738/* Three simple macros defining base-64. */
3739
3740/* Is c a base-64 character? */
3741
3742#define IS_BASE64(c) \
3743 (((c) >= 'A' && (c) <= 'Z') || \
3744 ((c) >= 'a' && (c) <= 'z') || \
3745 ((c) >= '0' && (c) <= '9') || \
3746 (c) == '+' || (c) == '/')
3747
3748/* given that c is a base-64 character, what is its base-64 value? */
3749
3750#define FROM_BASE64(c) \
3751 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3752 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3753 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3754 (c) == '+' ? 62 : 63)
3755
3756/* What is the base-64 character of the bottom 6 bits of n? */
3757
3758#define TO_BASE64(n) \
3759 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3760
3761/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3762 * decoded as itself. We are permissive on decoding; the only ASCII
3763 * byte not decoding to itself is the + which begins a base64
3764 * string. */
3765
3766#define DECODE_DIRECT(c) \
3767 ((c) <= 127 && (c) != '+')
3768
3769/* The UTF-7 encoder treats ASCII characters differently according to
3770 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3771 * the above). See RFC2152. This array identifies these different
3772 * sets:
3773 * 0 : "Set D"
3774 * alphanumeric and '(),-./:?
3775 * 1 : "Set O"
3776 * !"#$%&*;<=>@[]^_`{|}
3777 * 2 : "whitespace"
3778 * ht nl cr sp
3779 * 3 : special (must be base64 encoded)
3780 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3781 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003782
Tim Petersced69f82003-09-16 20:30:58 +00003783static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003784char utf7_category[128] = {
3785/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3786 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3787/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3788 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3789/* sp ! " # $ % & ' ( ) * + , - . / */
3790 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3791/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3792 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3793/* @ A B C D E F G H I J K L M N O */
3794 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3795/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3796 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3797/* ` a b c d e f g h i j k l m n o */
3798 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3799/* p q r s t u v w x y z { | } ~ del */
3800 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003801};
3802
Antoine Pitrou244651a2009-05-04 18:56:13 +00003803/* ENCODE_DIRECT: this character should be encoded as itself. The
3804 * answer depends on whether we are encoding set O as itself, and also
3805 * on whether we are encoding whitespace as itself. RFC2152 makes it
3806 * clear that the answers to these questions vary between
3807 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003808
Antoine Pitrou244651a2009-05-04 18:56:13 +00003809#define ENCODE_DIRECT(c, directO, directWS) \
3810 ((c) < 128 && (c) > 0 && \
3811 ((utf7_category[(c)] == 0) || \
3812 (directWS && (utf7_category[(c)] == 2)) || \
3813 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003814
Alexander Belopolsky40018472011-02-26 01:02:56 +00003815PyObject *
3816PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003817 Py_ssize_t size,
3818 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003819{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003820 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3821}
3822
Antoine Pitrou244651a2009-05-04 18:56:13 +00003823/* The decoder. The only state we preserve is our read position,
3824 * i.e. how many characters we have consumed. So if we end in the
3825 * middle of a shift sequence we have to back off the read position
3826 * and the output to the beginning of the sequence, otherwise we lose
3827 * all the shift state (seen bits, number of bits seen, high
3828 * surrogate). */
3829
Alexander Belopolsky40018472011-02-26 01:02:56 +00003830PyObject *
3831PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003832 Py_ssize_t size,
3833 const char *errors,
3834 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003835{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003836 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003837 Py_ssize_t startinpos;
3838 Py_ssize_t endinpos;
3839 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003840 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003841 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003842 const char *errmsg = "";
3843 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003844 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003845 unsigned int base64bits = 0;
3846 unsigned long base64buffer = 0;
3847 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003848 PyObject *errorHandler = NULL;
3849 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003850
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003851 /* Start off assuming it's all ASCII. Widen later as necessary. */
3852 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003853 if (!unicode)
3854 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003855 if (size == 0) {
3856 if (consumed)
3857 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003858 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003859 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003860
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003861 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 e = s + size;
3863
3864 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003865 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003866 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003867 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868
Antoine Pitrou244651a2009-05-04 18:56:13 +00003869 if (inShift) { /* in a base-64 section */
3870 if (IS_BASE64(ch)) { /* consume a base-64 character */
3871 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3872 base64bits += 6;
3873 s++;
3874 if (base64bits >= 16) {
3875 /* we have enough bits for a UTF-16 value */
3876 Py_UNICODE outCh = (Py_UNICODE)
3877 (base64buffer >> (base64bits-16));
3878 base64bits -= 16;
3879 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3880 if (surrogate) {
3881 /* expecting a second surrogate */
3882 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003883 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3884 | (outCh & 0x3FF)) + 0x10000;
3885 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3886 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003887 surrogate = 0;
3888 }
3889 else {
3890 surrogate = 0;
3891 errmsg = "second surrogate missing";
3892 goto utf7Error;
3893 }
3894 }
3895 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3896 /* first surrogate */
3897 surrogate = outCh;
3898 }
3899 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3900 errmsg = "unexpected second surrogate";
3901 goto utf7Error;
3902 }
3903 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003904 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3905 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003906 }
3907 }
3908 }
3909 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003910 inShift = 0;
3911 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003912 if (surrogate) {
3913 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003914 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003915 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003916 if (base64bits > 0) { /* left-over bits */
3917 if (base64bits >= 6) {
3918 /* We've seen at least one base-64 character */
3919 errmsg = "partial character in shift sequence";
3920 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003921 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003922 else {
3923 /* Some bits remain; they should be zero */
3924 if (base64buffer != 0) {
3925 errmsg = "non-zero padding bits in shift sequence";
3926 goto utf7Error;
3927 }
3928 }
3929 }
3930 if (ch != '-') {
3931 /* '-' is absorbed; other terminating
3932 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003933 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3934 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003935 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003936 }
3937 }
3938 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003939 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003940 s++; /* consume '+' */
3941 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003942 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003943 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3944 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003945 }
3946 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003947 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003948 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003949 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003950 }
3951 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003952 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003953 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3954 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003955 s++;
3956 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003957 else {
3958 startinpos = s-starts;
3959 s++;
3960 errmsg = "unexpected special character";
3961 goto utf7Error;
3962 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003963 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003964utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003965 endinpos = s-starts;
3966 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003967 errors, &errorHandler,
3968 "utf7", errmsg,
3969 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003970 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003971 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003972 }
3973
Antoine Pitrou244651a2009-05-04 18:56:13 +00003974 /* end of string */
3975
3976 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3977 /* if we're in an inconsistent state, that's an error */
3978 if (surrogate ||
3979 (base64bits >= 6) ||
3980 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003981 endinpos = size;
3982 if (unicode_decode_call_errorhandler(
3983 errors, &errorHandler,
3984 "utf7", "unterminated shift sequence",
3985 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003986 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003987 goto onError;
3988 if (s < e)
3989 goto restart;
3990 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003991 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003992
3993 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003994 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003996 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003997 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003998 }
3999 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004000 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004001 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004002 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004003
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004004 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004005 goto onError;
4006
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004007 Py_XDECREF(errorHandler);
4008 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004009#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004010 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 Py_DECREF(unicode);
4012 return NULL;
4013 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004014#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004015 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004016 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004017
Benjamin Peterson29060642009-01-31 22:14:21 +00004018 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004019 Py_XDECREF(errorHandler);
4020 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004021 Py_DECREF(unicode);
4022 return NULL;
4023}
4024
4025
Alexander Belopolsky40018472011-02-26 01:02:56 +00004026PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004027_PyUnicode_EncodeUTF7(PyObject *str,
4028 int base64SetO,
4029 int base64WhiteSpace,
4030 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004031{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004032 int kind;
4033 void *data;
4034 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004035 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004036 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004037 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004038 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004039 unsigned int base64bits = 0;
4040 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004041 char * out;
4042 char * start;
4043
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004044 if (PyUnicode_READY(str) < 0)
4045 return NULL;
4046 kind = PyUnicode_KIND(str);
4047 data = PyUnicode_DATA(str);
4048 len = PyUnicode_GET_LENGTH(str);
4049
4050 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004051 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004052
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004053 /* It might be possible to tighten this worst case */
4054 allocated = 8 * len;
4055 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004056 return PyErr_NoMemory();
4057
Antoine Pitrou244651a2009-05-04 18:56:13 +00004058 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004059 if (v == NULL)
4060 return NULL;
4061
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004062 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004063 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004064 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004065
Antoine Pitrou244651a2009-05-04 18:56:13 +00004066 if (inShift) {
4067 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4068 /* shifting out */
4069 if (base64bits) { /* output remaining bits */
4070 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4071 base64buffer = 0;
4072 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004073 }
4074 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004075 /* Characters not in the BASE64 set implicitly unshift the sequence
4076 so no '-' is required, except if the character is itself a '-' */
4077 if (IS_BASE64(ch) || ch == '-') {
4078 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004079 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004080 *out++ = (char) ch;
4081 }
4082 else {
4083 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004084 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004085 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004086 else { /* not in a shift sequence */
4087 if (ch == '+') {
4088 *out++ = '+';
4089 *out++ = '-';
4090 }
4091 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4092 *out++ = (char) ch;
4093 }
4094 else {
4095 *out++ = '+';
4096 inShift = 1;
4097 goto encode_char;
4098 }
4099 }
4100 continue;
4101encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004102 if (ch >= 0x10000) {
4103 /* code first surrogate */
4104 base64bits += 16;
4105 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4106 while (base64bits >= 6) {
4107 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4108 base64bits -= 6;
4109 }
4110 /* prepare second surrogate */
4111 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4112 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004113 base64bits += 16;
4114 base64buffer = (base64buffer << 16) | ch;
4115 while (base64bits >= 6) {
4116 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4117 base64bits -= 6;
4118 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004119 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004120 if (base64bits)
4121 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4122 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004123 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004124 if (_PyBytes_Resize(&v, out - start) < 0)
4125 return NULL;
4126 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004127}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004128PyObject *
4129PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4130 Py_ssize_t size,
4131 int base64SetO,
4132 int base64WhiteSpace,
4133 const char *errors)
4134{
4135 PyObject *result;
4136 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4137 if (tmp == NULL)
4138 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004139 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004140 base64WhiteSpace, errors);
4141 Py_DECREF(tmp);
4142 return result;
4143}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004144
Antoine Pitrou244651a2009-05-04 18:56:13 +00004145#undef IS_BASE64
4146#undef FROM_BASE64
4147#undef TO_BASE64
4148#undef DECODE_DIRECT
4149#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004150
Guido van Rossumd57fd912000-03-10 22:53:23 +00004151/* --- UTF-8 Codec -------------------------------------------------------- */
4152
Tim Petersced69f82003-09-16 20:30:58 +00004153static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004154char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004155 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4156 illegal prefix. See RFC 3629 for details */
4157 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4158 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004159 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004160 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4162 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4163 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004164 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4165 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 +00004166 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4167 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4169 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4170 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4171 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4172 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 +00004173};
4174
Alexander Belopolsky40018472011-02-26 01:02:56 +00004175PyObject *
4176PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004177 Py_ssize_t size,
4178 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004179{
Walter Dörwald69652032004-09-07 20:24:22 +00004180 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4181}
4182
Antoine Pitrouab868312009-01-10 15:40:25 +00004183/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4184#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4185
4186/* Mask to quickly check whether a C 'long' contains a
4187 non-ASCII, UTF8-encoded char. */
4188#if (SIZEOF_LONG == 8)
4189# define ASCII_CHAR_MASK 0x8080808080808080L
4190#elif (SIZEOF_LONG == 4)
4191# define ASCII_CHAR_MASK 0x80808080L
4192#else
4193# error C 'long' size should be either 4 or 8!
4194#endif
4195
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004196/* Scans a UTF-8 string and returns the maximum character to be expected,
4197 the size of the decoded unicode string and if any major errors were
4198 encountered.
4199
4200 This function does check basic UTF-8 sanity, it does however NOT CHECK
4201 if the string contains surrogates, and if all continuation bytes are
4202 within the correct ranges, these checks are performed in
4203 PyUnicode_DecodeUTF8Stateful.
4204
4205 If it sets has_errors to 1, it means the value of unicode_size and max_char
4206 will be bogus and you should not rely on useful information in them.
4207 */
4208static Py_UCS4
4209utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4210 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4211 int *has_errors)
4212{
4213 Py_ssize_t n;
4214 Py_ssize_t char_count = 0;
4215 Py_UCS4 max_char = 127, new_max;
4216 Py_UCS4 upper_bound;
4217 const unsigned char *p = (const unsigned char *)s;
4218 const unsigned char *end = p + string_size;
4219 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4220 int err = 0;
4221
4222 for (; p < end && !err; ++p, ++char_count) {
4223 /* Only check value if it's not a ASCII char... */
4224 if (*p < 0x80) {
4225 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4226 an explanation. */
4227 if (!((size_t) p & LONG_PTR_MASK)) {
4228 /* Help register allocation */
4229 register const unsigned char *_p = p;
4230 while (_p < aligned_end) {
4231 unsigned long value = *(unsigned long *) _p;
4232 if (value & ASCII_CHAR_MASK)
4233 break;
4234 _p += SIZEOF_LONG;
4235 char_count += SIZEOF_LONG;
4236 }
4237 p = _p;
4238 if (p == end)
4239 break;
4240 }
4241 }
4242 if (*p >= 0x80) {
4243 n = utf8_code_length[*p];
4244 new_max = max_char;
4245 switch (n) {
4246 /* invalid start byte */
4247 case 0:
4248 err = 1;
4249 break;
4250 case 2:
4251 /* Code points between 0x00FF and 0x07FF inclusive.
4252 Approximate the upper bound of the code point,
4253 if this flips over 255 we can be sure it will be more
4254 than 255 and the string will need 2 bytes per code coint,
4255 if it stays under or equal to 255, we can be sure 1 byte
4256 is enough.
4257 ((*p & 0b00011111) << 6) | 0b00111111 */
4258 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4259 if (max_char < upper_bound)
4260 new_max = upper_bound;
4261 /* Ensure we track at least that we left ASCII space. */
4262 if (new_max < 128)
4263 new_max = 128;
4264 break;
4265 case 3:
4266 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4267 always > 255 and <= 65535 and will always need 2 bytes. */
4268 if (max_char < 65535)
4269 new_max = 65535;
4270 break;
4271 case 4:
4272 /* Code point will be above 0xFFFF for sure in this case. */
4273 new_max = 65537;
4274 break;
4275 /* Internal error, this should be caught by the first if */
4276 case 1:
4277 default:
4278 assert(0 && "Impossible case in utf8_max_char_and_size");
4279 err = 1;
4280 }
4281 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004282 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004283 --n;
4284 /* Check if the follow up chars are all valid continuation bytes */
4285 if (n >= 1) {
4286 const unsigned char *cont;
4287 if ((p + n) >= end) {
4288 if (consumed == 0)
4289 /* incomplete data, non-incremental decoding */
4290 err = 1;
4291 break;
4292 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004293 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004294 if ((*cont & 0xc0) != 0x80) {
4295 err = 1;
4296 break;
4297 }
4298 }
4299 p += n;
4300 }
4301 else
4302 err = 1;
4303 max_char = new_max;
4304 }
4305 }
4306
4307 if (unicode_size)
4308 *unicode_size = char_count;
4309 if (has_errors)
4310 *has_errors = err;
4311 return max_char;
4312}
4313
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004314/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4315 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4316 onError. Potential resizing overallocates, so the result needs to shrink
4317 at the end.
4318*/
4319#define WRITE_MAYBE_FAIL(index, value) \
4320 do { \
4321 if (has_errors) { \
4322 Py_ssize_t pos = index; \
4323 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4324 unicode_resize(&unicode, pos + pos/8) < 0) \
4325 goto onError; \
4326 if (unicode_putchar(&unicode, &pos, value) < 0) \
4327 goto onError; \
4328 } \
4329 else \
4330 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004331 } while (0)
4332
Alexander Belopolsky40018472011-02-26 01:02:56 +00004333PyObject *
4334PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004335 Py_ssize_t size,
4336 const char *errors,
4337 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004338{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004339 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004340 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004341 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004342 Py_ssize_t startinpos;
4343 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004344 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004345 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004346 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004347 PyObject *errorHandler = NULL;
4348 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004349 Py_UCS4 maxchar = 0;
4350 Py_ssize_t unicode_size;
4351 Py_ssize_t i;
4352 int kind;
4353 void *data;
4354 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004355
Walter Dörwald69652032004-09-07 20:24:22 +00004356 if (size == 0) {
4357 if (consumed)
4358 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004359 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004360 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004361 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4362 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004363 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004364 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004365 code below widens and resizes as necessary. */
4366 unicode = PyUnicode_New(size, 127);
4367 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004368 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004369 if (!unicode)
4370 return NULL;
4371 /* When the string is ASCII only, just use memcpy and return.
4372 unicode_size may be != size if there is an incomplete UTF-8
4373 sequence at the end of the ASCII block. */
4374 if (!has_errors && maxchar < 128 && size == unicode_size) {
4375 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4376 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004377 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004378 kind = PyUnicode_KIND(unicode);
4379 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004380 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004381 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004382 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004383 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004384
4385 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004386 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004387
4388 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004389 /* Fast path for runs of ASCII characters. Given that common UTF-8
4390 input will consist of an overwhelming majority of ASCII
4391 characters, we try to optimize for this case by checking
4392 as many characters as a C 'long' can contain.
4393 First, check if we can do an aligned read, as most CPUs have
4394 a penalty for unaligned reads.
4395 */
4396 if (!((size_t) s & LONG_PTR_MASK)) {
4397 /* Help register allocation */
4398 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004399 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004400 while (_s < aligned_end) {
4401 /* Read a whole long at a time (either 4 or 8 bytes),
4402 and do a fast unrolled copy if it only contains ASCII
4403 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004404 unsigned long value = *(unsigned long *) _s;
4405 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004406 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004407 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4408 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4409 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4410 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004411#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004412 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4413 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4414 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4415 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004416#endif
4417 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004418 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004419 }
4420 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004421 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004422 if (s == e)
4423 break;
4424 ch = (unsigned char)*s;
4425 }
4426 }
4427
4428 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004429 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004430 s++;
4431 continue;
4432 }
4433
4434 n = utf8_code_length[ch];
4435
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004436 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004437 if (consumed)
4438 break;
4439 else {
4440 errmsg = "unexpected end of data";
4441 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004442 endinpos = startinpos+1;
4443 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4444 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004445 goto utf8Error;
4446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004447 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004448
4449 switch (n) {
4450
4451 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004452 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004453 startinpos = s-starts;
4454 endinpos = startinpos+1;
4455 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004456
4457 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004458 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004459 startinpos = s-starts;
4460 endinpos = startinpos+1;
4461 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004462
4463 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004464 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004465 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004466 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004467 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004468 goto utf8Error;
4469 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004471 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004472 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004473 break;
4474
4475 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004476 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4477 will result in surrogates in range d800-dfff. Surrogates are
4478 not valid UTF-8 so they are rejected.
4479 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4480 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004481 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004482 (s[2] & 0xc0) != 0x80 ||
4483 ((unsigned char)s[0] == 0xE0 &&
4484 (unsigned char)s[1] < 0xA0) ||
4485 ((unsigned char)s[0] == 0xED &&
4486 (unsigned char)s[1] > 0x9F)) {
4487 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004488 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004489 endinpos = startinpos + 1;
4490
4491 /* if s[1] first two bits are 1 and 0, then the invalid
4492 continuation byte is s[2], so increment endinpos by 1,
4493 if not, s[1] is invalid and endinpos doesn't need to
4494 be incremented. */
4495 if ((s[1] & 0xC0) == 0x80)
4496 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004497 goto utf8Error;
4498 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004499 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004500 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004501 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004502 break;
4503
4504 case 4:
4505 if ((s[1] & 0xc0) != 0x80 ||
4506 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004507 (s[3] & 0xc0) != 0x80 ||
4508 ((unsigned char)s[0] == 0xF0 &&
4509 (unsigned char)s[1] < 0x90) ||
4510 ((unsigned char)s[0] == 0xF4 &&
4511 (unsigned char)s[1] > 0x8F)) {
4512 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004513 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004514 endinpos = startinpos + 1;
4515 if ((s[1] & 0xC0) == 0x80) {
4516 endinpos++;
4517 if ((s[2] & 0xC0) == 0x80)
4518 endinpos++;
4519 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004520 goto utf8Error;
4521 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004522 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004523 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4524 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4525
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004526 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004527 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004528 }
4529 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004530 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004531
Benjamin Peterson29060642009-01-31 22:14:21 +00004532 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004533 if (!has_errors) {
4534 PyObject *tmp;
4535 Py_ssize_t k;
4536 /* We encountered some error that wasn't detected in the original scan,
4537 e.g. an encoded surrogate character. The original maxchar computation may
4538 have been incorrect, so redo it now. */
4539 for (k = 0, maxchar = 0; k < i; k++)
4540 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4541 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4542 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004543 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004544 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004545 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004546 unicode = tmp;
4547 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004548 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004549 if (unicode_decode_call_errorhandler(
4550 errors, &errorHandler,
4551 "utf8", errmsg,
4552 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004553 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004554 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004555 /* Update data because unicode_decode_call_errorhandler might have
4556 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004557 data = PyUnicode_DATA(unicode);
4558 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004559 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004560 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004561 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004562 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004563
Walter Dörwald69652032004-09-07 20:24:22 +00004564 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004565 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004566
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004567 /* Adjust length and ready string when it contained errors and
4568 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004569 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004570 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004571 goto onError;
4572 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004573
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004574 Py_XDECREF(errorHandler);
4575 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004576 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004577 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004578
Benjamin Peterson29060642009-01-31 22:14:21 +00004579 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004580 Py_XDECREF(errorHandler);
4581 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004582 Py_DECREF(unicode);
4583 return NULL;
4584}
4585
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004586#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004587
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004588#ifdef __APPLE__
4589
4590/* Simplified UTF-8 decoder using surrogateescape error handler,
4591 used to decode the command line arguments on Mac OS X. */
4592
4593wchar_t*
4594_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4595{
4596 int n;
4597 const char *e;
4598 wchar_t *unicode, *p;
4599
4600 /* Note: size will always be longer than the resulting Unicode
4601 character count */
4602 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4603 PyErr_NoMemory();
4604 return NULL;
4605 }
4606 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4607 if (!unicode)
4608 return NULL;
4609
4610 /* Unpack UTF-8 encoded data */
4611 p = unicode;
4612 e = s + size;
4613 while (s < e) {
4614 Py_UCS4 ch = (unsigned char)*s;
4615
4616 if (ch < 0x80) {
4617 *p++ = (wchar_t)ch;
4618 s++;
4619 continue;
4620 }
4621
4622 n = utf8_code_length[ch];
4623 if (s + n > e) {
4624 goto surrogateescape;
4625 }
4626
4627 switch (n) {
4628 case 0:
4629 case 1:
4630 goto surrogateescape;
4631
4632 case 2:
4633 if ((s[1] & 0xc0) != 0x80)
4634 goto surrogateescape;
4635 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4636 assert ((ch > 0x007F) && (ch <= 0x07FF));
4637 *p++ = (wchar_t)ch;
4638 break;
4639
4640 case 3:
4641 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4642 will result in surrogates in range d800-dfff. Surrogates are
4643 not valid UTF-8 so they are rejected.
4644 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4645 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4646 if ((s[1] & 0xc0) != 0x80 ||
4647 (s[2] & 0xc0) != 0x80 ||
4648 ((unsigned char)s[0] == 0xE0 &&
4649 (unsigned char)s[1] < 0xA0) ||
4650 ((unsigned char)s[0] == 0xED &&
4651 (unsigned char)s[1] > 0x9F)) {
4652
4653 goto surrogateescape;
4654 }
4655 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4656 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004657 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004658 break;
4659
4660 case 4:
4661 if ((s[1] & 0xc0) != 0x80 ||
4662 (s[2] & 0xc0) != 0x80 ||
4663 (s[3] & 0xc0) != 0x80 ||
4664 ((unsigned char)s[0] == 0xF0 &&
4665 (unsigned char)s[1] < 0x90) ||
4666 ((unsigned char)s[0] == 0xF4 &&
4667 (unsigned char)s[1] > 0x8F)) {
4668 goto surrogateescape;
4669 }
4670 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4671 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4672 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4673
4674#if SIZEOF_WCHAR_T == 4
4675 *p++ = (wchar_t)ch;
4676#else
4677 /* compute and append the two surrogates: */
4678
4679 /* translate from 10000..10FFFF to 0..FFFF */
4680 ch -= 0x10000;
4681
4682 /* high surrogate = top 10 bits added to D800 */
4683 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4684
4685 /* low surrogate = bottom 10 bits added to DC00 */
4686 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4687#endif
4688 break;
4689 }
4690 s += n;
4691 continue;
4692
4693 surrogateescape:
4694 *p++ = 0xDC00 + ch;
4695 s++;
4696 }
4697 *p = L'\0';
4698 return unicode;
4699}
4700
4701#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004703/* Primary internal function which creates utf8 encoded bytes objects.
4704
4705 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004706 and allocate exactly as much space needed at the end. Else allocate the
4707 maximum possible needed (4 result bytes per Unicode character), and return
4708 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004709*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004710PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004711_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004712{
Tim Peters602f7402002-04-27 18:03:26 +00004713#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004714
Guido van Rossum98297ee2007-11-06 21:34:58 +00004715 Py_ssize_t i; /* index into s of next input byte */
4716 PyObject *result; /* result string object */
4717 char *p; /* next free byte in output buffer */
4718 Py_ssize_t nallocated; /* number of result bytes allocated */
4719 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004720 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004721 PyObject *errorHandler = NULL;
4722 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004723 int kind;
4724 void *data;
4725 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004726
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004727 if (!PyUnicode_Check(unicode)) {
4728 PyErr_BadArgument();
4729 return NULL;
4730 }
4731
4732 if (PyUnicode_READY(unicode) == -1)
4733 return NULL;
4734
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004735 if (PyUnicode_UTF8(unicode))
4736 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4737 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004738
4739 kind = PyUnicode_KIND(unicode);
4740 data = PyUnicode_DATA(unicode);
4741 size = PyUnicode_GET_LENGTH(unicode);
4742
Tim Peters602f7402002-04-27 18:03:26 +00004743 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004744
Tim Peters602f7402002-04-27 18:03:26 +00004745 if (size <= MAX_SHORT_UNICHARS) {
4746 /* Write into the stack buffer; nallocated can't overflow.
4747 * At the end, we'll allocate exactly as much heap space as it
4748 * turns out we need.
4749 */
4750 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004751 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004752 p = stackbuf;
4753 }
4754 else {
4755 /* Overallocate on the heap, and give the excess back at the end. */
4756 nallocated = size * 4;
4757 if (nallocated / 4 != size) /* overflow! */
4758 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004759 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004760 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004761 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004762 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004763 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004764
Tim Peters602f7402002-04-27 18:03:26 +00004765 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004766 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004767
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004768 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004769 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004770 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004771
Guido van Rossumd57fd912000-03-10 22:53:23 +00004772 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004773 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004774 *p++ = (char)(0xc0 | (ch >> 6));
4775 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004776 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004777 Py_ssize_t newpos;
4778 PyObject *rep;
4779 Py_ssize_t repsize, k, startpos;
4780 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004781 rep = unicode_encode_call_errorhandler(
4782 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004783 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004784 if (!rep)
4785 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004786
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004787 if (PyBytes_Check(rep))
4788 repsize = PyBytes_GET_SIZE(rep);
4789 else
4790 repsize = PyUnicode_GET_SIZE(rep);
4791
4792 if (repsize > 4) {
4793 Py_ssize_t offset;
4794
4795 if (result == NULL)
4796 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004797 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004798 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004800 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4801 /* integer overflow */
4802 PyErr_NoMemory();
4803 goto error;
4804 }
4805 nallocated += repsize - 4;
4806 if (result != NULL) {
4807 if (_PyBytes_Resize(&result, nallocated) < 0)
4808 goto error;
4809 } else {
4810 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004811 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004812 goto error;
4813 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4814 }
4815 p = PyBytes_AS_STRING(result) + offset;
4816 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004818 if (PyBytes_Check(rep)) {
4819 char *prep = PyBytes_AS_STRING(rep);
4820 for(k = repsize; k > 0; k--)
4821 *p++ = *prep++;
4822 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004823 enum PyUnicode_Kind repkind;
4824 void *repdata;
4825
4826 if (PyUnicode_READY(rep) < 0) {
4827 Py_DECREF(rep);
4828 goto error;
4829 }
4830 repkind = PyUnicode_KIND(rep);
4831 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004832
4833 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004834 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004835 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004836 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004837 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004838 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004839 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004840 goto error;
4841 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004842 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004843 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004844 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004845 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004846 } else if (ch < 0x10000) {
4847 *p++ = (char)(0xe0 | (ch >> 12));
4848 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4849 *p++ = (char)(0x80 | (ch & 0x3f));
4850 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004851 /* Encode UCS4 Unicode ordinals */
4852 *p++ = (char)(0xf0 | (ch >> 18));
4853 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4854 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4855 *p++ = (char)(0x80 | (ch & 0x3f));
4856 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004857 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004858
Guido van Rossum98297ee2007-11-06 21:34:58 +00004859 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004860 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004861 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004862 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004863 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004864 }
4865 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004866 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004867 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004868 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004869 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004870 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004871
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004872 Py_XDECREF(errorHandler);
4873 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004874 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004875 error:
4876 Py_XDECREF(errorHandler);
4877 Py_XDECREF(exc);
4878 Py_XDECREF(result);
4879 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004880
Tim Peters602f7402002-04-27 18:03:26 +00004881#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004882}
4883
Alexander Belopolsky40018472011-02-26 01:02:56 +00004884PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004885PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4886 Py_ssize_t size,
4887 const char *errors)
4888{
4889 PyObject *v, *unicode;
4890
4891 unicode = PyUnicode_FromUnicode(s, size);
4892 if (unicode == NULL)
4893 return NULL;
4894 v = _PyUnicode_AsUTF8String(unicode, errors);
4895 Py_DECREF(unicode);
4896 return v;
4897}
4898
4899PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004900PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004901{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004902 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004903}
4904
Walter Dörwald41980ca2007-08-16 21:55:45 +00004905/* --- UTF-32 Codec ------------------------------------------------------- */
4906
4907PyObject *
4908PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004909 Py_ssize_t size,
4910 const char *errors,
4911 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004912{
4913 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4914}
4915
4916PyObject *
4917PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004918 Py_ssize_t size,
4919 const char *errors,
4920 int *byteorder,
4921 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004922{
4923 const char *starts = s;
4924 Py_ssize_t startinpos;
4925 Py_ssize_t endinpos;
4926 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004927 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004928 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004929 int bo = 0; /* assume native ordering by default */
4930 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004931 /* Offsets from q for retrieving bytes in the right order. */
4932#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4933 int iorder[] = {0, 1, 2, 3};
4934#else
4935 int iorder[] = {3, 2, 1, 0};
4936#endif
4937 PyObject *errorHandler = NULL;
4938 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004939
Walter Dörwald41980ca2007-08-16 21:55:45 +00004940 q = (unsigned char *)s;
4941 e = q + size;
4942
4943 if (byteorder)
4944 bo = *byteorder;
4945
4946 /* Check for BOM marks (U+FEFF) in the input and adjust current
4947 byte order setting accordingly. In native mode, the leading BOM
4948 mark is skipped, in all other modes, it is copied to the output
4949 stream as-is (giving a ZWNBSP character). */
4950 if (bo == 0) {
4951 if (size >= 4) {
4952 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004953 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004954#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004955 if (bom == 0x0000FEFF) {
4956 q += 4;
4957 bo = -1;
4958 }
4959 else if (bom == 0xFFFE0000) {
4960 q += 4;
4961 bo = 1;
4962 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004963#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004964 if (bom == 0x0000FEFF) {
4965 q += 4;
4966 bo = 1;
4967 }
4968 else if (bom == 0xFFFE0000) {
4969 q += 4;
4970 bo = -1;
4971 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004972#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004973 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004974 }
4975
4976 if (bo == -1) {
4977 /* force LE */
4978 iorder[0] = 0;
4979 iorder[1] = 1;
4980 iorder[2] = 2;
4981 iorder[3] = 3;
4982 }
4983 else if (bo == 1) {
4984 /* force BE */
4985 iorder[0] = 3;
4986 iorder[1] = 2;
4987 iorder[2] = 1;
4988 iorder[3] = 0;
4989 }
4990
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004991 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004992 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004993 if (!unicode)
4994 return NULL;
4995 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004996 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004997 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004998
Walter Dörwald41980ca2007-08-16 21:55:45 +00004999 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005000 Py_UCS4 ch;
5001 /* remaining bytes at the end? (size should be divisible by 4) */
5002 if (e-q<4) {
5003 if (consumed)
5004 break;
5005 errmsg = "truncated data";
5006 startinpos = ((const char *)q)-starts;
5007 endinpos = ((const char *)e)-starts;
5008 goto utf32Error;
5009 /* The remaining input chars are ignored if the callback
5010 chooses to skip the input */
5011 }
5012 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5013 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005014
Benjamin Peterson29060642009-01-31 22:14:21 +00005015 if (ch >= 0x110000)
5016 {
5017 errmsg = "codepoint not in range(0x110000)";
5018 startinpos = ((const char *)q)-starts;
5019 endinpos = startinpos+4;
5020 goto utf32Error;
5021 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005022 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5023 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005024 q += 4;
5025 continue;
5026 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 if (unicode_decode_call_errorhandler(
5028 errors, &errorHandler,
5029 "utf32", errmsg,
5030 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005031 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005032 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005033 }
5034
5035 if (byteorder)
5036 *byteorder = bo;
5037
5038 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005039 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005040
5041 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005042 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005043 goto onError;
5044
5045 Py_XDECREF(errorHandler);
5046 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005047#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005048 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005049 Py_DECREF(unicode);
5050 return NULL;
5051 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005052#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005053 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005054 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057 Py_DECREF(unicode);
5058 Py_XDECREF(errorHandler);
5059 Py_XDECREF(exc);
5060 return NULL;
5061}
5062
5063PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005064_PyUnicode_EncodeUTF32(PyObject *str,
5065 const char *errors,
5066 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005067{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005068 int kind;
5069 void *data;
5070 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005071 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005072 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005073 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005074 /* Offsets from p for storing byte pairs in the right order. */
5075#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5076 int iorder[] = {0, 1, 2, 3};
5077#else
5078 int iorder[] = {3, 2, 1, 0};
5079#endif
5080
Benjamin Peterson29060642009-01-31 22:14:21 +00005081#define STORECHAR(CH) \
5082 do { \
5083 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5084 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5085 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5086 p[iorder[0]] = (CH) & 0xff; \
5087 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005088 } while(0)
5089
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005090 if (!PyUnicode_Check(str)) {
5091 PyErr_BadArgument();
5092 return NULL;
5093 }
5094 if (PyUnicode_READY(str) < 0)
5095 return NULL;
5096 kind = PyUnicode_KIND(str);
5097 data = PyUnicode_DATA(str);
5098 len = PyUnicode_GET_LENGTH(str);
5099
5100 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005101 bytesize = nsize * 4;
5102 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005103 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005104 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105 if (v == NULL)
5106 return NULL;
5107
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005108 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005109 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005110 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005111 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005112 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005113
5114 if (byteorder == -1) {
5115 /* force LE */
5116 iorder[0] = 0;
5117 iorder[1] = 1;
5118 iorder[2] = 2;
5119 iorder[3] = 3;
5120 }
5121 else if (byteorder == 1) {
5122 /* force BE */
5123 iorder[0] = 3;
5124 iorder[1] = 2;
5125 iorder[2] = 1;
5126 iorder[3] = 0;
5127 }
5128
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005129 for (i = 0; i < len; i++)
5130 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005131
5132 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005133 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005134#undef STORECHAR
5135}
5136
Alexander Belopolsky40018472011-02-26 01:02:56 +00005137PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005138PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5139 Py_ssize_t size,
5140 const char *errors,
5141 int byteorder)
5142{
5143 PyObject *result;
5144 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5145 if (tmp == NULL)
5146 return NULL;
5147 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5148 Py_DECREF(tmp);
5149 return result;
5150}
5151
5152PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005153PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154{
Walter Dörwald41980ca2007-08-16 21:55:45 +00005155 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005156 PyUnicode_GET_SIZE(unicode),
5157 NULL,
5158 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005159}
5160
Guido van Rossumd57fd912000-03-10 22:53:23 +00005161/* --- UTF-16 Codec ------------------------------------------------------- */
5162
Tim Peters772747b2001-08-09 22:21:55 +00005163PyObject *
5164PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005165 Py_ssize_t size,
5166 const char *errors,
5167 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005168{
Walter Dörwald69652032004-09-07 20:24:22 +00005169 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5170}
5171
Antoine Pitrouab868312009-01-10 15:40:25 +00005172/* Two masks for fast checking of whether a C 'long' may contain
5173 UTF16-encoded surrogate characters. This is an efficient heuristic,
5174 assuming that non-surrogate characters with a code point >= 0x8000 are
5175 rare in most input.
5176 FAST_CHAR_MASK is used when the input is in native byte ordering,
5177 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005178*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005179#if (SIZEOF_LONG == 8)
5180# define FAST_CHAR_MASK 0x8000800080008000L
5181# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5182#elif (SIZEOF_LONG == 4)
5183# define FAST_CHAR_MASK 0x80008000L
5184# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5185#else
5186# error C 'long' size should be either 4 or 8!
5187#endif
5188
Walter Dörwald69652032004-09-07 20:24:22 +00005189PyObject *
5190PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005191 Py_ssize_t size,
5192 const char *errors,
5193 int *byteorder,
5194 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005195{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005196 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005197 Py_ssize_t startinpos;
5198 Py_ssize_t endinpos;
5199 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005200 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005201 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005202 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005203 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005204 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005205 /* Offsets from q for retrieving byte pairs in the right order. */
5206#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5207 int ihi = 1, ilo = 0;
5208#else
5209 int ihi = 0, ilo = 1;
5210#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005211 PyObject *errorHandler = NULL;
5212 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005213
5214 /* Note: size will always be longer than the resulting Unicode
5215 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005216 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005217 if (!unicode)
5218 return NULL;
5219 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005220 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005221 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005222
Tim Peters772747b2001-08-09 22:21:55 +00005223 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005224 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005225
5226 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005227 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005228
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005229 /* Check for BOM marks (U+FEFF) in the input and adjust current
5230 byte order setting accordingly. In native mode, the leading BOM
5231 mark is skipped, in all other modes, it is copied to the output
5232 stream as-is (giving a ZWNBSP character). */
5233 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005234 if (size >= 2) {
5235 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005236#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005237 if (bom == 0xFEFF) {
5238 q += 2;
5239 bo = -1;
5240 }
5241 else if (bom == 0xFFFE) {
5242 q += 2;
5243 bo = 1;
5244 }
Tim Petersced69f82003-09-16 20:30:58 +00005245#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005246 if (bom == 0xFEFF) {
5247 q += 2;
5248 bo = 1;
5249 }
5250 else if (bom == 0xFFFE) {
5251 q += 2;
5252 bo = -1;
5253 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005254#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005255 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005256 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005257
Tim Peters772747b2001-08-09 22:21:55 +00005258 if (bo == -1) {
5259 /* force LE */
5260 ihi = 1;
5261 ilo = 0;
5262 }
5263 else if (bo == 1) {
5264 /* force BE */
5265 ihi = 0;
5266 ilo = 1;
5267 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005268#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5269 native_ordering = ilo < ihi;
5270#else
5271 native_ordering = ilo > ihi;
5272#endif
Tim Peters772747b2001-08-09 22:21:55 +00005273
Antoine Pitrouab868312009-01-10 15:40:25 +00005274 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005275 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005276 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005277 /* First check for possible aligned read of a C 'long'. Unaligned
5278 reads are more expensive, better to defer to another iteration. */
5279 if (!((size_t) q & LONG_PTR_MASK)) {
5280 /* Fast path for runs of non-surrogate chars. */
5281 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005282 int kind = PyUnicode_KIND(unicode);
5283 void *data = PyUnicode_DATA(unicode);
5284 while (_q < aligned_end) {
5285 unsigned long block = * (unsigned long *) _q;
5286 unsigned short *pblock = (unsigned short*)&block;
5287 Py_UCS4 maxch;
5288 if (native_ordering) {
5289 /* Can use buffer directly */
5290 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005291 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005292 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005293 else {
5294 /* Need to byte-swap */
5295 unsigned char *_p = (unsigned char*)pblock;
5296 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005297 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005298 _p[0] = _q[1];
5299 _p[1] = _q[0];
5300 _p[2] = _q[3];
5301 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005302#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005303 _p[4] = _q[5];
5304 _p[5] = _q[4];
5305 _p[6] = _q[7];
5306 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005307#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005308 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005309 maxch = Py_MAX(pblock[0], pblock[1]);
5310#if SIZEOF_LONG == 8
5311 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5312#endif
5313 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5314 if (unicode_widen(&unicode, maxch) < 0)
5315 goto onError;
5316 kind = PyUnicode_KIND(unicode);
5317 data = PyUnicode_DATA(unicode);
5318 }
5319 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5320 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5321#if SIZEOF_LONG == 8
5322 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5323 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5324#endif
5325 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005326 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005327 q = _q;
5328 if (q >= e)
5329 break;
5330 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005332
Benjamin Peterson14339b62009-01-31 16:36:08 +00005333 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005334
5335 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005336 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5337 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005338 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) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005352 if (unicode_putchar(&unicode, &outpos,
5353 (((ch & 0x3FF)<<10) |
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005354 (ch2 & 0x3FF)) + 0x10000) < 0)
5355 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005356 continue;
5357 }
5358 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005359 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005360 startinpos = (((const char *)q)-4)-starts;
5361 endinpos = startinpos+2;
5362 goto utf16Error;
5363 }
5364
Benjamin Peterson14339b62009-01-31 16:36:08 +00005365 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005366 errmsg = "illegal encoding";
5367 startinpos = (((const char *)q)-2)-starts;
5368 endinpos = startinpos+2;
5369 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005370
Benjamin Peterson29060642009-01-31 22:14:21 +00005371 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005373 errors,
5374 &errorHandler,
5375 "utf16", errmsg,
5376 &starts,
5377 (const char **)&e,
5378 &startinpos,
5379 &endinpos,
5380 &exc,
5381 (const char **)&q,
5382 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005383 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005385 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005386 /* remaining byte at the end? (size should be even) */
5387 if (e == q) {
5388 if (!consumed) {
5389 errmsg = "truncated data";
5390 startinpos = ((const char *)q) - starts;
5391 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005392 if (unicode_decode_call_errorhandler(
5393 errors,
5394 &errorHandler,
5395 "utf16", errmsg,
5396 &starts,
5397 (const char **)&e,
5398 &startinpos,
5399 &endinpos,
5400 &exc,
5401 (const char **)&q,
5402 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005403 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005404 goto onError;
5405 /* The remaining input chars are ignored if the callback
5406 chooses to skip the input */
5407 }
5408 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005409
5410 if (byteorder)
5411 *byteorder = bo;
5412
Walter Dörwald69652032004-09-07 20:24:22 +00005413 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005414 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005415
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005417 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005418 goto onError;
5419
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005420 Py_XDECREF(errorHandler);
5421 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005422 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005423 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424
Benjamin Peterson29060642009-01-31 22:14:21 +00005425 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005427 Py_XDECREF(errorHandler);
5428 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005429 return NULL;
5430}
5431
Antoine Pitrouab868312009-01-10 15:40:25 +00005432#undef FAST_CHAR_MASK
5433#undef SWAPPED_FAST_CHAR_MASK
5434
Tim Peters772747b2001-08-09 22:21:55 +00005435PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005436_PyUnicode_EncodeUTF16(PyObject *str,
5437 const char *errors,
5438 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005439{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005440 int kind;
5441 void *data;
5442 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005443 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005444 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005445 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005446 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005447 /* Offsets from p for storing byte pairs in the right order. */
5448#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5449 int ihi = 1, ilo = 0;
5450#else
5451 int ihi = 0, ilo = 1;
5452#endif
5453
Benjamin Peterson29060642009-01-31 22:14:21 +00005454#define STORECHAR(CH) \
5455 do { \
5456 p[ihi] = ((CH) >> 8) & 0xff; \
5457 p[ilo] = (CH) & 0xff; \
5458 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005459 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005460
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005461 if (!PyUnicode_Check(str)) {
5462 PyErr_BadArgument();
5463 return NULL;
5464 }
5465 if (PyUnicode_READY(str) < 0)
5466 return NULL;
5467 kind = PyUnicode_KIND(str);
5468 data = PyUnicode_DATA(str);
5469 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005470
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005471 pairs = 0;
5472 if (kind == PyUnicode_4BYTE_KIND)
5473 for (i = 0; i < len; i++)
5474 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5475 pairs++;
5476 /* 2 * (len + pairs + (byteorder == 0)) */
5477 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005478 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005479 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005480 bytesize = nsize * 2;
5481 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005482 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005483 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005484 if (v == NULL)
5485 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005486
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005487 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005488 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005489 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005490 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005491 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005492
5493 if (byteorder == -1) {
5494 /* force LE */
5495 ihi = 1;
5496 ilo = 0;
5497 }
5498 else if (byteorder == 1) {
5499 /* force BE */
5500 ihi = 0;
5501 ilo = 1;
5502 }
5503
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005504 for (i = 0; i < len; i++) {
5505 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5506 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005507 if (ch >= 0x10000) {
5508 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5509 ch = 0xD800 | ((ch-0x10000) >> 10);
5510 }
Tim Peters772747b2001-08-09 22:21:55 +00005511 STORECHAR(ch);
5512 if (ch2)
5513 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005514 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005515
5516 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005517 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005518#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005519}
5520
Alexander Belopolsky40018472011-02-26 01:02:56 +00005521PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005522PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5523 Py_ssize_t size,
5524 const char *errors,
5525 int byteorder)
5526{
5527 PyObject *result;
5528 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5529 if (tmp == NULL)
5530 return NULL;
5531 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5532 Py_DECREF(tmp);
5533 return result;
5534}
5535
5536PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005537PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005538{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005539 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005540}
5541
5542/* --- Unicode Escape Codec ----------------------------------------------- */
5543
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005544/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5545 if all the escapes in the string make it still a valid ASCII string.
5546 Returns -1 if any escapes were found which cause the string to
5547 pop out of ASCII range. Otherwise returns the length of the
5548 required buffer to hold the string.
5549 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005550static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005551length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5552{
5553 const unsigned char *p = (const unsigned char *)s;
5554 const unsigned char *end = p + size;
5555 Py_ssize_t length = 0;
5556
5557 if (size < 0)
5558 return -1;
5559
5560 for (; p < end; ++p) {
5561 if (*p > 127) {
5562 /* Non-ASCII */
5563 return -1;
5564 }
5565 else if (*p != '\\') {
5566 /* Normal character */
5567 ++length;
5568 }
5569 else {
5570 /* Backslash-escape, check next char */
5571 ++p;
5572 /* Escape sequence reaches till end of string or
5573 non-ASCII follow-up. */
5574 if (p >= end || *p > 127)
5575 return -1;
5576 switch (*p) {
5577 case '\n':
5578 /* backslash + \n result in zero characters */
5579 break;
5580 case '\\': case '\'': case '\"':
5581 case 'b': case 'f': case 't':
5582 case 'n': case 'r': case 'v': case 'a':
5583 ++length;
5584 break;
5585 case '0': case '1': case '2': case '3':
5586 case '4': case '5': case '6': case '7':
5587 case 'x': case 'u': case 'U': case 'N':
5588 /* these do not guarantee ASCII characters */
5589 return -1;
5590 default:
5591 /* count the backslash + the other character */
5592 length += 2;
5593 }
5594 }
5595 }
5596 return length;
5597}
5598
5599/* Similar to PyUnicode_WRITE but either write into wstr field
5600 or treat string as ASCII. */
5601#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5602 do { \
5603 if ((kind) != PyUnicode_WCHAR_KIND) \
5604 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5605 else \
5606 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5607 } while (0)
5608
5609#define WRITE_WSTR(buf, index, value) \
5610 assert(kind == PyUnicode_WCHAR_KIND), \
5611 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5612
5613
Fredrik Lundh06d12682001-01-24 07:59:11 +00005614static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005615
Alexander Belopolsky40018472011-02-26 01:02:56 +00005616PyObject *
5617PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005618 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005619 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005620{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005621 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005622 Py_ssize_t startinpos;
5623 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005624 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005625 PyObject *v;
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öwise9b11c12011-11-08 17:35:34 +01005631 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005632 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005633
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005634 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005635
5636 /* After length_of_escaped_ascii_string() there are two alternatives,
5637 either the string is pure ASCII with named escapes like \n, etc.
5638 and we determined it's exact size (common case)
5639 or it contains \x, \u, ... escape sequences. then we create a
5640 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005641 if (len >= 0) {
5642 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005643 if (!v)
5644 goto onError;
5645 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005646 }
5647 else {
5648 /* Escaped strings will always be longer than the resulting
5649 Unicode string, so we start with size here and then reduce the
5650 length after conversion to the true value.
5651 (but if the error callback returns a long replacement string
5652 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005653 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005654 if (!v)
5655 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005656 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005657 }
5658
Guido van Rossumd57fd912000-03-10 22:53:23 +00005659 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005660 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005661 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005662 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005663
Guido van Rossumd57fd912000-03-10 22:53:23 +00005664 while (s < end) {
5665 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005666 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005667 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005669 /* The only case in which i == ascii_length is a backslash
5670 followed by a newline. */
5671 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005672
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673 /* Non-escape characters are interpreted as Unicode ordinals */
5674 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005675 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5676 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677 continue;
5678 }
5679
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005680 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005681 /* \ - Escapes */
5682 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005683 c = *s++;
5684 if (s > end)
5685 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005686
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005687 /* The only case in which i == ascii_length is a backslash
5688 followed by a newline. */
5689 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005690
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005691 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005692
Benjamin Peterson29060642009-01-31 22:14:21 +00005693 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005694#define WRITECHAR(ch) \
5695 do { \
5696 if (unicode_putchar(&v, &i, ch) < 0) \
5697 goto onError; \
5698 }while(0)
5699
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701 case '\\': WRITECHAR('\\'); break;
5702 case '\'': WRITECHAR('\''); break;
5703 case '\"': WRITECHAR('\"'); break;
5704 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005705 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005706 case 'f': WRITECHAR('\014'); break;
5707 case 't': WRITECHAR('\t'); break;
5708 case 'n': WRITECHAR('\n'); break;
5709 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005710 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005711 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005712 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005713 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005714
Benjamin Peterson29060642009-01-31 22:14:21 +00005715 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716 case '0': case '1': case '2': case '3':
5717 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005718 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005719 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005720 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005721 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005722 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005723 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005724 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005725 break;
5726
Benjamin Peterson29060642009-01-31 22:14:21 +00005727 /* hex escapes */
5728 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005729 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005730 digits = 2;
5731 message = "truncated \\xXX escape";
5732 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005733
Benjamin Peterson29060642009-01-31 22:14:21 +00005734 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005735 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005736 digits = 4;
5737 message = "truncated \\uXXXX escape";
5738 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005739
Benjamin Peterson29060642009-01-31 22:14:21 +00005740 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005741 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005742 digits = 8;
5743 message = "truncated \\UXXXXXXXX escape";
5744 hexescape:
5745 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005746 if (s+digits>end) {
5747 endinpos = size;
5748 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005749 errors, &errorHandler,
5750 "unicodeescape", "end of string in escape sequence",
5751 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005752 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005753 goto onError;
5754 goto nextByte;
5755 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005756 for (j = 0; j < digits; ++j) {
5757 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005758 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005759 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005760 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005761 errors, &errorHandler,
5762 "unicodeescape", message,
5763 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005764 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005765 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005766 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005767 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005768 }
5769 chr = (chr<<4) & ~0xF;
5770 if (c >= '0' && c <= '9')
5771 chr += c - '0';
5772 else if (c >= 'a' && c <= 'f')
5773 chr += 10 + c - 'a';
5774 else
5775 chr += 10 + c - 'A';
5776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005777 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005778 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005779 /* _decoding_error will have already written into the
5780 target buffer. */
5781 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005782 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005783 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005784 if (chr <= 0x10ffff) {
5785 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005786 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005787 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005788 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005789 errors, &errorHandler,
5790 "unicodeescape", "illegal Unicode character",
5791 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005792 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005793 goto onError;
5794 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 break;
5796
Benjamin Peterson29060642009-01-31 22:14:21 +00005797 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005798 case 'N':
5799 message = "malformed \\N character escape";
5800 if (ucnhash_CAPI == NULL) {
5801 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005802 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5803 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005804 if (ucnhash_CAPI == NULL)
5805 goto ucnhashError;
5806 }
5807 if (*s == '{') {
5808 const char *start = s+1;
5809 /* look for the closing brace */
5810 while (*s != '}' && s < end)
5811 s++;
5812 if (s > start && s < end && *s == '}') {
5813 /* found a name. look it up in the unicode database */
5814 message = "unknown Unicode character name";
5815 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005816 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005817 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005818 goto store;
5819 }
5820 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005821 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005822 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005823 errors, &errorHandler,
5824 "unicodeescape", message,
5825 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005826 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005827 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005828 break;
5829
5830 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005831 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005832 message = "\\ at end of string";
5833 s--;
5834 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005835 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005836 errors, &errorHandler,
5837 "unicodeescape", message,
5838 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005839 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005840 goto onError;
5841 }
5842 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005843 WRITECHAR('\\');
5844 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005845 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005846 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005847 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005848 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005849 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005850 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005851#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005852
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005853 if (PyUnicode_Resize(&v, i) < 0)
5854 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005855 Py_XDECREF(errorHandler);
5856 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005857#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005858 if (_PyUnicode_READY_REPLACE(&v)) {
5859 Py_DECREF(v);
5860 return NULL;
5861 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005862#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005863 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005864 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005865
Benjamin Peterson29060642009-01-31 22:14:21 +00005866 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005867 PyErr_SetString(
5868 PyExc_UnicodeError,
5869 "\\N escapes not supported (can't load unicodedata module)"
5870 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005871 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005872 Py_XDECREF(errorHandler);
5873 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005874 return NULL;
5875
Benjamin Peterson29060642009-01-31 22:14:21 +00005876 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005877 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005878 Py_XDECREF(errorHandler);
5879 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005880 return NULL;
5881}
5882
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005883#undef WRITE_ASCII_OR_WSTR
5884#undef WRITE_WSTR
5885
Guido van Rossumd57fd912000-03-10 22:53:23 +00005886/* Return a Unicode-Escape string version of the Unicode object.
5887
5888 If quotes is true, the string is enclosed in u"" or u'' quotes as
5889 appropriate.
5890
5891*/
5892
Alexander Belopolsky40018472011-02-26 01:02:56 +00005893PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005894PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005895{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005896 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005897 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005898 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005899 int kind;
5900 void *data;
5901 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005902
Thomas Wouters89f507f2006-12-13 04:49:30 +00005903 /* Initial allocation is based on the longest-possible unichr
5904 escape.
5905
5906 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5907 unichr, so in this case it's the longest unichr escape. In
5908 narrow (UTF-16) builds this is five chars per source unichr
5909 since there are two unichrs in the surrogate pair, so in narrow
5910 (UTF-16) builds it's not the longest unichr escape.
5911
5912 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5913 so in the narrow (UTF-16) build case it's the longest unichr
5914 escape.
5915 */
5916
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005917 if (!PyUnicode_Check(unicode)) {
5918 PyErr_BadArgument();
5919 return NULL;
5920 }
5921 if (PyUnicode_READY(unicode) < 0)
5922 return NULL;
5923 len = PyUnicode_GET_LENGTH(unicode);
5924 kind = PyUnicode_KIND(unicode);
5925 data = PyUnicode_DATA(unicode);
5926 switch(kind) {
5927 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5928 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5929 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5930 }
5931
5932 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005933 return PyBytes_FromStringAndSize(NULL, 0);
5934
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005935 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005937
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005938 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005939 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005940 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005941 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005942 if (repr == NULL)
5943 return NULL;
5944
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005945 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005947 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005948 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005949
Walter Dörwald79e913e2007-05-12 11:08:06 +00005950 /* Escape backslashes */
5951 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952 *p++ = '\\';
5953 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005954 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005955 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005956
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005957 /* Map 21-bit characters to '\U00xxxxxx' */
5958 else if (ch >= 0x10000) {
5959 *p++ = '\\';
5960 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005961 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5962 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5963 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5964 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5965 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5966 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5967 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5968 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005969 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005970 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005971
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005973 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005974 *p++ = '\\';
5975 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005976 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5977 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5978 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5979 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005981
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005982 /* Map special whitespace to '\t', \n', '\r' */
5983 else if (ch == '\t') {
5984 *p++ = '\\';
5985 *p++ = 't';
5986 }
5987 else if (ch == '\n') {
5988 *p++ = '\\';
5989 *p++ = 'n';
5990 }
5991 else if (ch == '\r') {
5992 *p++ = '\\';
5993 *p++ = 'r';
5994 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005995
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005996 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005997 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005998 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005999 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006000 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
6001 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00006002 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00006003
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004 /* Copy everything else as-is */
6005 else
6006 *p++ = (char) ch;
6007 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006009 assert(p - PyBytes_AS_STRING(repr) > 0);
6010 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6011 return NULL;
6012 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013}
6014
Alexander Belopolsky40018472011-02-26 01:02:56 +00006015PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006016PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6017 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006018{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006019 PyObject *result;
6020 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6021 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006022 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006023 result = PyUnicode_AsUnicodeEscapeString(tmp);
6024 Py_DECREF(tmp);
6025 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026}
6027
6028/* --- Raw Unicode Escape Codec ------------------------------------------- */
6029
Alexander Belopolsky40018472011-02-26 01:02:56 +00006030PyObject *
6031PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006032 Py_ssize_t size,
6033 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006034{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006035 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006036 Py_ssize_t startinpos;
6037 Py_ssize_t endinpos;
6038 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006039 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040 const char *end;
6041 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006042 PyObject *errorHandler = NULL;
6043 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006044
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 /* Escaped strings will always be longer than the resulting
6046 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006047 length after conversion to the true value. (But decoding error
6048 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006049 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006051 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006052 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006053 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006054 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006055 end = s + size;
6056 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006057 unsigned char c;
6058 Py_UCS4 x;
6059 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006060 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006061
Benjamin Peterson29060642009-01-31 22:14:21 +00006062 /* Non-escape characters are interpreted as Unicode ordinals */
6063 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006064 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6065 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006067 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006068 startinpos = s-starts;
6069
6070 /* \u-escapes are only interpreted iff the number of leading
6071 backslashes if odd */
6072 bs = s;
6073 for (;s < end;) {
6074 if (*s != '\\')
6075 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006076 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6077 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006078 }
6079 if (((s - bs) & 1) == 0 ||
6080 s >= end ||
6081 (*s != 'u' && *s != 'U')) {
6082 continue;
6083 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006084 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 count = *s=='u' ? 4 : 8;
6086 s++;
6087
6088 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006089 for (x = 0, i = 0; i < count; ++i, ++s) {
6090 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006091 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006092 endinpos = s-starts;
6093 if (unicode_decode_call_errorhandler(
6094 errors, &errorHandler,
6095 "rawunicodeescape", "truncated \\uXXXX",
6096 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006097 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006098 goto onError;
6099 goto nextByte;
6100 }
6101 x = (x<<4) & ~0xF;
6102 if (c >= '0' && c <= '9')
6103 x += c - '0';
6104 else if (c >= 'a' && c <= 'f')
6105 x += 10 + c - 'a';
6106 else
6107 x += 10 + c - 'A';
6108 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006109 if (x <= 0x10ffff) {
6110 if (unicode_putchar(&v, &outpos, x) < 0)
6111 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006112 } else {
6113 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006114 if (unicode_decode_call_errorhandler(
6115 errors, &errorHandler,
6116 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006117 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006118 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006120 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006121 nextByte:
6122 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006124 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006125 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006126 Py_XDECREF(errorHandler);
6127 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006128 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006129 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006130
Benjamin Peterson29060642009-01-31 22:14:21 +00006131 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006132 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006133 Py_XDECREF(errorHandler);
6134 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006135 return NULL;
6136}
6137
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006138
Alexander Belopolsky40018472011-02-26 01:02:56 +00006139PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006140PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006141{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006142 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006143 char *p;
6144 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145 Py_ssize_t expandsize, pos;
6146 int kind;
6147 void *data;
6148 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006149
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 if (!PyUnicode_Check(unicode)) {
6151 PyErr_BadArgument();
6152 return NULL;
6153 }
6154 if (PyUnicode_READY(unicode) < 0)
6155 return NULL;
6156 kind = PyUnicode_KIND(unicode);
6157 data = PyUnicode_DATA(unicode);
6158 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006159
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006160 switch(kind) {
6161 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6162 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6163 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6164 }
Victor Stinner0e368262011-11-10 20:12:49 +01006165
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006167 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006168
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006169 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006170 if (repr == NULL)
6171 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006172 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006173 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006174
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006175 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006176 for (pos = 0; pos < len; pos++) {
6177 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006178 /* Map 32-bit characters to '\Uxxxxxxxx' */
6179 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006180 *p++ = '\\';
6181 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006182 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6183 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6184 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6185 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6186 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6187 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6188 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6189 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006190 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006191 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006192 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193 *p++ = '\\';
6194 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006195 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6196 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6197 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6198 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006199 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006200 /* Copy everything else as-is */
6201 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006202 *p++ = (char) ch;
6203 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006204
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006205 assert(p > q);
6206 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006207 return NULL;
6208 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209}
6210
Alexander Belopolsky40018472011-02-26 01:02:56 +00006211PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006212PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6213 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006214{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006215 PyObject *result;
6216 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6217 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006218 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006219 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6220 Py_DECREF(tmp);
6221 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006222}
6223
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006224/* --- Unicode Internal Codec ------------------------------------------- */
6225
Alexander Belopolsky40018472011-02-26 01:02:56 +00006226PyObject *
6227_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006228 Py_ssize_t size,
6229 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006230{
6231 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006232 Py_ssize_t startinpos;
6233 Py_ssize_t endinpos;
6234 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006235 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006236 const char *end;
6237 const char *reason;
6238 PyObject *errorHandler = NULL;
6239 PyObject *exc = NULL;
6240
Thomas Wouters89f507f2006-12-13 04:49:30 +00006241 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006242 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006243 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006244 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006245 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006246 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006247 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006248 end = s + size;
6249
6250 while (s < end) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006251 Py_UCS4 ch = *(Py_UNICODE*)s;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006252 /* We have to sanity check the raw data, otherwise doom looms for
6253 some malformed UCS-4 data. */
6254 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006255#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006256 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006257#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006258 end-s < Py_UNICODE_SIZE
6259 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006260 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006261 startinpos = s - starts;
6262 if (end-s < Py_UNICODE_SIZE) {
6263 endinpos = end-starts;
6264 reason = "truncated input";
6265 }
6266 else {
6267 endinpos = s - starts + Py_UNICODE_SIZE;
6268 reason = "illegal code point (> 0x10FFFF)";
6269 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 if (unicode_decode_call_errorhandler(
6271 errors, &errorHandler,
6272 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006273 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006274 &v, &outpos)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006275 goto onError;
6276 }
6277 }
6278 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006279 if (unicode_putchar(&v, &outpos, ch) < 0)
6280 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006281 s += Py_UNICODE_SIZE;
6282 }
6283 }
6284
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006285 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006286 goto onError;
6287 Py_XDECREF(errorHandler);
6288 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006289 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006290 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006291
Benjamin Peterson29060642009-01-31 22:14:21 +00006292 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006293 Py_XDECREF(v);
6294 Py_XDECREF(errorHandler);
6295 Py_XDECREF(exc);
6296 return NULL;
6297}
6298
Guido van Rossumd57fd912000-03-10 22:53:23 +00006299/* --- Latin-1 Codec ------------------------------------------------------ */
6300
Alexander Belopolsky40018472011-02-26 01:02:56 +00006301PyObject *
6302PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006303 Py_ssize_t size,
6304 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006305{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006306 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006307 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308}
6309
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006310/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006311static void
6312make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006313 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006314 PyObject *unicode,
6315 Py_ssize_t startpos, Py_ssize_t endpos,
6316 const char *reason)
6317{
6318 if (*exceptionObject == NULL) {
6319 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006320 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006321 encoding, unicode, startpos, endpos, reason);
6322 }
6323 else {
6324 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6325 goto onError;
6326 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6327 goto onError;
6328 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6329 goto onError;
6330 return;
6331 onError:
6332 Py_DECREF(*exceptionObject);
6333 *exceptionObject = NULL;
6334 }
6335}
6336
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006337/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006338static void
6339raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006340 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006341 PyObject *unicode,
6342 Py_ssize_t startpos, Py_ssize_t endpos,
6343 const char *reason)
6344{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006345 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006346 encoding, unicode, startpos, endpos, reason);
6347 if (*exceptionObject != NULL)
6348 PyCodec_StrictErrors(*exceptionObject);
6349}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006350
6351/* error handling callback helper:
6352 build arguments, call the callback and check the arguments,
6353 put the result into newpos and return the replacement string, which
6354 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006355static PyObject *
6356unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006357 PyObject **errorHandler,
6358 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006360 Py_ssize_t startpos, Py_ssize_t endpos,
6361 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006362{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006363 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006364 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006365 PyObject *restuple;
6366 PyObject *resunicode;
6367
6368 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006369 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006370 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006371 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006372 }
6373
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006374 if (PyUnicode_READY(unicode) < 0)
6375 return NULL;
6376 len = PyUnicode_GET_LENGTH(unicode);
6377
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006378 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006379 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006380 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006381 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006382
6383 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006384 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006385 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006386 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006387 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006388 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006389 Py_DECREF(restuple);
6390 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006392 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006393 &resunicode, newpos)) {
6394 Py_DECREF(restuple);
6395 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006396 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006397 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6398 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6399 Py_DECREF(restuple);
6400 return NULL;
6401 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006403 *newpos = len + *newpos;
6404 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006405 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6406 Py_DECREF(restuple);
6407 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006408 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006409 Py_INCREF(resunicode);
6410 Py_DECREF(restuple);
6411 return resunicode;
6412}
6413
Alexander Belopolsky40018472011-02-26 01:02:56 +00006414static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006415unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006416 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006417 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006419 /* input state */
6420 Py_ssize_t pos=0, size;
6421 int kind;
6422 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006423 /* output object */
6424 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425 /* pointer into the output */
6426 char *str;
6427 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006428 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006429 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6430 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006431 PyObject *errorHandler = NULL;
6432 PyObject *exc = NULL;
6433 /* the following variable is used for caching string comparisons
6434 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6435 int known_errorHandler = -1;
6436
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006437 if (PyUnicode_READY(unicode) < 0)
6438 return NULL;
6439 size = PyUnicode_GET_LENGTH(unicode);
6440 kind = PyUnicode_KIND(unicode);
6441 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 /* allocate enough for a simple encoding without
6443 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006444 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006445 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006446 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006447 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006448 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006449 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006450 ressize = size;
6451
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006452 while (pos < size) {
6453 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006454
Benjamin Peterson29060642009-01-31 22:14:21 +00006455 /* can we encode this? */
6456 if (c<limit) {
6457 /* no overflow check, because we know that the space is enough */
6458 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006460 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006461 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006462 Py_ssize_t requiredsize;
6463 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006464 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006466 Py_ssize_t collstart = pos;
6467 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006469 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006470 ++collend;
6471 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6472 if (known_errorHandler==-1) {
6473 if ((errors==NULL) || (!strcmp(errors, "strict")))
6474 known_errorHandler = 1;
6475 else if (!strcmp(errors, "replace"))
6476 known_errorHandler = 2;
6477 else if (!strcmp(errors, "ignore"))
6478 known_errorHandler = 3;
6479 else if (!strcmp(errors, "xmlcharrefreplace"))
6480 known_errorHandler = 4;
6481 else
6482 known_errorHandler = 0;
6483 }
6484 switch (known_errorHandler) {
6485 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006486 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006487 goto onError;
6488 case 2: /* replace */
6489 while (collstart++<collend)
6490 *str++ = '?'; /* fall through */
6491 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006492 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006493 break;
6494 case 4: /* xmlcharrefreplace */
6495 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496 /* determine replacement size */
6497 for (i = collstart, repsize = 0; i < collend; ++i) {
6498 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6499 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006500 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006501 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006505 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006506 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006507#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006508 else
6509 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006510#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006511 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006512 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006513 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006514 repsize += 2+6+1;
6515 else
6516 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006517#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006518 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006519 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006520 if (requiredsize > ressize) {
6521 if (requiredsize<2*ressize)
6522 requiredsize = 2*ressize;
6523 if (_PyBytes_Resize(&res, requiredsize))
6524 goto onError;
6525 str = PyBytes_AS_STRING(res) + respos;
6526 ressize = requiredsize;
6527 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006528 /* generate replacement */
6529 for (i = collstart; i < collend; ++i) {
6530 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006532 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006533 break;
6534 default:
6535 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006536 encoding, reason, unicode, &exc,
6537 collstart, collend, &newpos);
6538 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6539 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006540 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006541 if (PyBytes_Check(repunicode)) {
6542 /* Directly copy bytes result to output. */
6543 repsize = PyBytes_Size(repunicode);
6544 if (repsize > 1) {
6545 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006546 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006547 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6548 Py_DECREF(repunicode);
6549 goto onError;
6550 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006551 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006552 ressize += repsize-1;
6553 }
6554 memcpy(str, PyBytes_AsString(repunicode), repsize);
6555 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006556 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006557 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006558 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006559 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006560 /* need more space? (at least enough for what we
6561 have+the replacement+the rest of the string, so
6562 we won't have to check space for encodable characters) */
6563 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006564 repsize = PyUnicode_GET_LENGTH(repunicode);
6565 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006566 if (requiredsize > ressize) {
6567 if (requiredsize<2*ressize)
6568 requiredsize = 2*ressize;
6569 if (_PyBytes_Resize(&res, requiredsize)) {
6570 Py_DECREF(repunicode);
6571 goto onError;
6572 }
6573 str = PyBytes_AS_STRING(res) + respos;
6574 ressize = requiredsize;
6575 }
6576 /* check if there is anything unencodable in the replacement
6577 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006578 for (i = 0; repsize-->0; ++i, ++str) {
6579 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006580 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006581 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006582 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 Py_DECREF(repunicode);
6584 goto onError;
6585 }
6586 *str = (char)c;
6587 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006588 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006589 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006590 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006591 }
6592 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006593 /* Resize if we allocated to much */
6594 size = str - PyBytes_AS_STRING(res);
6595 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006596 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006597 if (_PyBytes_Resize(&res, size) < 0)
6598 goto onError;
6599 }
6600
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006601 Py_XDECREF(errorHandler);
6602 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006603 return res;
6604
6605 onError:
6606 Py_XDECREF(res);
6607 Py_XDECREF(errorHandler);
6608 Py_XDECREF(exc);
6609 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006610}
6611
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006612/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006613PyObject *
6614PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006615 Py_ssize_t size,
6616 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006617{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006618 PyObject *result;
6619 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6620 if (unicode == NULL)
6621 return NULL;
6622 result = unicode_encode_ucs1(unicode, errors, 256);
6623 Py_DECREF(unicode);
6624 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006625}
6626
Alexander Belopolsky40018472011-02-26 01:02:56 +00006627PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006628_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006629{
6630 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006631 PyErr_BadArgument();
6632 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006634 if (PyUnicode_READY(unicode) == -1)
6635 return NULL;
6636 /* Fast path: if it is a one-byte string, construct
6637 bytes object directly. */
6638 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6639 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6640 PyUnicode_GET_LENGTH(unicode));
6641 /* Non-Latin-1 characters present. Defer to above function to
6642 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006643 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006644}
6645
6646PyObject*
6647PyUnicode_AsLatin1String(PyObject *unicode)
6648{
6649 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006650}
6651
6652/* --- 7-bit ASCII Codec -------------------------------------------------- */
6653
Alexander Belopolsky40018472011-02-26 01:02:56 +00006654PyObject *
6655PyUnicode_DecodeASCII(const char *s,
6656 Py_ssize_t size,
6657 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006658{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006659 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006660 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006661 int kind;
6662 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006663 Py_ssize_t startinpos;
6664 Py_ssize_t endinpos;
6665 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006667 int has_error;
6668 const unsigned char *p = (const unsigned char *)s;
6669 const unsigned char *end = p + size;
6670 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006671 PyObject *errorHandler = NULL;
6672 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006673
Guido van Rossumd57fd912000-03-10 22:53:23 +00006674 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006675 if (size == 1 && (unsigned char)s[0] < 128)
6676 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006677
Victor Stinner702c7342011-10-05 13:50:52 +02006678 has_error = 0;
6679 while (p < end && !has_error) {
6680 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6681 an explanation. */
6682 if (!((size_t) p & LONG_PTR_MASK)) {
6683 /* Help register allocation */
6684 register const unsigned char *_p = p;
6685 while (_p < aligned_end) {
6686 unsigned long value = *(unsigned long *) _p;
6687 if (value & ASCII_CHAR_MASK) {
6688 has_error = 1;
6689 break;
6690 }
6691 _p += SIZEOF_LONG;
6692 }
6693 if (_p == end)
6694 break;
6695 if (has_error)
6696 break;
6697 p = _p;
6698 }
6699 if (*p & 0x80) {
6700 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006701 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006702 }
6703 else {
6704 ++p;
6705 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006706 }
Victor Stinner702c7342011-10-05 13:50:52 +02006707 if (!has_error)
6708 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006709
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006710 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006711 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006712 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006713 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006714 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006715 kind = PyUnicode_KIND(v);
6716 data = PyUnicode_DATA(v);
6717 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 e = s + size;
6719 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006720 register unsigned char c = (unsigned char)*s;
6721 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006722 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 ++s;
6724 }
6725 else {
6726 startinpos = s-starts;
6727 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 if (unicode_decode_call_errorhandler(
6729 errors, &errorHandler,
6730 "ascii", "ordinal not in range(128)",
6731 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006732 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006733 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006734 kind = PyUnicode_KIND(v);
6735 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006737 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006738 if (PyUnicode_Resize(&v, outpos) < 0)
6739 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006740 Py_XDECREF(errorHandler);
6741 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006742 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006743 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006744
Benjamin Peterson29060642009-01-31 22:14:21 +00006745 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006746 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006747 Py_XDECREF(errorHandler);
6748 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 return NULL;
6750}
6751
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006753PyObject *
6754PyUnicode_EncodeASCII(const Py_UNICODE *p,
6755 Py_ssize_t size,
6756 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006757{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006758 PyObject *result;
6759 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6760 if (unicode == NULL)
6761 return NULL;
6762 result = unicode_encode_ucs1(unicode, errors, 128);
6763 Py_DECREF(unicode);
6764 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006765}
6766
Alexander Belopolsky40018472011-02-26 01:02:56 +00006767PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006768_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006769{
6770 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006771 PyErr_BadArgument();
6772 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006773 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006774 if (PyUnicode_READY(unicode) == -1)
6775 return NULL;
6776 /* Fast path: if it is an ASCII-only string, construct bytes object
6777 directly. Else defer to above function to raise the exception. */
6778 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6779 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6780 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006781 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006782}
6783
6784PyObject *
6785PyUnicode_AsASCIIString(PyObject *unicode)
6786{
6787 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006788}
6789
Victor Stinner99b95382011-07-04 14:23:54 +02006790#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006791
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006792/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006793
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006794#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006795#define NEED_RETRY
6796#endif
6797
Victor Stinner3a50e702011-10-18 21:21:00 +02006798#ifndef WC_ERR_INVALID_CHARS
6799# define WC_ERR_INVALID_CHARS 0x0080
6800#endif
6801
6802static char*
6803code_page_name(UINT code_page, PyObject **obj)
6804{
6805 *obj = NULL;
6806 if (code_page == CP_ACP)
6807 return "mbcs";
6808 if (code_page == CP_UTF7)
6809 return "CP_UTF7";
6810 if (code_page == CP_UTF8)
6811 return "CP_UTF8";
6812
6813 *obj = PyBytes_FromFormat("cp%u", code_page);
6814 if (*obj == NULL)
6815 return NULL;
6816 return PyBytes_AS_STRING(*obj);
6817}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006818
Alexander Belopolsky40018472011-02-26 01:02:56 +00006819static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006820is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006821{
6822 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006823 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006824
Victor Stinner3a50e702011-10-18 21:21:00 +02006825 if (!IsDBCSLeadByteEx(code_page, *curr))
6826 return 0;
6827
6828 prev = CharPrevExA(code_page, s, curr, 0);
6829 if (prev == curr)
6830 return 1;
6831 /* FIXME: This code is limited to "true" double-byte encodings,
6832 as it assumes an incomplete character consists of a single
6833 byte. */
6834 if (curr - prev == 2)
6835 return 1;
6836 if (!IsDBCSLeadByteEx(code_page, *prev))
6837 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006838 return 0;
6839}
6840
Victor Stinner3a50e702011-10-18 21:21:00 +02006841static DWORD
6842decode_code_page_flags(UINT code_page)
6843{
6844 if (code_page == CP_UTF7) {
6845 /* The CP_UTF7 decoder only supports flags=0 */
6846 return 0;
6847 }
6848 else
6849 return MB_ERR_INVALID_CHARS;
6850}
6851
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006852/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006853 * Decode a byte string from a Windows code page into unicode object in strict
6854 * mode.
6855 *
6856 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6857 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006858 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006859static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006860decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006861 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006862 const char *in,
6863 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006864{
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 const DWORD flags = decode_code_page_flags(code_page);
6866 Py_UNICODE *out;
6867 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006868
6869 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006870 assert(insize > 0);
6871 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6872 if (outsize <= 0)
6873 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006874
6875 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006876 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006877 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006878 if (*v == NULL)
6879 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006880 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006881 }
6882 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006883 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006884 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006885 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006886 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006887 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006888 }
6889
6890 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006891 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6892 if (outsize <= 0)
6893 goto error;
6894 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006895
Victor Stinner3a50e702011-10-18 21:21:00 +02006896error:
6897 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6898 return -2;
6899 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006900 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006901}
6902
Victor Stinner3a50e702011-10-18 21:21:00 +02006903/*
6904 * Decode a byte string from a code page into unicode object with an error
6905 * handler.
6906 *
6907 * Returns consumed size if succeed, or raise a WindowsError or
6908 * UnicodeDecodeError exception and returns -1 on error.
6909 */
6910static int
6911decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006912 PyObject **v,
6913 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006914 const char *errors)
6915{
6916 const char *startin = in;
6917 const char *endin = in + size;
6918 const DWORD flags = decode_code_page_flags(code_page);
6919 /* Ideally, we should get reason from FormatMessage. This is the Windows
6920 2000 English version of the message. */
6921 const char *reason = "No mapping for the Unicode character exists "
6922 "in the target code page.";
6923 /* each step cannot decode more than 1 character, but a character can be
6924 represented as a surrogate pair */
6925 wchar_t buffer[2], *startout, *out;
6926 int insize, outsize;
6927 PyObject *errorHandler = NULL;
6928 PyObject *exc = NULL;
6929 PyObject *encoding_obj = NULL;
6930 char *encoding;
6931 DWORD err;
6932 int ret = -1;
6933
6934 assert(size > 0);
6935
6936 encoding = code_page_name(code_page, &encoding_obj);
6937 if (encoding == NULL)
6938 return -1;
6939
6940 if (errors == NULL || strcmp(errors, "strict") == 0) {
6941 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6942 UnicodeDecodeError. */
6943 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6944 if (exc != NULL) {
6945 PyCodec_StrictErrors(exc);
6946 Py_CLEAR(exc);
6947 }
6948 goto error;
6949 }
6950
6951 if (*v == NULL) {
6952 /* Create unicode object */
6953 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6954 PyErr_NoMemory();
6955 goto error;
6956 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006957 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006958 if (*v == NULL)
6959 goto error;
6960 startout = PyUnicode_AS_UNICODE(*v);
6961 }
6962 else {
6963 /* Extend unicode object */
6964 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6965 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6966 PyErr_NoMemory();
6967 goto error;
6968 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006969 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006970 goto error;
6971 startout = PyUnicode_AS_UNICODE(*v) + n;
6972 }
6973
6974 /* Decode the byte string character per character */
6975 out = startout;
6976 while (in < endin)
6977 {
6978 /* Decode a character */
6979 insize = 1;
6980 do
6981 {
6982 outsize = MultiByteToWideChar(code_page, flags,
6983 in, insize,
6984 buffer, Py_ARRAY_LENGTH(buffer));
6985 if (outsize > 0)
6986 break;
6987 err = GetLastError();
6988 if (err != ERROR_NO_UNICODE_TRANSLATION
6989 && err != ERROR_INSUFFICIENT_BUFFER)
6990 {
6991 PyErr_SetFromWindowsErr(0);
6992 goto error;
6993 }
6994 insize++;
6995 }
6996 /* 4=maximum length of a UTF-8 sequence */
6997 while (insize <= 4 && (in + insize) <= endin);
6998
6999 if (outsize <= 0) {
7000 Py_ssize_t startinpos, endinpos, outpos;
7001
7002 startinpos = in - startin;
7003 endinpos = startinpos + 1;
7004 outpos = out - PyUnicode_AS_UNICODE(*v);
7005 if (unicode_decode_call_errorhandler(
7006 errors, &errorHandler,
7007 encoding, reason,
7008 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007009 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007010 {
7011 goto error;
7012 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007013 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007014 }
7015 else {
7016 in += insize;
7017 memcpy(out, buffer, outsize * sizeof(wchar_t));
7018 out += outsize;
7019 }
7020 }
7021
7022 /* write a NUL character at the end */
7023 *out = 0;
7024
7025 /* Extend unicode object */
7026 outsize = out - startout;
7027 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007028 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007029 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007030 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007031
7032error:
7033 Py_XDECREF(encoding_obj);
7034 Py_XDECREF(errorHandler);
7035 Py_XDECREF(exc);
7036 return ret;
7037}
7038
Victor Stinner3a50e702011-10-18 21:21:00 +02007039static PyObject *
7040decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007041 const char *s, Py_ssize_t size,
7042 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007043{
Victor Stinner76a31a62011-11-04 00:05:13 +01007044 PyObject *v = NULL;
7045 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046
Victor Stinner3a50e702011-10-18 21:21:00 +02007047 if (code_page < 0) {
7048 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7049 return NULL;
7050 }
7051
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007053 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007054
Victor Stinner76a31a62011-11-04 00:05:13 +01007055 do
7056 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 if (size > INT_MAX) {
7059 chunk_size = INT_MAX;
7060 final = 0;
7061 done = 0;
7062 }
7063 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007064#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007065 {
7066 chunk_size = (int)size;
7067 final = (consumed == NULL);
7068 done = 1;
7069 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007070
Victor Stinner76a31a62011-11-04 00:05:13 +01007071 /* Skip trailing lead-byte unless 'final' is set */
7072 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7073 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007074
Victor Stinner76a31a62011-11-04 00:05:13 +01007075 if (chunk_size == 0 && done) {
7076 if (v != NULL)
7077 break;
7078 Py_INCREF(unicode_empty);
7079 return unicode_empty;
7080 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081
Victor Stinner76a31a62011-11-04 00:05:13 +01007082
7083 converted = decode_code_page_strict(code_page, &v,
7084 s, chunk_size);
7085 if (converted == -2)
7086 converted = decode_code_page_errors(code_page, &v,
7087 s, chunk_size,
7088 errors);
7089 assert(converted != 0);
7090
7091 if (converted < 0) {
7092 Py_XDECREF(v);
7093 return NULL;
7094 }
7095
7096 if (consumed)
7097 *consumed += converted;
7098
7099 s += converted;
7100 size -= converted;
7101 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007102
Victor Stinner17efeed2011-10-04 20:05:46 +02007103#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007104 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007105 Py_DECREF(v);
7106 return NULL;
7107 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007108#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007109 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007110 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007111}
7112
Alexander Belopolsky40018472011-02-26 01:02:56 +00007113PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007114PyUnicode_DecodeCodePageStateful(int code_page,
7115 const char *s,
7116 Py_ssize_t size,
7117 const char *errors,
7118 Py_ssize_t *consumed)
7119{
7120 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7121}
7122
7123PyObject *
7124PyUnicode_DecodeMBCSStateful(const char *s,
7125 Py_ssize_t size,
7126 const char *errors,
7127 Py_ssize_t *consumed)
7128{
7129 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7130}
7131
7132PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007133PyUnicode_DecodeMBCS(const char *s,
7134 Py_ssize_t size,
7135 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007136{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007137 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7138}
7139
Victor Stinner3a50e702011-10-18 21:21:00 +02007140static DWORD
7141encode_code_page_flags(UINT code_page, const char *errors)
7142{
7143 if (code_page == CP_UTF8) {
7144 if (winver.dwMajorVersion >= 6)
7145 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7146 and later */
7147 return WC_ERR_INVALID_CHARS;
7148 else
7149 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7150 return 0;
7151 }
7152 else if (code_page == CP_UTF7) {
7153 /* CP_UTF7 only supports flags=0 */
7154 return 0;
7155 }
7156 else {
7157 if (errors != NULL && strcmp(errors, "replace") == 0)
7158 return 0;
7159 else
7160 return WC_NO_BEST_FIT_CHARS;
7161 }
7162}
7163
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007164/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007165 * Encode a Unicode string to a Windows code page into a byte string in strict
7166 * mode.
7167 *
7168 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7169 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007171static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007172encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007173 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007174 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007175{
Victor Stinner554f3f02010-06-16 23:33:54 +00007176 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 BOOL *pusedDefaultChar = &usedDefaultChar;
7178 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007179 PyObject *exc = NULL;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007180 Py_UNICODE *p;
7181 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007182 const DWORD flags = encode_code_page_flags(code_page, NULL);
7183 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007184 /* Create a substring so that we can get the UTF-16 representation
7185 of just the slice under consideration. */
7186 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007187
Martin v. Löwis3d325192011-11-04 18:23:06 +01007188 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007189
Victor Stinner3a50e702011-10-18 21:21:00 +02007190 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007191 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007192 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007193 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007194
Victor Stinner2fc507f2011-11-04 20:06:39 +01007195 substring = PyUnicode_Substring(unicode, offset, offset+len);
7196 if (substring == NULL)
7197 return -1;
7198 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7199 if (p == NULL) {
7200 Py_DECREF(substring);
7201 return -1;
7202 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007203
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007204 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007205 outsize = WideCharToMultiByte(code_page, flags,
7206 p, size,
7207 NULL, 0,
7208 NULL, pusedDefaultChar);
7209 if (outsize <= 0)
7210 goto error;
7211 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007212 if (pusedDefaultChar && *pusedDefaultChar) {
7213 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007215 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007216
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007218 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007220 if (*outbytes == NULL) {
7221 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007222 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007223 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007224 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007225 }
7226 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007227 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 const Py_ssize_t n = PyBytes_Size(*outbytes);
7229 if (outsize > PY_SSIZE_T_MAX - n) {
7230 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007231 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007232 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007234 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7235 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007238 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007239 }
7240
7241 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 outsize = WideCharToMultiByte(code_page, flags,
7243 p, size,
7244 out, outsize,
7245 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007246 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007247 if (outsize <= 0)
7248 goto error;
7249 if (pusedDefaultChar && *pusedDefaultChar)
7250 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007251 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007252
Victor Stinner3a50e702011-10-18 21:21:00 +02007253error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007254 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007255 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7256 return -2;
7257 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007258 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007259}
7260
Victor Stinner3a50e702011-10-18 21:21:00 +02007261/*
7262 * Encode a Unicode string to a Windows code page into a byte string using a
7263 * error handler.
7264 *
7265 * Returns consumed characters if succeed, or raise a WindowsError and returns
7266 * -1 on other error.
7267 */
7268static int
7269encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007270 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007271 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007272{
Victor Stinner3a50e702011-10-18 21:21:00 +02007273 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007274 Py_ssize_t pos = unicode_offset;
7275 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007276 /* Ideally, we should get reason from FormatMessage. This is the Windows
7277 2000 English version of the message. */
7278 const char *reason = "invalid character";
7279 /* 4=maximum length of a UTF-8 sequence */
7280 char buffer[4];
7281 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7282 Py_ssize_t outsize;
7283 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 PyObject *errorHandler = NULL;
7285 PyObject *exc = NULL;
7286 PyObject *encoding_obj = NULL;
7287 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007288 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007289 PyObject *rep;
7290 int ret = -1;
7291
7292 assert(insize > 0);
7293
7294 encoding = code_page_name(code_page, &encoding_obj);
7295 if (encoding == NULL)
7296 return -1;
7297
7298 if (errors == NULL || strcmp(errors, "strict") == 0) {
7299 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7300 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007301 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007302 if (exc != NULL) {
7303 PyCodec_StrictErrors(exc);
7304 Py_DECREF(exc);
7305 }
7306 Py_XDECREF(encoding_obj);
7307 return -1;
7308 }
7309
7310 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7311 pusedDefaultChar = &usedDefaultChar;
7312 else
7313 pusedDefaultChar = NULL;
7314
7315 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7316 PyErr_NoMemory();
7317 goto error;
7318 }
7319 outsize = insize * Py_ARRAY_LENGTH(buffer);
7320
7321 if (*outbytes == NULL) {
7322 /* Create string object */
7323 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7324 if (*outbytes == NULL)
7325 goto error;
7326 out = PyBytes_AS_STRING(*outbytes);
7327 }
7328 else {
7329 /* Extend string object */
7330 Py_ssize_t n = PyBytes_Size(*outbytes);
7331 if (n > PY_SSIZE_T_MAX - outsize) {
7332 PyErr_NoMemory();
7333 goto error;
7334 }
7335 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7336 goto error;
7337 out = PyBytes_AS_STRING(*outbytes) + n;
7338 }
7339
7340 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007341 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007342 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007343 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7344 wchar_t chars[2];
7345 int charsize;
7346 if (ch < 0x10000) {
7347 chars[0] = (wchar_t)ch;
7348 charsize = 1;
7349 }
7350 else {
7351 ch -= 0x10000;
7352 chars[0] = 0xd800 + (ch >> 10);
7353 chars[1] = 0xdc00 + (ch & 0x3ff);
7354 charsize = 2;
7355 }
7356
Victor Stinner3a50e702011-10-18 21:21:00 +02007357 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007358 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007359 buffer, Py_ARRAY_LENGTH(buffer),
7360 NULL, pusedDefaultChar);
7361 if (outsize > 0) {
7362 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7363 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007364 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007365 memcpy(out, buffer, outsize);
7366 out += outsize;
7367 continue;
7368 }
7369 }
7370 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7371 PyErr_SetFromWindowsErr(0);
7372 goto error;
7373 }
7374
Victor Stinner3a50e702011-10-18 21:21:00 +02007375 rep = unicode_encode_call_errorhandler(
7376 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007377 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007378 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007379 if (rep == NULL)
7380 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007381 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007382
7383 if (PyBytes_Check(rep)) {
7384 outsize = PyBytes_GET_SIZE(rep);
7385 if (outsize != 1) {
7386 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7387 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7388 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7389 Py_DECREF(rep);
7390 goto error;
7391 }
7392 out = PyBytes_AS_STRING(*outbytes) + offset;
7393 }
7394 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7395 out += outsize;
7396 }
7397 else {
7398 Py_ssize_t i;
7399 enum PyUnicode_Kind kind;
7400 void *data;
7401
7402 if (PyUnicode_READY(rep) < 0) {
7403 Py_DECREF(rep);
7404 goto error;
7405 }
7406
7407 outsize = PyUnicode_GET_LENGTH(rep);
7408 if (outsize != 1) {
7409 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7410 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7411 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7412 Py_DECREF(rep);
7413 goto error;
7414 }
7415 out = PyBytes_AS_STRING(*outbytes) + offset;
7416 }
7417 kind = PyUnicode_KIND(rep);
7418 data = PyUnicode_DATA(rep);
7419 for (i=0; i < outsize; i++) {
7420 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7421 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007422 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007423 encoding, unicode,
7424 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007425 "unable to encode error handler result to ASCII");
7426 Py_DECREF(rep);
7427 goto error;
7428 }
7429 *out = (unsigned char)ch;
7430 out++;
7431 }
7432 }
7433 Py_DECREF(rep);
7434 }
7435 /* write a NUL byte */
7436 *out = 0;
7437 outsize = out - PyBytes_AS_STRING(*outbytes);
7438 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7439 if (_PyBytes_Resize(outbytes, outsize) < 0)
7440 goto error;
7441 ret = 0;
7442
7443error:
7444 Py_XDECREF(encoding_obj);
7445 Py_XDECREF(errorHandler);
7446 Py_XDECREF(exc);
7447 return ret;
7448}
7449
Victor Stinner3a50e702011-10-18 21:21:00 +02007450static PyObject *
7451encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007452 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007453 const char *errors)
7454{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007455 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007457 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007458 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007459
Victor Stinner2fc507f2011-11-04 20:06:39 +01007460 if (PyUnicode_READY(unicode) < 0)
7461 return NULL;
7462 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007463
Victor Stinner3a50e702011-10-18 21:21:00 +02007464 if (code_page < 0) {
7465 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7466 return NULL;
7467 }
7468
Martin v. Löwis3d325192011-11-04 18:23:06 +01007469 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007470 return PyBytes_FromStringAndSize(NULL, 0);
7471
Victor Stinner7581cef2011-11-03 22:32:33 +01007472 offset = 0;
7473 do
7474 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007475#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007476 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007477 chunks. */
7478 if (len > INT_MAX/2) {
7479 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007480 done = 0;
7481 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007482 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007483#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007484 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007485 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007486 done = 1;
7487 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007488
Victor Stinner76a31a62011-11-04 00:05:13 +01007489 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007490 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007491 errors);
7492 if (ret == -2)
7493 ret = encode_code_page_errors(code_page, &outbytes,
7494 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007495 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007496 if (ret < 0) {
7497 Py_XDECREF(outbytes);
7498 return NULL;
7499 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007500
Victor Stinner7581cef2011-11-03 22:32:33 +01007501 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007502 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007503 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007504
Victor Stinner3a50e702011-10-18 21:21:00 +02007505 return outbytes;
7506}
7507
7508PyObject *
7509PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7510 Py_ssize_t size,
7511 const char *errors)
7512{
Victor Stinner7581cef2011-11-03 22:32:33 +01007513 PyObject *unicode, *res;
7514 unicode = PyUnicode_FromUnicode(p, size);
7515 if (unicode == NULL)
7516 return NULL;
7517 res = encode_code_page(CP_ACP, unicode, errors);
7518 Py_DECREF(unicode);
7519 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007520}
7521
7522PyObject *
7523PyUnicode_EncodeCodePage(int code_page,
7524 PyObject *unicode,
7525 const char *errors)
7526{
Victor Stinner7581cef2011-11-03 22:32:33 +01007527 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007528}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007529
Alexander Belopolsky40018472011-02-26 01:02:56 +00007530PyObject *
7531PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007532{
7533 if (!PyUnicode_Check(unicode)) {
7534 PyErr_BadArgument();
7535 return NULL;
7536 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007537 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007538}
7539
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007540#undef NEED_RETRY
7541
Victor Stinner99b95382011-07-04 14:23:54 +02007542#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007543
Guido van Rossumd57fd912000-03-10 22:53:23 +00007544/* --- Character Mapping Codec -------------------------------------------- */
7545
Alexander Belopolsky40018472011-02-26 01:02:56 +00007546PyObject *
7547PyUnicode_DecodeCharmap(const char *s,
7548 Py_ssize_t size,
7549 PyObject *mapping,
7550 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007551{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007552 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007553 Py_ssize_t startinpos;
7554 Py_ssize_t endinpos;
7555 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007556 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007557 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007558 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007559 PyObject *errorHandler = NULL;
7560 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007561
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562 /* Default to Latin-1 */
7563 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007564 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007565
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007566 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007567 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007568 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007569 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007570 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007571 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007572 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007573 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007574 Py_ssize_t maplen;
7575 enum PyUnicode_Kind kind;
7576 void *data;
7577 Py_UCS4 x;
7578
7579 if (PyUnicode_READY(mapping) < 0)
7580 return NULL;
7581
7582 maplen = PyUnicode_GET_LENGTH(mapping);
7583 data = PyUnicode_DATA(mapping);
7584 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007585 while (s < e) {
7586 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007587
Benjamin Peterson29060642009-01-31 22:14:21 +00007588 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007589 x = PyUnicode_READ(kind, data, ch);
7590 else
7591 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007592
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007593 if (x == 0xfffe)
7594 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007595 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007596 startinpos = s-starts;
7597 endinpos = startinpos+1;
7598 if (unicode_decode_call_errorhandler(
7599 errors, &errorHandler,
7600 "charmap", "character maps to <undefined>",
7601 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007602 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007603 goto onError;
7604 }
7605 continue;
7606 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007607
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007608 if (unicode_putchar(&v, &outpos, x) < 0)
7609 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007610 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007611 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007612 }
7613 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007614 while (s < e) {
7615 unsigned char ch = *s;
7616 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007617
Benjamin Peterson29060642009-01-31 22:14:21 +00007618 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7619 w = PyLong_FromLong((long)ch);
7620 if (w == NULL)
7621 goto onError;
7622 x = PyObject_GetItem(mapping, w);
7623 Py_DECREF(w);
7624 if (x == NULL) {
7625 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7626 /* No mapping found means: mapping is undefined. */
7627 PyErr_Clear();
7628 x = Py_None;
7629 Py_INCREF(x);
7630 } else
7631 goto onError;
7632 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007633
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 /* Apply mapping */
7635 if (PyLong_Check(x)) {
7636 long value = PyLong_AS_LONG(x);
7637 if (value < 0 || value > 65535) {
7638 PyErr_SetString(PyExc_TypeError,
7639 "character mapping must be in range(65536)");
7640 Py_DECREF(x);
7641 goto onError;
7642 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007643 if (unicode_putchar(&v, &outpos, value) < 0)
7644 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007645 }
7646 else if (x == Py_None) {
7647 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007648 startinpos = s-starts;
7649 endinpos = startinpos+1;
7650 if (unicode_decode_call_errorhandler(
7651 errors, &errorHandler,
7652 "charmap", "character maps to <undefined>",
7653 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007654 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007655 Py_DECREF(x);
7656 goto onError;
7657 }
7658 Py_DECREF(x);
7659 continue;
7660 }
7661 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007662 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007663
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007664 if (PyUnicode_READY(x) < 0)
7665 goto onError;
7666 targetsize = PyUnicode_GET_LENGTH(x);
7667
7668 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007669 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007670 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007671 PyUnicode_READ_CHAR(x, 0)) < 0)
7672 goto onError;
7673 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007674 else if (targetsize > 1) {
7675 /* 1-n mapping */
7676 if (targetsize > extrachars) {
7677 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007678 Py_ssize_t needed = (targetsize - extrachars) + \
7679 (targetsize << 2);
7680 extrachars += needed;
7681 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007682 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007683 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007684 Py_DECREF(x);
7685 goto onError;
7686 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007688 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7689 goto onError;
7690 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7691 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007692 extrachars -= targetsize;
7693 }
7694 /* 1-0 mapping: skip the character */
7695 }
7696 else {
7697 /* wrong return value */
7698 PyErr_SetString(PyExc_TypeError,
7699 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007700 Py_DECREF(x);
7701 goto onError;
7702 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007703 Py_DECREF(x);
7704 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007705 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007706 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007707 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007708 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007709 Py_XDECREF(errorHandler);
7710 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007711 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007712 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007713
Benjamin Peterson29060642009-01-31 22:14:21 +00007714 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007715 Py_XDECREF(errorHandler);
7716 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007717 Py_XDECREF(v);
7718 return NULL;
7719}
7720
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007721/* Charmap encoding: the lookup table */
7722
Alexander Belopolsky40018472011-02-26 01:02:56 +00007723struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007724 PyObject_HEAD
7725 unsigned char level1[32];
7726 int count2, count3;
7727 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007728};
7729
7730static PyObject*
7731encoding_map_size(PyObject *obj, PyObject* args)
7732{
7733 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007734 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007735 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007736}
7737
7738static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007739 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007740 PyDoc_STR("Return the size (in bytes) of this object") },
7741 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007742};
7743
7744static void
7745encoding_map_dealloc(PyObject* o)
7746{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007747 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007748}
7749
7750static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007751 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007752 "EncodingMap", /*tp_name*/
7753 sizeof(struct encoding_map), /*tp_basicsize*/
7754 0, /*tp_itemsize*/
7755 /* methods */
7756 encoding_map_dealloc, /*tp_dealloc*/
7757 0, /*tp_print*/
7758 0, /*tp_getattr*/
7759 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007760 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007761 0, /*tp_repr*/
7762 0, /*tp_as_number*/
7763 0, /*tp_as_sequence*/
7764 0, /*tp_as_mapping*/
7765 0, /*tp_hash*/
7766 0, /*tp_call*/
7767 0, /*tp_str*/
7768 0, /*tp_getattro*/
7769 0, /*tp_setattro*/
7770 0, /*tp_as_buffer*/
7771 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7772 0, /*tp_doc*/
7773 0, /*tp_traverse*/
7774 0, /*tp_clear*/
7775 0, /*tp_richcompare*/
7776 0, /*tp_weaklistoffset*/
7777 0, /*tp_iter*/
7778 0, /*tp_iternext*/
7779 encoding_map_methods, /*tp_methods*/
7780 0, /*tp_members*/
7781 0, /*tp_getset*/
7782 0, /*tp_base*/
7783 0, /*tp_dict*/
7784 0, /*tp_descr_get*/
7785 0, /*tp_descr_set*/
7786 0, /*tp_dictoffset*/
7787 0, /*tp_init*/
7788 0, /*tp_alloc*/
7789 0, /*tp_new*/
7790 0, /*tp_free*/
7791 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007792};
7793
7794PyObject*
7795PyUnicode_BuildEncodingMap(PyObject* string)
7796{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007797 PyObject *result;
7798 struct encoding_map *mresult;
7799 int i;
7800 int need_dict = 0;
7801 unsigned char level1[32];
7802 unsigned char level2[512];
7803 unsigned char *mlevel1, *mlevel2, *mlevel3;
7804 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007805 int kind;
7806 void *data;
7807 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007809 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007810 PyErr_BadArgument();
7811 return NULL;
7812 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007813 kind = PyUnicode_KIND(string);
7814 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007815 memset(level1, 0xFF, sizeof level1);
7816 memset(level2, 0xFF, sizeof level2);
7817
7818 /* If there isn't a one-to-one mapping of NULL to \0,
7819 or if there are non-BMP characters, we need to use
7820 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007821 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007822 need_dict = 1;
7823 for (i = 1; i < 256; i++) {
7824 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007825 ch = PyUnicode_READ(kind, data, i);
7826 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007827 need_dict = 1;
7828 break;
7829 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007830 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007831 /* unmapped character */
7832 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007833 l1 = ch >> 11;
7834 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007835 if (level1[l1] == 0xFF)
7836 level1[l1] = count2++;
7837 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007838 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007839 }
7840
7841 if (count2 >= 0xFF || count3 >= 0xFF)
7842 need_dict = 1;
7843
7844 if (need_dict) {
7845 PyObject *result = PyDict_New();
7846 PyObject *key, *value;
7847 if (!result)
7848 return NULL;
7849 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007850 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007851 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007852 if (!key || !value)
7853 goto failed1;
7854 if (PyDict_SetItem(result, key, value) == -1)
7855 goto failed1;
7856 Py_DECREF(key);
7857 Py_DECREF(value);
7858 }
7859 return result;
7860 failed1:
7861 Py_XDECREF(key);
7862 Py_XDECREF(value);
7863 Py_DECREF(result);
7864 return NULL;
7865 }
7866
7867 /* Create a three-level trie */
7868 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7869 16*count2 + 128*count3 - 1);
7870 if (!result)
7871 return PyErr_NoMemory();
7872 PyObject_Init(result, &EncodingMapType);
7873 mresult = (struct encoding_map*)result;
7874 mresult->count2 = count2;
7875 mresult->count3 = count3;
7876 mlevel1 = mresult->level1;
7877 mlevel2 = mresult->level23;
7878 mlevel3 = mresult->level23 + 16*count2;
7879 memcpy(mlevel1, level1, 32);
7880 memset(mlevel2, 0xFF, 16*count2);
7881 memset(mlevel3, 0, 128*count3);
7882 count3 = 0;
7883 for (i = 1; i < 256; i++) {
7884 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007885 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007886 /* unmapped character */
7887 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007888 o1 = PyUnicode_READ(kind, data, i)>>11;
7889 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007890 i2 = 16*mlevel1[o1] + o2;
7891 if (mlevel2[i2] == 0xFF)
7892 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007893 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007894 i3 = 128*mlevel2[i2] + o3;
7895 mlevel3[i3] = i;
7896 }
7897 return result;
7898}
7899
7900static int
7901encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7902{
7903 struct encoding_map *map = (struct encoding_map*)mapping;
7904 int l1 = c>>11;
7905 int l2 = (c>>7) & 0xF;
7906 int l3 = c & 0x7F;
7907 int i;
7908
7909#ifdef Py_UNICODE_WIDE
7910 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007911 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007912 }
7913#endif
7914 if (c == 0)
7915 return 0;
7916 /* level 1*/
7917 i = map->level1[l1];
7918 if (i == 0xFF) {
7919 return -1;
7920 }
7921 /* level 2*/
7922 i = map->level23[16*i+l2];
7923 if (i == 0xFF) {
7924 return -1;
7925 }
7926 /* level 3 */
7927 i = map->level23[16*map->count2 + 128*i + l3];
7928 if (i == 0) {
7929 return -1;
7930 }
7931 return i;
7932}
7933
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007934/* Lookup the character ch in the mapping. If the character
7935 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007936 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007937static PyObject *
7938charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007939{
Christian Heimes217cfd12007-12-02 14:31:20 +00007940 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007941 PyObject *x;
7942
7943 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007944 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007945 x = PyObject_GetItem(mapping, w);
7946 Py_DECREF(w);
7947 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007948 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7949 /* No mapping found means: mapping is undefined. */
7950 PyErr_Clear();
7951 x = Py_None;
7952 Py_INCREF(x);
7953 return x;
7954 } else
7955 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007956 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007957 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007958 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007959 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007960 long value = PyLong_AS_LONG(x);
7961 if (value < 0 || value > 255) {
7962 PyErr_SetString(PyExc_TypeError,
7963 "character mapping must be in range(256)");
7964 Py_DECREF(x);
7965 return NULL;
7966 }
7967 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007968 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007969 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007970 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007971 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007972 /* wrong return value */
7973 PyErr_Format(PyExc_TypeError,
7974 "character mapping must return integer, bytes or None, not %.400s",
7975 x->ob_type->tp_name);
7976 Py_DECREF(x);
7977 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007978 }
7979}
7980
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007981static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007982charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007983{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007984 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7985 /* exponentially overallocate to minimize reallocations */
7986 if (requiredsize < 2*outsize)
7987 requiredsize = 2*outsize;
7988 if (_PyBytes_Resize(outobj, requiredsize))
7989 return -1;
7990 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007991}
7992
Benjamin Peterson14339b62009-01-31 16:36:08 +00007993typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007994 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007995} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007996/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007997 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007998 space is available. Return a new reference to the object that
7999 was put in the output buffer, or Py_None, if the mapping was undefined
8000 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00008001 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008002static charmapencode_result
8003charmapencode_output(Py_UNICODE c, PyObject *mapping,
8004 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008005{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008006 PyObject *rep;
8007 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00008008 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008009
Christian Heimes90aa7642007-12-19 02:45:37 +00008010 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008011 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008012 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013 if (res == -1)
8014 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 if (outsize<requiredsize)
8016 if (charmapencode_resize(outobj, outpos, requiredsize))
8017 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008018 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008019 outstart[(*outpos)++] = (char)res;
8020 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008021 }
8022
8023 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008024 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008026 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008027 Py_DECREF(rep);
8028 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008029 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008030 if (PyLong_Check(rep)) {
8031 Py_ssize_t requiredsize = *outpos+1;
8032 if (outsize<requiredsize)
8033 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8034 Py_DECREF(rep);
8035 return enc_EXCEPTION;
8036 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008037 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008038 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008039 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008040 else {
8041 const char *repchars = PyBytes_AS_STRING(rep);
8042 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8043 Py_ssize_t requiredsize = *outpos+repsize;
8044 if (outsize<requiredsize)
8045 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8046 Py_DECREF(rep);
8047 return enc_EXCEPTION;
8048 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008049 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 memcpy(outstart + *outpos, repchars, repsize);
8051 *outpos += repsize;
8052 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008053 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008054 Py_DECREF(rep);
8055 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008056}
8057
8058/* handle an error in PyUnicode_EncodeCharmap
8059 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008060static int
8061charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008062 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008063 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008064 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008065 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008066{
8067 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008068 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008069 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008070 Py_UNICODE *uni2;
8071 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008072 Py_ssize_t collstartpos = *inpos;
8073 Py_ssize_t collendpos = *inpos+1;
8074 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008075 char *encoding = "charmap";
8076 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008077 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008078 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008079 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008080
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008081 if (PyUnicode_READY(unicode) < 0)
8082 return -1;
8083 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008084 /* find all unencodable characters */
8085 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008086 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008087 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008088 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008089 val = encoding_map_lookup(ch, mapping);
8090 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008091 break;
8092 ++collendpos;
8093 continue;
8094 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008095
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008096 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8097 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008098 if (rep==NULL)
8099 return -1;
8100 else if (rep!=Py_None) {
8101 Py_DECREF(rep);
8102 break;
8103 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008104 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008106 }
8107 /* cache callback name lookup
8108 * (if not done yet, i.e. it's the first error) */
8109 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008110 if ((errors==NULL) || (!strcmp(errors, "strict")))
8111 *known_errorHandler = 1;
8112 else if (!strcmp(errors, "replace"))
8113 *known_errorHandler = 2;
8114 else if (!strcmp(errors, "ignore"))
8115 *known_errorHandler = 3;
8116 else if (!strcmp(errors, "xmlcharrefreplace"))
8117 *known_errorHandler = 4;
8118 else
8119 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008120 }
8121 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008122 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008123 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008124 return -1;
8125 case 2: /* replace */
8126 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008127 x = charmapencode_output('?', mapping, res, respos);
8128 if (x==enc_EXCEPTION) {
8129 return -1;
8130 }
8131 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008132 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008133 return -1;
8134 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008135 }
8136 /* fall through */
8137 case 3: /* ignore */
8138 *inpos = collendpos;
8139 break;
8140 case 4: /* xmlcharrefreplace */
8141 /* generate replacement (temporarily (mis)uses p) */
8142 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008143 char buffer[2+29+1+1];
8144 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008145 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 for (cp = buffer; *cp; ++cp) {
8147 x = charmapencode_output(*cp, mapping, res, respos);
8148 if (x==enc_EXCEPTION)
8149 return -1;
8150 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008151 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 return -1;
8153 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008154 }
8155 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 *inpos = collendpos;
8157 break;
8158 default:
8159 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008160 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008161 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008162 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008164 if (PyBytes_Check(repunicode)) {
8165 /* Directly copy bytes result to output. */
8166 Py_ssize_t outsize = PyBytes_Size(*res);
8167 Py_ssize_t requiredsize;
8168 repsize = PyBytes_Size(repunicode);
8169 requiredsize = *respos + repsize;
8170 if (requiredsize > outsize)
8171 /* Make room for all additional bytes. */
8172 if (charmapencode_resize(res, respos, requiredsize)) {
8173 Py_DECREF(repunicode);
8174 return -1;
8175 }
8176 memcpy(PyBytes_AsString(*res) + *respos,
8177 PyBytes_AsString(repunicode), repsize);
8178 *respos += repsize;
8179 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008180 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008181 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008182 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008183 /* generate replacement */
8184 repsize = PyUnicode_GET_SIZE(repunicode);
8185 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008186 x = charmapencode_output(*uni2, mapping, res, respos);
8187 if (x==enc_EXCEPTION) {
8188 return -1;
8189 }
8190 else if (x==enc_FAILED) {
8191 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008192 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008193 return -1;
8194 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008195 }
8196 *inpos = newpos;
8197 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008198 }
8199 return 0;
8200}
8201
Alexander Belopolsky40018472011-02-26 01:02:56 +00008202PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008203_PyUnicode_EncodeCharmap(PyObject *unicode,
8204 PyObject *mapping,
8205 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008206{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008207 /* output object */
8208 PyObject *res = NULL;
8209 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008210 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008211 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008212 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008213 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214 PyObject *errorHandler = NULL;
8215 PyObject *exc = NULL;
8216 /* the following variable is used for caching string comparisons
8217 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8218 * 3=ignore, 4=xmlcharrefreplace */
8219 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008220
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008221 if (PyUnicode_READY(unicode) < 0)
8222 return NULL;
8223 size = PyUnicode_GET_LENGTH(unicode);
8224
Guido van Rossumd57fd912000-03-10 22:53:23 +00008225 /* Default to Latin-1 */
8226 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008227 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008228
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008229 /* allocate enough for a simple encoding without
8230 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008231 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008232 if (res == NULL)
8233 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008234 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008235 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008236
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008237 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008238 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008239 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008240 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008241 if (x==enc_EXCEPTION) /* error */
8242 goto onError;
8243 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008244 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 &exc,
8246 &known_errorHandler, &errorHandler, errors,
8247 &res, &respos)) {
8248 goto onError;
8249 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008250 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 else
8252 /* done with this character => adjust input position */
8253 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008255
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008256 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008257 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008258 if (_PyBytes_Resize(&res, respos) < 0)
8259 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008260
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008261 Py_XDECREF(exc);
8262 Py_XDECREF(errorHandler);
8263 return res;
8264
Benjamin Peterson29060642009-01-31 22:14:21 +00008265 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 Py_XDECREF(res);
8267 Py_XDECREF(exc);
8268 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008269 return NULL;
8270}
8271
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008272/* Deprecated */
8273PyObject *
8274PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8275 Py_ssize_t size,
8276 PyObject *mapping,
8277 const char *errors)
8278{
8279 PyObject *result;
8280 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8281 if (unicode == NULL)
8282 return NULL;
8283 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8284 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008285 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008286}
8287
Alexander Belopolsky40018472011-02-26 01:02:56 +00008288PyObject *
8289PyUnicode_AsCharmapString(PyObject *unicode,
8290 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008291{
8292 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 PyErr_BadArgument();
8294 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008295 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008296 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008297}
8298
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008299/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008300static void
8301make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008302 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008303 Py_ssize_t startpos, Py_ssize_t endpos,
8304 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008305{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008306 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008307 *exceptionObject = _PyUnicodeTranslateError_Create(
8308 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008309 }
8310 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008311 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8312 goto onError;
8313 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8314 goto onError;
8315 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8316 goto onError;
8317 return;
8318 onError:
8319 Py_DECREF(*exceptionObject);
8320 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008321 }
8322}
8323
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008325static void
8326raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008327 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008328 Py_ssize_t startpos, Py_ssize_t endpos,
8329 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008330{
8331 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008332 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008334 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335}
8336
8337/* error handling callback helper:
8338 build arguments, call the callback and check the arguments,
8339 put the result into newpos and return the replacement string, which
8340 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008341static PyObject *
8342unicode_translate_call_errorhandler(const char *errors,
8343 PyObject **errorHandler,
8344 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008345 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008346 Py_ssize_t startpos, Py_ssize_t endpos,
8347 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008349 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008351 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008352 PyObject *restuple;
8353 PyObject *resunicode;
8354
8355 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008356 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008357 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008358 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 }
8360
8361 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008362 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008363 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008364 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008365
8366 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008368 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008369 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008370 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008371 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008372 Py_DECREF(restuple);
8373 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374 }
8375 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 &resunicode, &i_newpos)) {
8377 Py_DECREF(restuple);
8378 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008379 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008380 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008381 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008382 else
8383 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008384 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8386 Py_DECREF(restuple);
8387 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008388 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 Py_INCREF(resunicode);
8390 Py_DECREF(restuple);
8391 return resunicode;
8392}
8393
8394/* Lookup the character ch in the mapping and put the result in result,
8395 which must be decrefed by the caller.
8396 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008397static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008398charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399{
Christian Heimes217cfd12007-12-02 14:31:20 +00008400 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008401 PyObject *x;
8402
8403 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008405 x = PyObject_GetItem(mapping, w);
8406 Py_DECREF(w);
8407 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8409 /* No mapping found means: use 1:1 mapping. */
8410 PyErr_Clear();
8411 *result = NULL;
8412 return 0;
8413 } else
8414 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 }
8416 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008417 *result = x;
8418 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008420 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008421 long value = PyLong_AS_LONG(x);
8422 long max = PyUnicode_GetMax();
8423 if (value < 0 || value > max) {
8424 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008425 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008426 Py_DECREF(x);
8427 return -1;
8428 }
8429 *result = x;
8430 return 0;
8431 }
8432 else if (PyUnicode_Check(x)) {
8433 *result = x;
8434 return 0;
8435 }
8436 else {
8437 /* wrong return value */
8438 PyErr_SetString(PyExc_TypeError,
8439 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008440 Py_DECREF(x);
8441 return -1;
8442 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008443}
8444/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008445 if not reallocate and adjust various state variables.
8446 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008447static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008448charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008449 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008450{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008451 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008452 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008453 /* exponentially overallocate to minimize reallocations */
8454 if (requiredsize < 2 * oldsize)
8455 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008456 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8457 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008458 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008459 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460 }
8461 return 0;
8462}
8463/* lookup the character, put the result in the output string and adjust
8464 various state variables. Return a new reference to the object that
8465 was put in the output buffer in *result, or Py_None, if the mapping was
8466 undefined (in which case no character was written).
8467 The called must decref result.
8468 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008469static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008470charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8471 PyObject *mapping, Py_UCS4 **output,
8472 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008473 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008475 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8476 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008477 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008478 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008479 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008481 }
8482 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008483 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008484 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008485 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008486 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008487 }
8488 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008489 Py_ssize_t repsize;
8490 if (PyUnicode_READY(*res) == -1)
8491 return -1;
8492 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 if (repsize==1) {
8494 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008495 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008496 }
8497 else if (repsize!=0) {
8498 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 Py_ssize_t requiredsize = *opos +
8500 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008501 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008502 Py_ssize_t i;
8503 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008504 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008505 for(i = 0; i < repsize; i++)
8506 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008507 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008508 }
8509 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008510 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008511 return 0;
8512}
8513
Alexander Belopolsky40018472011-02-26 01:02:56 +00008514PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515_PyUnicode_TranslateCharmap(PyObject *input,
8516 PyObject *mapping,
8517 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008518{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008519 /* input object */
8520 char *idata;
8521 Py_ssize_t size, i;
8522 int kind;
8523 /* output buffer */
8524 Py_UCS4 *output = NULL;
8525 Py_ssize_t osize;
8526 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008527 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008528 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008529 char *reason = "character maps to <undefined>";
8530 PyObject *errorHandler = NULL;
8531 PyObject *exc = NULL;
8532 /* the following variable is used for caching string comparisons
8533 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8534 * 3=ignore, 4=xmlcharrefreplace */
8535 int known_errorHandler = -1;
8536
Guido van Rossumd57fd912000-03-10 22:53:23 +00008537 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008538 PyErr_BadArgument();
8539 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008540 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008541
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008542 if (PyUnicode_READY(input) == -1)
8543 return NULL;
8544 idata = (char*)PyUnicode_DATA(input);
8545 kind = PyUnicode_KIND(input);
8546 size = PyUnicode_GET_LENGTH(input);
8547 i = 0;
8548
8549 if (size == 0) {
8550 Py_INCREF(input);
8551 return input;
8552 }
8553
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008554 /* allocate enough for a simple 1:1 translation without
8555 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008556 osize = size;
8557 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8558 opos = 0;
8559 if (output == NULL) {
8560 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008561 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008562 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008563
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008564 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 /* try to encode it */
8566 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008567 if (charmaptranslate_output(input, i, mapping,
8568 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008569 Py_XDECREF(x);
8570 goto onError;
8571 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008572 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 else { /* untranslatable character */
8576 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8577 Py_ssize_t repsize;
8578 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008579 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008580 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 Py_ssize_t collstart = i;
8582 Py_ssize_t collend = i+1;
8583 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008584
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008586 while (collend < size) {
8587 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 goto onError;
8589 Py_XDECREF(x);
8590 if (x!=Py_None)
8591 break;
8592 ++collend;
8593 }
8594 /* cache callback name lookup
8595 * (if not done yet, i.e. it's the first error) */
8596 if (known_errorHandler==-1) {
8597 if ((errors==NULL) || (!strcmp(errors, "strict")))
8598 known_errorHandler = 1;
8599 else if (!strcmp(errors, "replace"))
8600 known_errorHandler = 2;
8601 else if (!strcmp(errors, "ignore"))
8602 known_errorHandler = 3;
8603 else if (!strcmp(errors, "xmlcharrefreplace"))
8604 known_errorHandler = 4;
8605 else
8606 known_errorHandler = 0;
8607 }
8608 switch (known_errorHandler) {
8609 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008610 raise_translate_exception(&exc, input, collstart,
8611 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008612 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008613 case 2: /* replace */
8614 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008615 for (coll = collstart; coll<collend; coll++)
8616 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 /* fall through */
8618 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008619 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008620 break;
8621 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 /* generate replacement (temporarily (mis)uses i) */
8623 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008624 char buffer[2+29+1+1];
8625 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008626 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8627 if (charmaptranslate_makespace(&output, &osize,
8628 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008629 goto onError;
8630 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008631 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 break;
8635 default:
8636 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008637 reason, input, &exc,
8638 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008639 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008640 goto onError;
8641 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008642 repsize = PyUnicode_GET_LENGTH(repunicode);
8643 if (charmaptranslate_makespace(&output, &osize,
8644 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008645 Py_DECREF(repunicode);
8646 goto onError;
8647 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008648 for (uni2 = 0; repsize-->0; ++uni2)
8649 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8650 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008652 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008653 }
8654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8656 if (!res)
8657 goto onError;
8658 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008659 Py_XDECREF(exc);
8660 Py_XDECREF(errorHandler);
8661 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008662
Benjamin Peterson29060642009-01-31 22:14:21 +00008663 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008664 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008665 Py_XDECREF(exc);
8666 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008667 return NULL;
8668}
8669
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008670/* Deprecated. Use PyUnicode_Translate instead. */
8671PyObject *
8672PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8673 Py_ssize_t size,
8674 PyObject *mapping,
8675 const char *errors)
8676{
8677 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8678 if (!unicode)
8679 return NULL;
8680 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8681}
8682
Alexander Belopolsky40018472011-02-26 01:02:56 +00008683PyObject *
8684PyUnicode_Translate(PyObject *str,
8685 PyObject *mapping,
8686 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008687{
8688 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008689
Guido van Rossumd57fd912000-03-10 22:53:23 +00008690 str = PyUnicode_FromObject(str);
8691 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008692 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008693 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008694 Py_DECREF(str);
8695 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008696
Benjamin Peterson29060642009-01-31 22:14:21 +00008697 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008698 Py_XDECREF(str);
8699 return NULL;
8700}
Tim Petersced69f82003-09-16 20:30:58 +00008701
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008702static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008703fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008704{
8705 /* No need to call PyUnicode_READY(self) because this function is only
8706 called as a callback from fixup() which does it already. */
8707 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8708 const int kind = PyUnicode_KIND(self);
8709 void *data = PyUnicode_DATA(self);
8710 Py_UCS4 maxchar = 0, ch, fixed;
8711 Py_ssize_t i;
8712
8713 for (i = 0; i < len; ++i) {
8714 ch = PyUnicode_READ(kind, data, i);
8715 fixed = 0;
8716 if (ch > 127) {
8717 if (Py_UNICODE_ISSPACE(ch))
8718 fixed = ' ';
8719 else {
8720 const int decimal = Py_UNICODE_TODECIMAL(ch);
8721 if (decimal >= 0)
8722 fixed = '0' + decimal;
8723 }
8724 if (fixed != 0) {
8725 if (fixed > maxchar)
8726 maxchar = fixed;
8727 PyUnicode_WRITE(kind, data, i, fixed);
8728 }
8729 else if (ch > maxchar)
8730 maxchar = ch;
8731 }
8732 else if (ch > maxchar)
8733 maxchar = ch;
8734 }
8735
8736 return maxchar;
8737}
8738
8739PyObject *
8740_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8741{
8742 if (!PyUnicode_Check(unicode)) {
8743 PyErr_BadInternalCall();
8744 return NULL;
8745 }
8746 if (PyUnicode_READY(unicode) == -1)
8747 return NULL;
8748 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8749 /* If the string is already ASCII, just return the same string */
8750 Py_INCREF(unicode);
8751 return unicode;
8752 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008753 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008754}
8755
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008756PyObject *
8757PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8758 Py_ssize_t length)
8759{
8760 PyObject *result;
8761 Py_UNICODE *p; /* write pointer into result */
8762 Py_ssize_t i;
8763 /* Copy to a new string */
8764 result = (PyObject *)_PyUnicode_New(length);
8765 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8766 if (result == NULL)
8767 return result;
8768 p = PyUnicode_AS_UNICODE(result);
8769 /* Iterate over code points */
8770 for (i = 0; i < length; i++) {
8771 Py_UNICODE ch =s[i];
8772 if (ch > 127) {
8773 int decimal = Py_UNICODE_TODECIMAL(ch);
8774 if (decimal >= 0)
8775 p[i] = '0' + decimal;
8776 }
8777 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008778#ifndef DONT_MAKE_RESULT_READY
8779 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008780 Py_DECREF(result);
8781 return NULL;
8782 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008783#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008784 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008785 return result;
8786}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008787/* --- Decimal Encoder ---------------------------------------------------- */
8788
Alexander Belopolsky40018472011-02-26 01:02:56 +00008789int
8790PyUnicode_EncodeDecimal(Py_UNICODE *s,
8791 Py_ssize_t length,
8792 char *output,
8793 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008794{
8795 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008796 PyObject *errorHandler = NULL;
8797 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008798 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008799 const char *encoding = "decimal";
8800 const char *reason = "invalid decimal Unicode string";
8801 /* the following variable is used for caching string comparisons
8802 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8803 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008804
8805 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008806 PyErr_BadArgument();
8807 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008808 }
8809
8810 p = s;
8811 end = s + length;
8812 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008813 register Py_UNICODE ch = *p;
8814 int decimal;
8815 PyObject *repunicode;
8816 Py_ssize_t repsize;
8817 Py_ssize_t newpos;
8818 Py_UNICODE *uni2;
8819 Py_UNICODE *collstart;
8820 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008821
Benjamin Peterson29060642009-01-31 22:14:21 +00008822 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008823 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008824 ++p;
8825 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008826 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008827 decimal = Py_UNICODE_TODECIMAL(ch);
8828 if (decimal >= 0) {
8829 *output++ = '0' + decimal;
8830 ++p;
8831 continue;
8832 }
8833 if (0 < ch && ch < 256) {
8834 *output++ = (char)ch;
8835 ++p;
8836 continue;
8837 }
8838 /* All other characters are considered unencodable */
8839 collstart = p;
8840 collend = p+1;
8841 while (collend < end) {
8842 if ((0 < *collend && *collend < 256) ||
8843 !Py_UNICODE_ISSPACE(*collend) ||
8844 Py_UNICODE_TODECIMAL(*collend))
8845 break;
8846 }
8847 /* cache callback name lookup
8848 * (if not done yet, i.e. it's the first error) */
8849 if (known_errorHandler==-1) {
8850 if ((errors==NULL) || (!strcmp(errors, "strict")))
8851 known_errorHandler = 1;
8852 else if (!strcmp(errors, "replace"))
8853 known_errorHandler = 2;
8854 else if (!strcmp(errors, "ignore"))
8855 known_errorHandler = 3;
8856 else if (!strcmp(errors, "xmlcharrefreplace"))
8857 known_errorHandler = 4;
8858 else
8859 known_errorHandler = 0;
8860 }
8861 switch (known_errorHandler) {
8862 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008863 unicode = PyUnicode_FromUnicode(s, length);
8864 if (unicode == NULL)
8865 goto onError;
8866 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8867 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008868 goto onError;
8869 case 2: /* replace */
8870 for (p = collstart; p < collend; ++p)
8871 *output++ = '?';
8872 /* fall through */
8873 case 3: /* ignore */
8874 p = collend;
8875 break;
8876 case 4: /* xmlcharrefreplace */
8877 /* generate replacement (temporarily (mis)uses p) */
8878 for (p = collstart; p < collend; ++p)
8879 output += sprintf(output, "&#%d;", (int)*p);
8880 p = collend;
8881 break;
8882 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008883 unicode = PyUnicode_FromUnicode(s, length);
8884 if (unicode == NULL)
8885 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008886 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008887 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008888 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008889 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008890 if (repunicode == NULL)
8891 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008892 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008893 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008894 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8895 Py_DECREF(repunicode);
8896 goto onError;
8897 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008898 /* generate replacement */
8899 repsize = PyUnicode_GET_SIZE(repunicode);
8900 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8901 Py_UNICODE ch = *uni2;
8902 if (Py_UNICODE_ISSPACE(ch))
8903 *output++ = ' ';
8904 else {
8905 decimal = Py_UNICODE_TODECIMAL(ch);
8906 if (decimal >= 0)
8907 *output++ = '0' + decimal;
8908 else if (0 < ch && ch < 256)
8909 *output++ = (char)ch;
8910 else {
8911 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008912 unicode = PyUnicode_FromUnicode(s, length);
8913 if (unicode == NULL)
8914 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008915 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008916 unicode, collstart-s, collend-s, reason);
8917 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008918 goto onError;
8919 }
8920 }
8921 }
8922 p = s + newpos;
8923 Py_DECREF(repunicode);
8924 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008925 }
8926 /* 0-terminate the output string */
8927 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008928 Py_XDECREF(exc);
8929 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008930 return 0;
8931
Benjamin Peterson29060642009-01-31 22:14:21 +00008932 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008933 Py_XDECREF(exc);
8934 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008935 return -1;
8936}
8937
Guido van Rossumd57fd912000-03-10 22:53:23 +00008938/* --- Helpers ------------------------------------------------------------ */
8939
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008940static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008941any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008942 Py_ssize_t start,
8943 Py_ssize_t end)
8944{
8945 int kind1, kind2, kind;
8946 void *buf1, *buf2;
8947 Py_ssize_t len1, len2, result;
8948
8949 kind1 = PyUnicode_KIND(s1);
8950 kind2 = PyUnicode_KIND(s2);
8951 kind = kind1 > kind2 ? kind1 : kind2;
8952 buf1 = PyUnicode_DATA(s1);
8953 buf2 = PyUnicode_DATA(s2);
8954 if (kind1 != kind)
8955 buf1 = _PyUnicode_AsKind(s1, kind);
8956 if (!buf1)
8957 return -2;
8958 if (kind2 != kind)
8959 buf2 = _PyUnicode_AsKind(s2, kind);
8960 if (!buf2) {
8961 if (kind1 != kind) PyMem_Free(buf1);
8962 return -2;
8963 }
8964 len1 = PyUnicode_GET_LENGTH(s1);
8965 len2 = PyUnicode_GET_LENGTH(s2);
8966
Victor Stinner794d5672011-10-10 03:21:36 +02008967 if (direction > 0) {
8968 switch(kind) {
8969 case PyUnicode_1BYTE_KIND:
8970 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8971 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8972 else
8973 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8974 break;
8975 case PyUnicode_2BYTE_KIND:
8976 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8977 break;
8978 case PyUnicode_4BYTE_KIND:
8979 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8980 break;
8981 default:
8982 assert(0); result = -2;
8983 }
8984 }
8985 else {
8986 switch(kind) {
8987 case PyUnicode_1BYTE_KIND:
8988 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8989 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8990 else
8991 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8992 break;
8993 case PyUnicode_2BYTE_KIND:
8994 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8995 break;
8996 case PyUnicode_4BYTE_KIND:
8997 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8998 break;
8999 default:
9000 assert(0); result = -2;
9001 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009002 }
9003
9004 if (kind1 != kind)
9005 PyMem_Free(buf1);
9006 if (kind2 != kind)
9007 PyMem_Free(buf2);
9008
9009 return result;
9010}
9011
9012Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009013_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009014 Py_ssize_t n_buffer,
9015 void *digits, Py_ssize_t n_digits,
9016 Py_ssize_t min_width,
9017 const char *grouping,
9018 const char *thousands_sep)
9019{
9020 switch(kind) {
9021 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009022 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9023 return _PyUnicode_ascii_InsertThousandsGrouping(
9024 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9025 min_width, grouping, thousands_sep);
9026 else
9027 return _PyUnicode_ucs1_InsertThousandsGrouping(
9028 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9029 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009030 case PyUnicode_2BYTE_KIND:
9031 return _PyUnicode_ucs2_InsertThousandsGrouping(
9032 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9033 min_width, grouping, thousands_sep);
9034 case PyUnicode_4BYTE_KIND:
9035 return _PyUnicode_ucs4_InsertThousandsGrouping(
9036 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9037 min_width, grouping, thousands_sep);
9038 }
9039 assert(0);
9040 return -1;
9041}
9042
9043
Thomas Wouters477c8d52006-05-27 19:21:47 +00009044/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009045#define ADJUST_INDICES(start, end, len) \
9046 if (end > len) \
9047 end = len; \
9048 else if (end < 0) { \
9049 end += len; \
9050 if (end < 0) \
9051 end = 0; \
9052 } \
9053 if (start < 0) { \
9054 start += len; \
9055 if (start < 0) \
9056 start = 0; \
9057 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009058
Alexander Belopolsky40018472011-02-26 01:02:56 +00009059Py_ssize_t
9060PyUnicode_Count(PyObject *str,
9061 PyObject *substr,
9062 Py_ssize_t start,
9063 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009064{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009065 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009066 PyObject* str_obj;
9067 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009068 int kind1, kind2, kind;
9069 void *buf1 = NULL, *buf2 = NULL;
9070 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009071
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009072 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009073 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009074 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009075 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009076 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009077 Py_DECREF(str_obj);
9078 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009079 }
Tim Petersced69f82003-09-16 20:30:58 +00009080
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009081 kind1 = PyUnicode_KIND(str_obj);
9082 kind2 = PyUnicode_KIND(sub_obj);
9083 kind = kind1 > kind2 ? kind1 : kind2;
9084 buf1 = PyUnicode_DATA(str_obj);
9085 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009086 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009087 if (!buf1)
9088 goto onError;
9089 buf2 = PyUnicode_DATA(sub_obj);
9090 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009091 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009092 if (!buf2)
9093 goto onError;
9094 len1 = PyUnicode_GET_LENGTH(str_obj);
9095 len2 = PyUnicode_GET_LENGTH(sub_obj);
9096
9097 ADJUST_INDICES(start, end, len1);
9098 switch(kind) {
9099 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009100 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9101 result = asciilib_count(
9102 ((Py_UCS1*)buf1) + start, end - start,
9103 buf2, len2, PY_SSIZE_T_MAX
9104 );
9105 else
9106 result = ucs1lib_count(
9107 ((Py_UCS1*)buf1) + start, end - start,
9108 buf2, len2, PY_SSIZE_T_MAX
9109 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009110 break;
9111 case PyUnicode_2BYTE_KIND:
9112 result = ucs2lib_count(
9113 ((Py_UCS2*)buf1) + start, end - start,
9114 buf2, len2, PY_SSIZE_T_MAX
9115 );
9116 break;
9117 case PyUnicode_4BYTE_KIND:
9118 result = ucs4lib_count(
9119 ((Py_UCS4*)buf1) + start, end - start,
9120 buf2, len2, PY_SSIZE_T_MAX
9121 );
9122 break;
9123 default:
9124 assert(0); result = 0;
9125 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009126
9127 Py_DECREF(sub_obj);
9128 Py_DECREF(str_obj);
9129
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009130 if (kind1 != kind)
9131 PyMem_Free(buf1);
9132 if (kind2 != kind)
9133 PyMem_Free(buf2);
9134
Guido van Rossumd57fd912000-03-10 22:53:23 +00009135 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009136 onError:
9137 Py_DECREF(sub_obj);
9138 Py_DECREF(str_obj);
9139 if (kind1 != kind && buf1)
9140 PyMem_Free(buf1);
9141 if (kind2 != kind && buf2)
9142 PyMem_Free(buf2);
9143 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009144}
9145
Alexander Belopolsky40018472011-02-26 01:02:56 +00009146Py_ssize_t
9147PyUnicode_Find(PyObject *str,
9148 PyObject *sub,
9149 Py_ssize_t start,
9150 Py_ssize_t end,
9151 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009152{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009153 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009154
Guido van Rossumd57fd912000-03-10 22:53:23 +00009155 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009156 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009157 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009158 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009160 Py_DECREF(str);
9161 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162 }
Tim Petersced69f82003-09-16 20:30:58 +00009163
Victor Stinner794d5672011-10-10 03:21:36 +02009164 result = any_find_slice(direction,
9165 str, sub, start, end
9166 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009167
Guido van Rossumd57fd912000-03-10 22:53:23 +00009168 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009169 Py_DECREF(sub);
9170
Guido van Rossumd57fd912000-03-10 22:53:23 +00009171 return result;
9172}
9173
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009174Py_ssize_t
9175PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9176 Py_ssize_t start, Py_ssize_t end,
9177 int direction)
9178{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009180 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181 if (PyUnicode_READY(str) == -1)
9182 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009183 if (start < 0 || end < 0) {
9184 PyErr_SetString(PyExc_IndexError, "string index out of range");
9185 return -2;
9186 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009187 if (end > PyUnicode_GET_LENGTH(str))
9188 end = PyUnicode_GET_LENGTH(str);
9189 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009190 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9191 kind, end-start, ch, direction);
9192 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009193 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009194 else
9195 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009196}
9197
Alexander Belopolsky40018472011-02-26 01:02:56 +00009198static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009199tailmatch(PyObject *self,
9200 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009201 Py_ssize_t start,
9202 Py_ssize_t end,
9203 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009204{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 int kind_self;
9206 int kind_sub;
9207 void *data_self;
9208 void *data_sub;
9209 Py_ssize_t offset;
9210 Py_ssize_t i;
9211 Py_ssize_t end_sub;
9212
9213 if (PyUnicode_READY(self) == -1 ||
9214 PyUnicode_READY(substring) == -1)
9215 return 0;
9216
9217 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009218 return 1;
9219
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009220 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9221 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009222 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009223 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009224
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009225 kind_self = PyUnicode_KIND(self);
9226 data_self = PyUnicode_DATA(self);
9227 kind_sub = PyUnicode_KIND(substring);
9228 data_sub = PyUnicode_DATA(substring);
9229 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9230
9231 if (direction > 0)
9232 offset = end;
9233 else
9234 offset = start;
9235
9236 if (PyUnicode_READ(kind_self, data_self, offset) ==
9237 PyUnicode_READ(kind_sub, data_sub, 0) &&
9238 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9239 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9240 /* If both are of the same kind, memcmp is sufficient */
9241 if (kind_self == kind_sub) {
9242 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009243 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009244 data_sub,
9245 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009246 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009247 }
9248 /* otherwise we have to compare each character by first accesing it */
9249 else {
9250 /* We do not need to compare 0 and len(substring)-1 because
9251 the if statement above ensured already that they are equal
9252 when we end up here. */
9253 // TODO: honor direction and do a forward or backwards search
9254 for (i = 1; i < end_sub; ++i) {
9255 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9256 PyUnicode_READ(kind_sub, data_sub, i))
9257 return 0;
9258 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009259 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009261 }
9262
9263 return 0;
9264}
9265
Alexander Belopolsky40018472011-02-26 01:02:56 +00009266Py_ssize_t
9267PyUnicode_Tailmatch(PyObject *str,
9268 PyObject *substr,
9269 Py_ssize_t start,
9270 Py_ssize_t end,
9271 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009272{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009273 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009274
Guido van Rossumd57fd912000-03-10 22:53:23 +00009275 str = PyUnicode_FromObject(str);
9276 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009277 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009278 substr = PyUnicode_FromObject(substr);
9279 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009280 Py_DECREF(str);
9281 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282 }
Tim Petersced69f82003-09-16 20:30:58 +00009283
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009284 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009285 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009286 Py_DECREF(str);
9287 Py_DECREF(substr);
9288 return result;
9289}
9290
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291/* Apply fixfct filter to the Unicode object self and return a
9292 reference to the modified object */
9293
Alexander Belopolsky40018472011-02-26 01:02:56 +00009294static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009295fixup(PyObject *self,
9296 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009297{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009298 PyObject *u;
9299 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009300
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009301 if (PyUnicode_READY(self) == -1)
9302 return NULL;
9303 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9304 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9305 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009306 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009307 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009308
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009309 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009310 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 /* fix functions return the new maximum character in a string,
9313 if the kind of the resulting unicode object does not change,
9314 everything is fine. Otherwise we need to change the string kind
9315 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009316 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317 if (maxchar_new == 0)
9318 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9319 else if (maxchar_new <= 127)
9320 maxchar_new = 127;
9321 else if (maxchar_new <= 255)
9322 maxchar_new = 255;
9323 else if (maxchar_new <= 65535)
9324 maxchar_new = 65535;
9325 else
9326 maxchar_new = 1114111; /* 0x10ffff */
9327
9328 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009329 /* fixfct should return TRUE if it modified the buffer. If
9330 FALSE, return a reference to the original buffer instead
9331 (to save space, not time) */
9332 Py_INCREF(self);
9333 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009334 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009335 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 else if (maxchar_new == maxchar_old) {
9337 return u;
9338 }
9339 else {
9340 /* In case the maximum character changed, we need to
9341 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009342 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343 if (v == NULL) {
9344 Py_DECREF(u);
9345 return NULL;
9346 }
9347 if (maxchar_new > maxchar_old) {
9348 /* If the maxchar increased so that the kind changed, not all
9349 characters are representable anymore and we need to fix the
9350 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009351 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009352 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9354 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009355 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009356 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009357 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358
9359 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009360 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009361 return v;
9362 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009363}
9364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009365static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009366fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009367{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368 /* No need to call PyUnicode_READY(self) because this function is only
9369 called as a callback from fixup() which does it already. */
9370 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9371 const int kind = PyUnicode_KIND(self);
9372 void *data = PyUnicode_DATA(self);
9373 int touched = 0;
9374 Py_UCS4 maxchar = 0;
9375 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009376
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009377 for (i = 0; i < len; ++i) {
9378 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9379 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9380 if (up != ch) {
9381 if (up > maxchar)
9382 maxchar = up;
9383 PyUnicode_WRITE(kind, data, i, up);
9384 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009385 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009386 else if (ch > maxchar)
9387 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009388 }
9389
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009390 if (touched)
9391 return maxchar;
9392 else
9393 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009394}
9395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009397fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009399 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9400 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9401 const int kind = PyUnicode_KIND(self);
9402 void *data = PyUnicode_DATA(self);
9403 int touched = 0;
9404 Py_UCS4 maxchar = 0;
9405 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009406
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009407 for(i = 0; i < len; ++i) {
9408 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9409 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9410 if (lo != ch) {
9411 if (lo > maxchar)
9412 maxchar = lo;
9413 PyUnicode_WRITE(kind, data, i, lo);
9414 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009415 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009416 else if (ch > maxchar)
9417 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009418 }
9419
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009420 if (touched)
9421 return maxchar;
9422 else
9423 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009424}
9425
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009427fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009429 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9430 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9431 const int kind = PyUnicode_KIND(self);
9432 void *data = PyUnicode_DATA(self);
9433 int touched = 0;
9434 Py_UCS4 maxchar = 0;
9435 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 for(i = 0; i < len; ++i) {
9438 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9439 Py_UCS4 nu = 0;
9440
9441 if (Py_UNICODE_ISUPPER(ch))
9442 nu = Py_UNICODE_TOLOWER(ch);
9443 else if (Py_UNICODE_ISLOWER(ch))
9444 nu = Py_UNICODE_TOUPPER(ch);
9445
9446 if (nu != 0) {
9447 if (nu > maxchar)
9448 maxchar = nu;
9449 PyUnicode_WRITE(kind, data, i, nu);
9450 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 else if (ch > maxchar)
9453 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009454 }
9455
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009456 if (touched)
9457 return maxchar;
9458 else
9459 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460}
9461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009463fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9466 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9467 const int kind = PyUnicode_KIND(self);
9468 void *data = PyUnicode_DATA(self);
9469 int touched = 0;
9470 Py_UCS4 maxchar = 0;
9471 Py_ssize_t i = 0;
9472 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009473
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009474 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009475 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009476
9477 ch = PyUnicode_READ(kind, data, i);
9478 if (!Py_UNICODE_ISUPPER(ch)) {
9479 maxchar = Py_UNICODE_TOUPPER(ch);
9480 PyUnicode_WRITE(kind, data, i, maxchar);
9481 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009482 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009483 ++i;
9484 for(; i < len; ++i) {
9485 ch = PyUnicode_READ(kind, data, i);
9486 if (!Py_UNICODE_ISLOWER(ch)) {
9487 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9488 if (lo > maxchar)
9489 maxchar = lo;
9490 PyUnicode_WRITE(kind, data, i, lo);
9491 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493 else if (ch > maxchar)
9494 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009495 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009496
9497 if (touched)
9498 return maxchar;
9499 else
9500 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009501}
9502
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009504fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009505{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9507 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9508 const int kind = PyUnicode_KIND(self);
9509 void *data = PyUnicode_DATA(self);
9510 Py_UCS4 maxchar = 0;
9511 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009512 int previous_is_cased;
9513
9514 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009515 if (len == 1) {
9516 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9517 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9518 if (ti != ch) {
9519 PyUnicode_WRITE(kind, data, i, ti);
9520 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009521 }
9522 else
9523 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009525 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009526 for(; i < len; ++i) {
9527 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9528 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009529
Benjamin Peterson29060642009-01-31 22:14:21 +00009530 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009532 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009533 nu = Py_UNICODE_TOTITLE(ch);
9534
9535 if (nu > maxchar)
9536 maxchar = nu;
9537 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009538
Benjamin Peterson29060642009-01-31 22:14:21 +00009539 if (Py_UNICODE_ISLOWER(ch) ||
9540 Py_UNICODE_ISUPPER(ch) ||
9541 Py_UNICODE_ISTITLE(ch))
9542 previous_is_cased = 1;
9543 else
9544 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009545 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009547}
9548
Tim Peters8ce9f162004-08-27 01:49:32 +00009549PyObject *
9550PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009552 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009553 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009554 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009555 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009556 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9557 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009558 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009559 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009560 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009561 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009562 int use_memcpy;
9563 unsigned char *res_data = NULL, *sep_data = NULL;
9564 PyObject *last_obj;
9565 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009566
Tim Peters05eba1f2004-08-27 21:32:02 +00009567 fseq = PySequence_Fast(seq, "");
9568 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009569 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009570 }
9571
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009572 /* NOTE: the following code can't call back into Python code,
9573 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009574 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009575
Tim Peters05eba1f2004-08-27 21:32:02 +00009576 seqlen = PySequence_Fast_GET_SIZE(fseq);
9577 /* If empty sequence, return u"". */
9578 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009579 Py_DECREF(fseq);
9580 Py_INCREF(unicode_empty);
9581 res = unicode_empty;
9582 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009583 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009584
Tim Peters05eba1f2004-08-27 21:32:02 +00009585 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009586 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009587 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009588 if (seqlen == 1) {
9589 if (PyUnicode_CheckExact(items[0])) {
9590 res = items[0];
9591 Py_INCREF(res);
9592 Py_DECREF(fseq);
9593 return res;
9594 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009595 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009596 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009597 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009598 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009599 /* Set up sep and seplen */
9600 if (separator == NULL) {
9601 /* fall back to a blank space separator */
9602 sep = PyUnicode_FromOrdinal(' ');
9603 if (!sep)
9604 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009605 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009606 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009607 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009608 else {
9609 if (!PyUnicode_Check(separator)) {
9610 PyErr_Format(PyExc_TypeError,
9611 "separator: expected str instance,"
9612 " %.80s found",
9613 Py_TYPE(separator)->tp_name);
9614 goto onError;
9615 }
9616 if (PyUnicode_READY(separator))
9617 goto onError;
9618 sep = separator;
9619 seplen = PyUnicode_GET_LENGTH(separator);
9620 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9621 /* inc refcount to keep this code path symmetric with the
9622 above case of a blank separator */
9623 Py_INCREF(sep);
9624 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009625 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009626 }
9627
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009628 /* There are at least two things to join, or else we have a subclass
9629 * of str in the sequence.
9630 * Do a pre-pass to figure out the total amount of space we'll
9631 * need (sz), and see whether all argument are strings.
9632 */
9633 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009634#ifdef Py_DEBUG
9635 use_memcpy = 0;
9636#else
9637 use_memcpy = 1;
9638#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009639 for (i = 0; i < seqlen; i++) {
9640 const Py_ssize_t old_sz = sz;
9641 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009642 if (!PyUnicode_Check(item)) {
9643 PyErr_Format(PyExc_TypeError,
9644 "sequence item %zd: expected str instance,"
9645 " %.80s found",
9646 i, Py_TYPE(item)->tp_name);
9647 goto onError;
9648 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009649 if (PyUnicode_READY(item) == -1)
9650 goto onError;
9651 sz += PyUnicode_GET_LENGTH(item);
9652 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009653 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009654 if (i != 0)
9655 sz += seplen;
9656 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9657 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009658 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009659 goto onError;
9660 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009661 if (use_memcpy && last_obj != NULL) {
9662 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9663 use_memcpy = 0;
9664 }
9665 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009666 }
Tim Petersced69f82003-09-16 20:30:58 +00009667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009669 if (res == NULL)
9670 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009671
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009672 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009673#ifdef Py_DEBUG
9674 use_memcpy = 0;
9675#else
9676 if (use_memcpy) {
9677 res_data = PyUnicode_1BYTE_DATA(res);
9678 kind = PyUnicode_KIND(res);
9679 if (seplen != 0)
9680 sep_data = PyUnicode_1BYTE_DATA(sep);
9681 }
9682#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009683 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009684 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009685 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009686 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009687 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009688 if (use_memcpy) {
9689 Py_MEMCPY(res_data,
9690 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009691 kind * seplen);
9692 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009693 }
9694 else {
9695 copy_characters(res, res_offset, sep, 0, seplen);
9696 res_offset += seplen;
9697 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009698 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009699 itemlen = PyUnicode_GET_LENGTH(item);
9700 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009701 if (use_memcpy) {
9702 Py_MEMCPY(res_data,
9703 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009704 kind * itemlen);
9705 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009706 }
9707 else {
9708 copy_characters(res, res_offset, item, 0, itemlen);
9709 res_offset += itemlen;
9710 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009711 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009712 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009713 if (use_memcpy)
9714 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009715 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009716 else
9717 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009718
Tim Peters05eba1f2004-08-27 21:32:02 +00009719 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009720 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009721 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009722 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009723
Benjamin Peterson29060642009-01-31 22:14:21 +00009724 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009725 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009726 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009727 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009728 return NULL;
9729}
9730
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009731#define FILL(kind, data, value, start, length) \
9732 do { \
9733 Py_ssize_t i_ = 0; \
9734 assert(kind != PyUnicode_WCHAR_KIND); \
9735 switch ((kind)) { \
9736 case PyUnicode_1BYTE_KIND: { \
9737 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9738 memset(to_, (unsigned char)value, length); \
9739 break; \
9740 } \
9741 case PyUnicode_2BYTE_KIND: { \
9742 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9743 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9744 break; \
9745 } \
9746 default: { \
9747 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9748 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9749 break; \
9750 } \
9751 } \
9752 } while (0)
9753
Victor Stinner9310abb2011-10-05 00:59:23 +02009754static PyObject *
9755pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009756 Py_ssize_t left,
9757 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009758 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009759{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009760 PyObject *u;
9761 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009762 int kind;
9763 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009764
9765 if (left < 0)
9766 left = 0;
9767 if (right < 0)
9768 right = 0;
9769
Tim Peters7a29bd52001-09-12 03:03:31 +00009770 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009771 Py_INCREF(self);
9772 return self;
9773 }
9774
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009775 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9776 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009777 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9778 return NULL;
9779 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009780 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9781 if (fill > maxchar)
9782 maxchar = fill;
9783 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009784 if (!u)
9785 return NULL;
9786
9787 kind = PyUnicode_KIND(u);
9788 data = PyUnicode_DATA(u);
9789 if (left)
9790 FILL(kind, data, fill, 0, left);
9791 if (right)
9792 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009793 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009794 assert(_PyUnicode_CheckConsistency(u, 1));
9795 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009796}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009797#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009798
Alexander Belopolsky40018472011-02-26 01:02:56 +00009799PyObject *
9800PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009801{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009802 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009803
9804 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009805 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009806 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009807
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009808 switch(PyUnicode_KIND(string)) {
9809 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009810 if (PyUnicode_IS_ASCII(string))
9811 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009812 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009813 PyUnicode_GET_LENGTH(string), keepends);
9814 else
9815 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009816 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009817 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009818 break;
9819 case PyUnicode_2BYTE_KIND:
9820 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009821 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009822 PyUnicode_GET_LENGTH(string), keepends);
9823 break;
9824 case PyUnicode_4BYTE_KIND:
9825 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009826 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 PyUnicode_GET_LENGTH(string), keepends);
9828 break;
9829 default:
9830 assert(0);
9831 list = 0;
9832 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009833 Py_DECREF(string);
9834 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009835}
9836
Alexander Belopolsky40018472011-02-26 01:02:56 +00009837static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009838split(PyObject *self,
9839 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009840 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009841{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009842 int kind1, kind2, kind;
9843 void *buf1, *buf2;
9844 Py_ssize_t len1, len2;
9845 PyObject* out;
9846
Guido van Rossumd57fd912000-03-10 22:53:23 +00009847 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009848 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009849
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 if (PyUnicode_READY(self) == -1)
9851 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009852
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009853 if (substring == NULL)
9854 switch(PyUnicode_KIND(self)) {
9855 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009856 if (PyUnicode_IS_ASCII(self))
9857 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009858 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009859 PyUnicode_GET_LENGTH(self), maxcount
9860 );
9861 else
9862 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009863 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009864 PyUnicode_GET_LENGTH(self), maxcount
9865 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009866 case PyUnicode_2BYTE_KIND:
9867 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009868 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 PyUnicode_GET_LENGTH(self), maxcount
9870 );
9871 case PyUnicode_4BYTE_KIND:
9872 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009873 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009874 PyUnicode_GET_LENGTH(self), maxcount
9875 );
9876 default:
9877 assert(0);
9878 return NULL;
9879 }
9880
9881 if (PyUnicode_READY(substring) == -1)
9882 return NULL;
9883
9884 kind1 = PyUnicode_KIND(self);
9885 kind2 = PyUnicode_KIND(substring);
9886 kind = kind1 > kind2 ? kind1 : kind2;
9887 buf1 = PyUnicode_DATA(self);
9888 buf2 = PyUnicode_DATA(substring);
9889 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009890 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009891 if (!buf1)
9892 return NULL;
9893 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009894 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 if (!buf2) {
9896 if (kind1 != kind) PyMem_Free(buf1);
9897 return NULL;
9898 }
9899 len1 = PyUnicode_GET_LENGTH(self);
9900 len2 = PyUnicode_GET_LENGTH(substring);
9901
9902 switch(kind) {
9903 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009904 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9905 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009906 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009907 else
9908 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009909 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009910 break;
9911 case PyUnicode_2BYTE_KIND:
9912 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009913 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009914 break;
9915 case PyUnicode_4BYTE_KIND:
9916 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009917 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009918 break;
9919 default:
9920 out = NULL;
9921 }
9922 if (kind1 != kind)
9923 PyMem_Free(buf1);
9924 if (kind2 != kind)
9925 PyMem_Free(buf2);
9926 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009927}
9928
Alexander Belopolsky40018472011-02-26 01:02:56 +00009929static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009930rsplit(PyObject *self,
9931 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009932 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009933{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009934 int kind1, kind2, kind;
9935 void *buf1, *buf2;
9936 Py_ssize_t len1, len2;
9937 PyObject* out;
9938
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009939 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009940 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009941
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 if (PyUnicode_READY(self) == -1)
9943 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009944
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009945 if (substring == NULL)
9946 switch(PyUnicode_KIND(self)) {
9947 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009948 if (PyUnicode_IS_ASCII(self))
9949 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009950 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009951 PyUnicode_GET_LENGTH(self), maxcount
9952 );
9953 else
9954 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009955 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009956 PyUnicode_GET_LENGTH(self), maxcount
9957 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009958 case PyUnicode_2BYTE_KIND:
9959 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 PyUnicode_GET_LENGTH(self), maxcount
9962 );
9963 case PyUnicode_4BYTE_KIND:
9964 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009965 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009966 PyUnicode_GET_LENGTH(self), maxcount
9967 );
9968 default:
9969 assert(0);
9970 return NULL;
9971 }
9972
9973 if (PyUnicode_READY(substring) == -1)
9974 return NULL;
9975
9976 kind1 = PyUnicode_KIND(self);
9977 kind2 = PyUnicode_KIND(substring);
9978 kind = kind1 > kind2 ? kind1 : kind2;
9979 buf1 = PyUnicode_DATA(self);
9980 buf2 = PyUnicode_DATA(substring);
9981 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009982 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983 if (!buf1)
9984 return NULL;
9985 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009986 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 if (!buf2) {
9988 if (kind1 != kind) PyMem_Free(buf1);
9989 return NULL;
9990 }
9991 len1 = PyUnicode_GET_LENGTH(self);
9992 len2 = PyUnicode_GET_LENGTH(substring);
9993
9994 switch(kind) {
9995 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009996 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9997 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009998 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009999 else
10000 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010001 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002 break;
10003 case PyUnicode_2BYTE_KIND:
10004 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010005 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010006 break;
10007 case PyUnicode_4BYTE_KIND:
10008 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010009 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010010 break;
10011 default:
10012 out = NULL;
10013 }
10014 if (kind1 != kind)
10015 PyMem_Free(buf1);
10016 if (kind2 != kind)
10017 PyMem_Free(buf2);
10018 return out;
10019}
10020
10021static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010022anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10023 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010024{
10025 switch(kind) {
10026 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010027 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10028 return asciilib_find(buf1, len1, buf2, len2, offset);
10029 else
10030 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010031 case PyUnicode_2BYTE_KIND:
10032 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10033 case PyUnicode_4BYTE_KIND:
10034 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10035 }
10036 assert(0);
10037 return -1;
10038}
10039
10040static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010041anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10042 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043{
10044 switch(kind) {
10045 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010046 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10047 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10048 else
10049 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010050 case PyUnicode_2BYTE_KIND:
10051 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10052 case PyUnicode_4BYTE_KIND:
10053 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10054 }
10055 assert(0);
10056 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010057}
10058
Alexander Belopolsky40018472011-02-26 01:02:56 +000010059static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060replace(PyObject *self, PyObject *str1,
10061 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010062{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 PyObject *u;
10064 char *sbuf = PyUnicode_DATA(self);
10065 char *buf1 = PyUnicode_DATA(str1);
10066 char *buf2 = PyUnicode_DATA(str2);
10067 int srelease = 0, release1 = 0, release2 = 0;
10068 int skind = PyUnicode_KIND(self);
10069 int kind1 = PyUnicode_KIND(str1);
10070 int kind2 = PyUnicode_KIND(str2);
10071 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10072 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10073 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010074 int mayshrink;
10075 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010076
10077 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010078 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010079 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010080 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010081
Victor Stinner59de0ee2011-10-07 10:01:28 +020010082 if (str1 == str2)
10083 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 if (skind < kind1)
10085 /* substring too wide to be present */
10086 goto nothing;
10087
Victor Stinner49a0a212011-10-12 23:46:10 +020010088 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10089 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10090 /* Replacing str1 with str2 may cause a maxchar reduction in the
10091 result string. */
10092 mayshrink = (maxchar_str2 < maxchar);
10093 maxchar = Py_MAX(maxchar, maxchar_str2);
10094
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010095 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010096 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010097 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010099 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010100 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010101 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010102 Py_UCS4 u1, u2;
10103 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010104 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010105 if (findchar(sbuf, PyUnicode_KIND(self),
10106 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010107 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010109 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010110 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010111 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010112 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010113 rkind = PyUnicode_KIND(u);
10114 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10115 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010116 if (--maxcount < 0)
10117 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010119 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010120 }
10121 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010122 int rkind = skind;
10123 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010125 if (kind1 < rkind) {
10126 /* widen substring */
10127 buf1 = _PyUnicode_AsKind(str1, rkind);
10128 if (!buf1) goto error;
10129 release1 = 1;
10130 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010131 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010132 if (i < 0)
10133 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010134 if (rkind > kind2) {
10135 /* widen replacement */
10136 buf2 = _PyUnicode_AsKind(str2, rkind);
10137 if (!buf2) goto error;
10138 release2 = 1;
10139 }
10140 else if (rkind < kind2) {
10141 /* widen self and buf1 */
10142 rkind = kind2;
10143 if (release1) PyMem_Free(buf1);
10144 sbuf = _PyUnicode_AsKind(self, rkind);
10145 if (!sbuf) goto error;
10146 srelease = 1;
10147 buf1 = _PyUnicode_AsKind(str1, rkind);
10148 if (!buf1) goto error;
10149 release1 = 1;
10150 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010151 u = PyUnicode_New(slen, maxchar);
10152 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010154 assert(PyUnicode_KIND(u) == rkind);
10155 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010156
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010157 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010158 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010159 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010160 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010161 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010162 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010163
10164 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010165 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010166 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010167 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010168 if (i == -1)
10169 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010170 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010171 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010172 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010173 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010174 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010175 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010176 }
10177 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010178 Py_ssize_t n, i, j, ires;
10179 Py_ssize_t product, new_size;
10180 int rkind = skind;
10181 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010184 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 buf1 = _PyUnicode_AsKind(str1, rkind);
10186 if (!buf1) goto error;
10187 release1 = 1;
10188 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010189 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010190 if (n == 0)
10191 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010193 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010194 buf2 = _PyUnicode_AsKind(str2, rkind);
10195 if (!buf2) goto error;
10196 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010197 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010198 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010199 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010200 rkind = kind2;
10201 sbuf = _PyUnicode_AsKind(self, rkind);
10202 if (!sbuf) goto error;
10203 srelease = 1;
10204 if (release1) PyMem_Free(buf1);
10205 buf1 = _PyUnicode_AsKind(str1, rkind);
10206 if (!buf1) goto error;
10207 release1 = 1;
10208 }
10209 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10210 PyUnicode_GET_LENGTH(str1))); */
10211 product = n * (len2-len1);
10212 if ((product / (len2-len1)) != n) {
10213 PyErr_SetString(PyExc_OverflowError,
10214 "replace string is too long");
10215 goto error;
10216 }
10217 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010218 if (new_size == 0) {
10219 Py_INCREF(unicode_empty);
10220 u = unicode_empty;
10221 goto done;
10222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010223 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10224 PyErr_SetString(PyExc_OverflowError,
10225 "replace string is too long");
10226 goto error;
10227 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010228 u = PyUnicode_New(new_size, maxchar);
10229 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010230 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010231 assert(PyUnicode_KIND(u) == rkind);
10232 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 ires = i = 0;
10234 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010235 while (n-- > 0) {
10236 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010237 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010238 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010239 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010240 if (j == -1)
10241 break;
10242 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010243 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010244 memcpy(res + rkind * ires,
10245 sbuf + rkind * i,
10246 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010247 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010248 }
10249 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010250 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010251 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010252 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010253 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010254 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010255 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010256 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010257 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010259 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010260 memcpy(res + rkind * ires,
10261 sbuf + rkind * i,
10262 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010263 }
10264 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010265 /* interleave */
10266 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010267 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010269 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010270 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010271 if (--n <= 0)
10272 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010273 memcpy(res + rkind * ires,
10274 sbuf + rkind * i,
10275 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010276 ires++;
10277 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010278 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010279 memcpy(res + rkind * ires,
10280 sbuf + rkind * i,
10281 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010282 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010283 }
10284
10285 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010286 unicode_adjust_maxchar(&u);
10287 if (u == NULL)
10288 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010289 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010290
10291 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010292 if (srelease)
10293 PyMem_FREE(sbuf);
10294 if (release1)
10295 PyMem_FREE(buf1);
10296 if (release2)
10297 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010298 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010300
Benjamin Peterson29060642009-01-31 22:14:21 +000010301 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010302 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010303 if (srelease)
10304 PyMem_FREE(sbuf);
10305 if (release1)
10306 PyMem_FREE(buf1);
10307 if (release2)
10308 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010309 if (PyUnicode_CheckExact(self)) {
10310 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010311 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010312 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010313 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010314 error:
10315 if (srelease && sbuf)
10316 PyMem_FREE(sbuf);
10317 if (release1 && buf1)
10318 PyMem_FREE(buf1);
10319 if (release2 && buf2)
10320 PyMem_FREE(buf2);
10321 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322}
10323
10324/* --- Unicode Object Methods --------------------------------------------- */
10325
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010326PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010327 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010328\n\
10329Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010330characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010331
10332static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010333unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010334{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010335 return fixup(self, fixtitle);
10336}
10337
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010338PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010339 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010340\n\
10341Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010342have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010343
10344static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010345unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010346{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010347 return fixup(self, fixcapitalize);
10348}
10349
10350#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010351PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010352 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010353\n\
10354Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010355normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010356
10357static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010358unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010359{
10360 PyObject *list;
10361 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010362 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363
Guido van Rossumd57fd912000-03-10 22:53:23 +000010364 /* Split into words */
10365 list = split(self, NULL, -1);
10366 if (!list)
10367 return NULL;
10368
10369 /* Capitalize each word */
10370 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010371 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010372 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373 if (item == NULL)
10374 goto onError;
10375 Py_DECREF(PyList_GET_ITEM(list, i));
10376 PyList_SET_ITEM(list, i, item);
10377 }
10378
10379 /* Join the words to form a new string */
10380 item = PyUnicode_Join(NULL, list);
10381
Benjamin Peterson29060642009-01-31 22:14:21 +000010382 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010383 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010384 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010385}
10386#endif
10387
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010388/* Argument converter. Coerces to a single unicode character */
10389
10390static int
10391convert_uc(PyObject *obj, void *addr)
10392{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010394 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010395
Benjamin Peterson14339b62009-01-31 16:36:08 +000010396 uniobj = PyUnicode_FromObject(obj);
10397 if (uniobj == NULL) {
10398 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010399 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010400 return 0;
10401 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010403 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010404 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010405 Py_DECREF(uniobj);
10406 return 0;
10407 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010408 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010409 Py_DECREF(uniobj);
10410 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010411}
10412
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010413PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010414 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010415\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010416Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010417done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418
10419static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010420unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010421{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010422 Py_ssize_t marg, left;
10423 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010424 Py_UCS4 fillchar = ' ';
10425
Victor Stinnere9a29352011-10-01 02:14:59 +020010426 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010427 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010428
Victor Stinnere9a29352011-10-01 02:14:59 +020010429 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010430 return NULL;
10431
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010432 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010433 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010434 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010435 }
10436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010438 left = marg / 2 + (marg & width & 1);
10439
Victor Stinner9310abb2011-10-05 00:59:23 +020010440 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010441}
10442
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010443/* This function assumes that str1 and str2 are readied by the caller. */
10444
Marc-André Lemburge5034372000-08-08 08:04:29 +000010445static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010446unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010447{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010448 int kind1, kind2;
10449 void *data1, *data2;
10450 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010451
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010452 kind1 = PyUnicode_KIND(str1);
10453 kind2 = PyUnicode_KIND(str2);
10454 data1 = PyUnicode_DATA(str1);
10455 data2 = PyUnicode_DATA(str2);
10456 len1 = PyUnicode_GET_LENGTH(str1);
10457 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 for (i = 0; i < len1 && i < len2; ++i) {
10460 Py_UCS4 c1, c2;
10461 c1 = PyUnicode_READ(kind1, data1, i);
10462 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010463
10464 if (c1 != c2)
10465 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010466 }
10467
10468 return (len1 < len2) ? -1 : (len1 != len2);
10469}
10470
Alexander Belopolsky40018472011-02-26 01:02:56 +000010471int
10472PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010473{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010474 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10475 if (PyUnicode_READY(left) == -1 ||
10476 PyUnicode_READY(right) == -1)
10477 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010478 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010479 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010480 PyErr_Format(PyExc_TypeError,
10481 "Can't compare %.100s and %.100s",
10482 left->ob_type->tp_name,
10483 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010484 return -1;
10485}
10486
Martin v. Löwis5b222132007-06-10 09:51:05 +000010487int
10488PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10489{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010490 Py_ssize_t i;
10491 int kind;
10492 void *data;
10493 Py_UCS4 chr;
10494
Victor Stinner910337b2011-10-03 03:20:16 +020010495 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010496 if (PyUnicode_READY(uni) == -1)
10497 return -1;
10498 kind = PyUnicode_KIND(uni);
10499 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010500 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010501 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10502 if (chr != str[i])
10503 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010504 /* This check keeps Python strings that end in '\0' from comparing equal
10505 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010507 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010508 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010509 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010510 return 0;
10511}
10512
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010513
Benjamin Peterson29060642009-01-31 22:14:21 +000010514#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010515 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010516
Alexander Belopolsky40018472011-02-26 01:02:56 +000010517PyObject *
10518PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010519{
10520 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010521
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010522 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10523 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010524 if (PyUnicode_READY(left) == -1 ||
10525 PyUnicode_READY(right) == -1)
10526 return NULL;
10527 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10528 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010529 if (op == Py_EQ) {
10530 Py_INCREF(Py_False);
10531 return Py_False;
10532 }
10533 if (op == Py_NE) {
10534 Py_INCREF(Py_True);
10535 return Py_True;
10536 }
10537 }
10538 if (left == right)
10539 result = 0;
10540 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010541 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010542
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010543 /* Convert the return value to a Boolean */
10544 switch (op) {
10545 case Py_EQ:
10546 v = TEST_COND(result == 0);
10547 break;
10548 case Py_NE:
10549 v = TEST_COND(result != 0);
10550 break;
10551 case Py_LE:
10552 v = TEST_COND(result <= 0);
10553 break;
10554 case Py_GE:
10555 v = TEST_COND(result >= 0);
10556 break;
10557 case Py_LT:
10558 v = TEST_COND(result == -1);
10559 break;
10560 case Py_GT:
10561 v = TEST_COND(result == 1);
10562 break;
10563 default:
10564 PyErr_BadArgument();
10565 return NULL;
10566 }
10567 Py_INCREF(v);
10568 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010569 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010570
Brian Curtindfc80e32011-08-10 20:28:54 -050010571 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010572}
10573
Alexander Belopolsky40018472011-02-26 01:02:56 +000010574int
10575PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010576{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010577 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010578 int kind1, kind2, kind;
10579 void *buf1, *buf2;
10580 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010581 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010582
10583 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010584 sub = PyUnicode_FromObject(element);
10585 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010586 PyErr_Format(PyExc_TypeError,
10587 "'in <string>' requires string as left operand, not %s",
10588 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010589 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010590 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010591 if (PyUnicode_READY(sub) == -1)
10592 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010593
Thomas Wouters477c8d52006-05-27 19:21:47 +000010594 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010595 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010596 Py_DECREF(sub);
10597 return -1;
10598 }
10599
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010600 kind1 = PyUnicode_KIND(str);
10601 kind2 = PyUnicode_KIND(sub);
10602 kind = kind1 > kind2 ? kind1 : kind2;
10603 buf1 = PyUnicode_DATA(str);
10604 buf2 = PyUnicode_DATA(sub);
10605 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010606 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010607 if (!buf1) {
10608 Py_DECREF(sub);
10609 return -1;
10610 }
10611 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010612 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010613 if (!buf2) {
10614 Py_DECREF(sub);
10615 if (kind1 != kind) PyMem_Free(buf1);
10616 return -1;
10617 }
10618 len1 = PyUnicode_GET_LENGTH(str);
10619 len2 = PyUnicode_GET_LENGTH(sub);
10620
10621 switch(kind) {
10622 case PyUnicode_1BYTE_KIND:
10623 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10624 break;
10625 case PyUnicode_2BYTE_KIND:
10626 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10627 break;
10628 case PyUnicode_4BYTE_KIND:
10629 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10630 break;
10631 default:
10632 result = -1;
10633 assert(0);
10634 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010635
10636 Py_DECREF(str);
10637 Py_DECREF(sub);
10638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010639 if (kind1 != kind)
10640 PyMem_Free(buf1);
10641 if (kind2 != kind)
10642 PyMem_Free(buf2);
10643
Guido van Rossum403d68b2000-03-13 15:55:09 +000010644 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010645}
10646
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647/* Concat to string or Unicode object giving a new Unicode object. */
10648
Alexander Belopolsky40018472011-02-26 01:02:56 +000010649PyObject *
10650PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010651{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010652 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010653 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010654
10655 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010656 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010658 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010659 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010660 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010661 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662
10663 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010664 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010665 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010668 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010669 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010670 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010671 }
10672
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010674 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10675 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010678 w = PyUnicode_New(
10679 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10680 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010682 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010683 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10684 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010685 Py_DECREF(u);
10686 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010687 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010689
Benjamin Peterson29060642009-01-31 22:14:21 +000010690 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691 Py_XDECREF(u);
10692 Py_XDECREF(v);
10693 return NULL;
10694}
10695
Victor Stinnerb0923652011-10-04 01:17:31 +020010696static void
10697unicode_append_inplace(PyObject **p_left, PyObject *right)
10698{
10699 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010700
10701 assert(PyUnicode_IS_READY(*p_left));
10702 assert(PyUnicode_IS_READY(right));
10703
10704 left_len = PyUnicode_GET_LENGTH(*p_left);
10705 right_len = PyUnicode_GET_LENGTH(right);
10706 if (left_len > PY_SSIZE_T_MAX - right_len) {
10707 PyErr_SetString(PyExc_OverflowError,
10708 "strings are too large to concat");
10709 goto error;
10710 }
10711 new_len = left_len + right_len;
10712
10713 /* Now we own the last reference to 'left', so we can resize it
10714 * in-place.
10715 */
10716 if (unicode_resize(p_left, new_len) != 0) {
10717 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10718 * deallocated so it cannot be put back into
10719 * 'variable'. The MemoryError is raised when there
10720 * is no value in 'variable', which might (very
10721 * remotely) be a cause of incompatibilities.
10722 */
10723 goto error;
10724 }
10725 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010726 copy_characters(*p_left, left_len, right, 0, right_len);
10727 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010728 return;
10729
10730error:
10731 Py_DECREF(*p_left);
10732 *p_left = NULL;
10733}
10734
Walter Dörwald1ab83302007-05-18 17:15:44 +000010735void
Victor Stinner23e56682011-10-03 03:54:37 +020010736PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010737{
Victor Stinner23e56682011-10-03 03:54:37 +020010738 PyObject *left, *res;
10739
10740 if (p_left == NULL) {
10741 if (!PyErr_Occurred())
10742 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010743 return;
10744 }
Victor Stinner23e56682011-10-03 03:54:37 +020010745 left = *p_left;
10746 if (right == NULL || !PyUnicode_Check(left)) {
10747 if (!PyErr_Occurred())
10748 PyErr_BadInternalCall();
10749 goto error;
10750 }
10751
Victor Stinnere1335c72011-10-04 20:53:03 +020010752 if (PyUnicode_READY(left))
10753 goto error;
10754 if (PyUnicode_READY(right))
10755 goto error;
10756
Victor Stinner23e56682011-10-03 03:54:37 +020010757 if (PyUnicode_CheckExact(left) && left != unicode_empty
10758 && PyUnicode_CheckExact(right) && right != unicode_empty
10759 && unicode_resizable(left)
10760 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10761 || _PyUnicode_WSTR(left) != NULL))
10762 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010763 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10764 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010765 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010766 not so different than duplicating the string. */
10767 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010768 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010769 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010770 if (p_left != NULL)
10771 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010772 return;
10773 }
10774 }
10775
10776 res = PyUnicode_Concat(left, right);
10777 if (res == NULL)
10778 goto error;
10779 Py_DECREF(left);
10780 *p_left = res;
10781 return;
10782
10783error:
10784 Py_DECREF(*p_left);
10785 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010786}
10787
10788void
10789PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10790{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010791 PyUnicode_Append(pleft, right);
10792 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010793}
10794
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010795PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010796 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010798Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010799string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010800interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010801
10802static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010803unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010804{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010805 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010806 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010807 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010808 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 int kind1, kind2, kind;
10810 void *buf1, *buf2;
10811 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010812
Jesus Ceaac451502011-04-20 17:09:23 +020010813 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10814 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010815 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010817 kind1 = PyUnicode_KIND(self);
10818 kind2 = PyUnicode_KIND(substring);
10819 kind = kind1 > kind2 ? kind1 : kind2;
10820 buf1 = PyUnicode_DATA(self);
10821 buf2 = PyUnicode_DATA(substring);
10822 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010823 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010824 if (!buf1) {
10825 Py_DECREF(substring);
10826 return NULL;
10827 }
10828 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010829 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010830 if (!buf2) {
10831 Py_DECREF(substring);
10832 if (kind1 != kind) PyMem_Free(buf1);
10833 return NULL;
10834 }
10835 len1 = PyUnicode_GET_LENGTH(self);
10836 len2 = PyUnicode_GET_LENGTH(substring);
10837
10838 ADJUST_INDICES(start, end, len1);
10839 switch(kind) {
10840 case PyUnicode_1BYTE_KIND:
10841 iresult = ucs1lib_count(
10842 ((Py_UCS1*)buf1) + start, end - start,
10843 buf2, len2, PY_SSIZE_T_MAX
10844 );
10845 break;
10846 case PyUnicode_2BYTE_KIND:
10847 iresult = ucs2lib_count(
10848 ((Py_UCS2*)buf1) + start, end - start,
10849 buf2, len2, PY_SSIZE_T_MAX
10850 );
10851 break;
10852 case PyUnicode_4BYTE_KIND:
10853 iresult = ucs4lib_count(
10854 ((Py_UCS4*)buf1) + start, end - start,
10855 buf2, len2, PY_SSIZE_T_MAX
10856 );
10857 break;
10858 default:
10859 assert(0); iresult = 0;
10860 }
10861
10862 result = PyLong_FromSsize_t(iresult);
10863
10864 if (kind1 != kind)
10865 PyMem_Free(buf1);
10866 if (kind2 != kind)
10867 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010868
10869 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010870
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871 return result;
10872}
10873
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010874PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010875 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010876\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010877Encode S using the codec registered for encoding. Default encoding\n\
10878is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010879handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010880a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10881'xmlcharrefreplace' as well as any other name registered with\n\
10882codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010883
10884static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010885unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010887 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010888 char *encoding = NULL;
10889 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010890
Benjamin Peterson308d6372009-09-18 21:42:35 +000010891 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10892 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010894 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010895}
10896
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010897PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010898 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010899\n\
10900Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010901If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010902
10903static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010904unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010905{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010906 Py_ssize_t i, j, line_pos, src_len, incr;
10907 Py_UCS4 ch;
10908 PyObject *u;
10909 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010910 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010911 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010912 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913
10914 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010915 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
Antoine Pitrou22425222011-10-04 19:10:51 +020010917 if (PyUnicode_READY(self) == -1)
10918 return NULL;
10919
Thomas Wouters7e474022000-07-16 12:04:32 +000010920 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 src_len = PyUnicode_GET_LENGTH(self);
10922 i = j = line_pos = 0;
10923 kind = PyUnicode_KIND(self);
10924 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010925 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010926 for (; i < src_len; i++) {
10927 ch = PyUnicode_READ(kind, src_data, i);
10928 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010929 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010930 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010932 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010933 goto overflow;
10934 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010935 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010936 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010937 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010938 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010939 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010940 goto overflow;
10941 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010943 if (ch == '\n' || ch == '\r')
10944 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010945 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010946 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010947 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010948 Py_INCREF(self);
10949 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010950 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010951
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010953 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010954 if (!u)
10955 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010956 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010957
Antoine Pitroue71d5742011-10-04 15:55:09 +020010958 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959
Antoine Pitroue71d5742011-10-04 15:55:09 +020010960 for (; i < src_len; i++) {
10961 ch = PyUnicode_READ(kind, src_data, i);
10962 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010963 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010964 incr = tabsize - (line_pos % tabsize);
10965 line_pos += incr;
10966 while (incr--) {
10967 PyUnicode_WRITE(kind, dest_data, j, ' ');
10968 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010969 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010970 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010971 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010972 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010973 line_pos++;
10974 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010975 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010976 if (ch == '\n' || ch == '\r')
10977 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010979 }
10980 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010981#ifndef DONT_MAKE_RESULT_READY
10982 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010983 Py_DECREF(u);
10984 return NULL;
10985 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010986#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010987 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010010988 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010989
Antoine Pitroue71d5742011-10-04 15:55:09 +020010990 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010991 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10992 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010993}
10994
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010995PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010996 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997\n\
10998Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010999such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000arguments start and end are interpreted as in slice notation.\n\
11001\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011002Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003
11004static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011005unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011006{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011007 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011008 Py_ssize_t start;
11009 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011010 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011011
Jesus Ceaac451502011-04-20 17:09:23 +020011012 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11013 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011015
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011016 if (PyUnicode_READY(self) == -1)
11017 return NULL;
11018 if (PyUnicode_READY(substring) == -1)
11019 return NULL;
11020
Victor Stinner7931d9a2011-11-04 00:22:48 +010011021 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011022
11023 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011024
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011025 if (result == -2)
11026 return NULL;
11027
Christian Heimes217cfd12007-12-02 14:31:20 +000011028 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029}
11030
11031static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011032unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011033{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011034 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11035 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011036 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011037 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011038}
11039
Guido van Rossumc2504932007-09-18 19:42:40 +000011040/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011041 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011042static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011043unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011044{
Guido van Rossumc2504932007-09-18 19:42:40 +000011045 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011046 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011047
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011048 if (_PyUnicode_HASH(self) != -1)
11049 return _PyUnicode_HASH(self);
11050 if (PyUnicode_READY(self) == -1)
11051 return -1;
11052 len = PyUnicode_GET_LENGTH(self);
11053
11054 /* The hash function as a macro, gets expanded three times below. */
11055#define HASH(P) \
11056 x = (Py_uhash_t)*P << 7; \
11057 while (--len >= 0) \
11058 x = (1000003*x) ^ (Py_uhash_t)*P++;
11059
11060 switch (PyUnicode_KIND(self)) {
11061 case PyUnicode_1BYTE_KIND: {
11062 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11063 HASH(c);
11064 break;
11065 }
11066 case PyUnicode_2BYTE_KIND: {
11067 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11068 HASH(s);
11069 break;
11070 }
11071 default: {
11072 Py_UCS4 *l;
11073 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11074 "Impossible switch case in unicode_hash");
11075 l = PyUnicode_4BYTE_DATA(self);
11076 HASH(l);
11077 break;
11078 }
11079 }
11080 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11081
Guido van Rossumc2504932007-09-18 19:42:40 +000011082 if (x == -1)
11083 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011084 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011085 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011087#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011089PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011090 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011091\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011092Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093
11094static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011095unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011097 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011098 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011099 Py_ssize_t start;
11100 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101
Jesus Ceaac451502011-04-20 17:09:23 +020011102 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11103 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011104 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011106 if (PyUnicode_READY(self) == -1)
11107 return NULL;
11108 if (PyUnicode_READY(substring) == -1)
11109 return NULL;
11110
Victor Stinner7931d9a2011-11-04 00:22:48 +010011111 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011112
11113 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 if (result == -2)
11116 return NULL;
11117
Guido van Rossumd57fd912000-03-10 22:53:23 +000011118 if (result < 0) {
11119 PyErr_SetString(PyExc_ValueError, "substring not found");
11120 return NULL;
11121 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011122
Christian Heimes217cfd12007-12-02 14:31:20 +000011123 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124}
11125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011126PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011127 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011129Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131
11132static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011133unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 Py_ssize_t i, length;
11136 int kind;
11137 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138 int cased;
11139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 if (PyUnicode_READY(self) == -1)
11141 return NULL;
11142 length = PyUnicode_GET_LENGTH(self);
11143 kind = PyUnicode_KIND(self);
11144 data = PyUnicode_DATA(self);
11145
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (length == 1)
11148 return PyBool_FromLong(
11149 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011151 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011153 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011154
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 for (i = 0; i < length; i++) {
11157 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011158
Benjamin Peterson29060642009-01-31 22:14:21 +000011159 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11160 return PyBool_FromLong(0);
11161 else if (!cased && Py_UNICODE_ISLOWER(ch))
11162 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011164 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165}
11166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011167PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011168 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011170Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011171at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172
11173static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011174unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011176 Py_ssize_t i, length;
11177 int kind;
11178 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179 int cased;
11180
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011181 if (PyUnicode_READY(self) == -1)
11182 return NULL;
11183 length = PyUnicode_GET_LENGTH(self);
11184 kind = PyUnicode_KIND(self);
11185 data = PyUnicode_DATA(self);
11186
Guido van Rossumd57fd912000-03-10 22:53:23 +000011187 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011188 if (length == 1)
11189 return PyBool_FromLong(
11190 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011192 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011193 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011194 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011195
Guido van Rossumd57fd912000-03-10 22:53:23 +000011196 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 for (i = 0; i < length; i++) {
11198 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011199
Benjamin Peterson29060642009-01-31 22:14:21 +000011200 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11201 return PyBool_FromLong(0);
11202 else if (!cased && Py_UNICODE_ISUPPER(ch))
11203 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011204 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011205 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206}
11207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011208PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011209 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011210\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011211Return True if S is a titlecased string and there is at least one\n\
11212character in S, i.e. upper- and titlecase characters may only\n\
11213follow uncased characters and lowercase characters only cased ones.\n\
11214Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215
11216static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011217unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011218{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011219 Py_ssize_t i, length;
11220 int kind;
11221 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011222 int cased, previous_is_cased;
11223
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011224 if (PyUnicode_READY(self) == -1)
11225 return NULL;
11226 length = PyUnicode_GET_LENGTH(self);
11227 kind = PyUnicode_KIND(self);
11228 data = PyUnicode_DATA(self);
11229
Guido van Rossumd57fd912000-03-10 22:53:23 +000011230 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011231 if (length == 1) {
11232 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11233 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11234 (Py_UNICODE_ISUPPER(ch) != 0));
11235 }
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;
11242 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011243 for (i = 0; i < length; i++) {
11244 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011245
Benjamin Peterson29060642009-01-31 22:14:21 +000011246 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11247 if (previous_is_cased)
11248 return PyBool_FromLong(0);
11249 previous_is_cased = 1;
11250 cased = 1;
11251 }
11252 else if (Py_UNICODE_ISLOWER(ch)) {
11253 if (!previous_is_cased)
11254 return PyBool_FromLong(0);
11255 previous_is_cased = 1;
11256 cased = 1;
11257 }
11258 else
11259 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011260 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011261 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011262}
11263
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011264PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011265 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011266\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011267Return True if all characters in S are whitespace\n\
11268and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011269
11270static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011271unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011273 Py_ssize_t i, length;
11274 int kind;
11275 void *data;
11276
11277 if (PyUnicode_READY(self) == -1)
11278 return NULL;
11279 length = PyUnicode_GET_LENGTH(self);
11280 kind = PyUnicode_KIND(self);
11281 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 1)
11285 return PyBool_FromLong(
11286 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011287
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011288 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011289 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011290 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011292 for (i = 0; i < length; i++) {
11293 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011294 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011295 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011296 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011297 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011298}
11299
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011300PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011301 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011302\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011303Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011304and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011305
11306static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011307unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011308{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011309 Py_ssize_t i, length;
11310 int kind;
11311 void *data;
11312
11313 if (PyUnicode_READY(self) == -1)
11314 return NULL;
11315 length = PyUnicode_GET_LENGTH(self);
11316 kind = PyUnicode_KIND(self);
11317 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011319 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011320 if (length == 1)
11321 return PyBool_FromLong(
11322 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011323
11324 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011325 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011326 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011327
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011328 for (i = 0; i < length; i++) {
11329 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011330 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011331 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011332 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011333}
11334
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011335PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011336 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011337\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011338Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011339and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011340
11341static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011342unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011343{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011344 int kind;
11345 void *data;
11346 Py_ssize_t len, i;
11347
11348 if (PyUnicode_READY(self) == -1)
11349 return NULL;
11350
11351 kind = PyUnicode_KIND(self);
11352 data = PyUnicode_DATA(self);
11353 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011354
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011355 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011356 if (len == 1) {
11357 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11358 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11359 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011360
11361 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011362 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011363 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011365 for (i = 0; i < len; i++) {
11366 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011367 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011368 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011369 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011370 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011371}
11372
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011373PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011374 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011376Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011377False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011378
11379static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011380unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011382 Py_ssize_t i, length;
11383 int kind;
11384 void *data;
11385
11386 if (PyUnicode_READY(self) == -1)
11387 return NULL;
11388 length = PyUnicode_GET_LENGTH(self);
11389 kind = PyUnicode_KIND(self);
11390 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391
Guido van Rossumd57fd912000-03-10 22:53:23 +000011392 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 if (length == 1)
11394 return PyBool_FromLong(
11395 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011396
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011397 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011398 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011399 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011400
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011401 for (i = 0; i < length; i++) {
11402 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011403 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011404 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011405 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406}
11407
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011408PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011409 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011410\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011411Return True if all characters in S are digits\n\
11412and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011413
11414static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011415unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011417 Py_ssize_t i, length;
11418 int kind;
11419 void *data;
11420
11421 if (PyUnicode_READY(self) == -1)
11422 return NULL;
11423 length = PyUnicode_GET_LENGTH(self);
11424 kind = PyUnicode_KIND(self);
11425 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 if (length == 1) {
11429 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11430 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11431 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011432
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011433 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011434 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011435 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011437 for (i = 0; i < length; i++) {
11438 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011439 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011440 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011441 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442}
11443
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011444PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011446\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011447Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011448False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011449
11450static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011451unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011453 Py_ssize_t i, length;
11454 int kind;
11455 void *data;
11456
11457 if (PyUnicode_READY(self) == -1)
11458 return NULL;
11459 length = PyUnicode_GET_LENGTH(self);
11460 kind = PyUnicode_KIND(self);
11461 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462
Guido van Rossumd57fd912000-03-10 22:53:23 +000011463 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011464 if (length == 1)
11465 return PyBool_FromLong(
11466 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011467
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011468 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011469 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011470 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 for (i = 0; i < length; i++) {
11473 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011475 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011476 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477}
11478
Martin v. Löwis47383402007-08-15 07:32:56 +000011479int
11480PyUnicode_IsIdentifier(PyObject *self)
11481{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 int kind;
11483 void *data;
11484 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011485 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011486
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011487 if (PyUnicode_READY(self) == -1) {
11488 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011489 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011490 }
11491
11492 /* Special case for empty strings */
11493 if (PyUnicode_GET_LENGTH(self) == 0)
11494 return 0;
11495 kind = PyUnicode_KIND(self);
11496 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011497
11498 /* PEP 3131 says that the first character must be in
11499 XID_Start and subsequent characters in XID_Continue,
11500 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011501 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011502 letters, digits, underscore). However, given the current
11503 definition of XID_Start and XID_Continue, it is sufficient
11504 to check just for these, except that _ must be allowed
11505 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011506 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011507 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011508 return 0;
11509
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011510 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011512 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011513 return 1;
11514}
11515
11516PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011517 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011518\n\
11519Return True if S is a valid identifier according\n\
11520to the language definition.");
11521
11522static PyObject*
11523unicode_isidentifier(PyObject *self)
11524{
11525 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11526}
11527
Georg Brandl559e5d72008-06-11 18:37:52 +000011528PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011529 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011530\n\
11531Return True if all characters in S are considered\n\
11532printable in repr() or S is empty, False otherwise.");
11533
11534static PyObject*
11535unicode_isprintable(PyObject *self)
11536{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 Py_ssize_t i, length;
11538 int kind;
11539 void *data;
11540
11541 if (PyUnicode_READY(self) == -1)
11542 return NULL;
11543 length = PyUnicode_GET_LENGTH(self);
11544 kind = PyUnicode_KIND(self);
11545 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011546
11547 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011548 if (length == 1)
11549 return PyBool_FromLong(
11550 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011552 for (i = 0; i < length; i++) {
11553 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011554 Py_RETURN_FALSE;
11555 }
11556 }
11557 Py_RETURN_TRUE;
11558}
11559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011560PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011561 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011562\n\
11563Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011564iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011565
11566static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011567unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011568{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011569 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570}
11571
Martin v. Löwis18e16552006-02-15 17:27:45 +000011572static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011573unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011574{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 if (PyUnicode_READY(self) == -1)
11576 return -1;
11577 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578}
11579
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011580PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011581 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011582\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011583Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011584done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011585
11586static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011587unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011589 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011590 Py_UCS4 fillchar = ' ';
11591
11592 if (PyUnicode_READY(self) == -1)
11593 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011594
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011595 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011596 return NULL;
11597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011598 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011600 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011601 }
11602
Victor Stinner7931d9a2011-11-04 00:22:48 +010011603 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011604}
11605
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011606PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011607 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011608\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011609Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011610
11611static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011612unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011613{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614 return fixup(self, fixlower);
11615}
11616
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011617#define LEFTSTRIP 0
11618#define RIGHTSTRIP 1
11619#define BOTHSTRIP 2
11620
11621/* Arrays indexed by above */
11622static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11623
11624#define STRIPNAME(i) (stripformat[i]+3)
11625
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011626/* externally visible for str.strip(unicode) */
11627PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011628_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011629{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630 void *data;
11631 int kind;
11632 Py_ssize_t i, j, len;
11633 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011635 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11636 return NULL;
11637
11638 kind = PyUnicode_KIND(self);
11639 data = PyUnicode_DATA(self);
11640 len = PyUnicode_GET_LENGTH(self);
11641 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11642 PyUnicode_DATA(sepobj),
11643 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011644
Benjamin Peterson14339b62009-01-31 16:36:08 +000011645 i = 0;
11646 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011647 while (i < len &&
11648 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011649 i++;
11650 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011651 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011652
Benjamin Peterson14339b62009-01-31 16:36:08 +000011653 j = len;
11654 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011655 do {
11656 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 } while (j >= i &&
11658 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011660 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011661
Victor Stinner7931d9a2011-11-04 00:22:48 +010011662 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663}
11664
11665PyObject*
11666PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11667{
11668 unsigned char *data;
11669 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011670 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011671
Victor Stinnerde636f32011-10-01 03:55:54 +020011672 if (PyUnicode_READY(self) == -1)
11673 return NULL;
11674
11675 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11676
Victor Stinner12bab6d2011-10-01 01:53:49 +020011677 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011678 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011679 if (PyUnicode_CheckExact(self)) {
11680 Py_INCREF(self);
11681 return self;
11682 }
11683 else
11684 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 }
11686
Victor Stinner12bab6d2011-10-01 01:53:49 +020011687 length = end - start;
11688 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011689 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011690
Victor Stinnerde636f32011-10-01 03:55:54 +020011691 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011692 PyErr_SetString(PyExc_IndexError, "string index out of range");
11693 return NULL;
11694 }
11695
Victor Stinnerb9275c12011-10-05 14:01:42 +020011696 if (PyUnicode_IS_ASCII(self)) {
11697 kind = PyUnicode_KIND(self);
11698 data = PyUnicode_1BYTE_DATA(self);
11699 return unicode_fromascii(data + start, length);
11700 }
11701 else {
11702 kind = PyUnicode_KIND(self);
11703 data = PyUnicode_1BYTE_DATA(self);
11704 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011705 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011706 length);
11707 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011708}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011709
11710static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011711do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011712{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011713 int kind;
11714 void *data;
11715 Py_ssize_t len, i, j;
11716
11717 if (PyUnicode_READY(self) == -1)
11718 return NULL;
11719
11720 kind = PyUnicode_KIND(self);
11721 data = PyUnicode_DATA(self);
11722 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011723
Benjamin Peterson14339b62009-01-31 16:36:08 +000011724 i = 0;
11725 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011726 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011727 i++;
11728 }
11729 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731 j = len;
11732 if (striptype != LEFTSTRIP) {
11733 do {
11734 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011735 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011736 j++;
11737 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011738
Victor Stinner7931d9a2011-11-04 00:22:48 +010011739 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011740}
11741
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011742
11743static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011744do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011745{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011746 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011747
Benjamin Peterson14339b62009-01-31 16:36:08 +000011748 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11749 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750
Benjamin Peterson14339b62009-01-31 16:36:08 +000011751 if (sep != NULL && sep != Py_None) {
11752 if (PyUnicode_Check(sep))
11753 return _PyUnicode_XStrip(self, striptype, sep);
11754 else {
11755 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011756 "%s arg must be None or str",
11757 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011758 return NULL;
11759 }
11760 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011761
Benjamin Peterson14339b62009-01-31 16:36:08 +000011762 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011763}
11764
11765
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011766PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011767 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011768\n\
11769Return a copy of the string S with leading and trailing\n\
11770whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011771If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011772
11773static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011774unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011775{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011776 if (PyTuple_GET_SIZE(args) == 0)
11777 return do_strip(self, BOTHSTRIP); /* Common case */
11778 else
11779 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011780}
11781
11782
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011783PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011784 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011785\n\
11786Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011787If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011788
11789static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011790unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011791{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011792 if (PyTuple_GET_SIZE(args) == 0)
11793 return do_strip(self, LEFTSTRIP); /* Common case */
11794 else
11795 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011796}
11797
11798
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011799PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011800 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011801\n\
11802Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011803If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011804
11805static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011806unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011807{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011808 if (PyTuple_GET_SIZE(args) == 0)
11809 return do_strip(self, RIGHTSTRIP); /* Common case */
11810 else
11811 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011812}
11813
11814
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011816unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011817{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011818 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011819 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011820
Georg Brandl222de0f2009-04-12 12:01:50 +000011821 if (len < 1) {
11822 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011823 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011824 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825
Tim Peters7a29bd52001-09-12 03:03:31 +000011826 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827 /* no repeat, return original string */
11828 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011829 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830 }
Tim Peters8f422462000-09-09 06:13:41 +000011831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 if (PyUnicode_READY(str) == -1)
11833 return NULL;
11834
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011835 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011836 PyErr_SetString(PyExc_OverflowError,
11837 "repeated string is too long");
11838 return NULL;
11839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011840 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011841
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011842 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011843 if (!u)
11844 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011845 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011846
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 if (PyUnicode_GET_LENGTH(str) == 1) {
11848 const int kind = PyUnicode_KIND(str);
11849 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11850 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011851 if (kind == PyUnicode_1BYTE_KIND)
11852 memset(to, (unsigned char)fill_char, len);
11853 else {
11854 for (n = 0; n < len; ++n)
11855 PyUnicode_WRITE(kind, to, n, fill_char);
11856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 }
11858 else {
11859 /* number of characters copied this far */
11860 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011861 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011862 char *to = (char *) PyUnicode_DATA(u);
11863 Py_MEMCPY(to, PyUnicode_DATA(str),
11864 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011865 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011866 n = (done <= nchars-done) ? done : nchars-done;
11867 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011868 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011869 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011870 }
11871
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011872 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011873 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011874}
11875
Alexander Belopolsky40018472011-02-26 01:02:56 +000011876PyObject *
11877PyUnicode_Replace(PyObject *obj,
11878 PyObject *subobj,
11879 PyObject *replobj,
11880 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011881{
11882 PyObject *self;
11883 PyObject *str1;
11884 PyObject *str2;
11885 PyObject *result;
11886
11887 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011888 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011889 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011890 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011891 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011892 Py_DECREF(self);
11893 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894 }
11895 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011896 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011897 Py_DECREF(self);
11898 Py_DECREF(str1);
11899 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902 Py_DECREF(self);
11903 Py_DECREF(str1);
11904 Py_DECREF(str2);
11905 return result;
11906}
11907
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011908PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011909 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910\n\
11911Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011912old replaced by new. If the optional argument count is\n\
11913given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011914
11915static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011916unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011917{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 PyObject *str1;
11919 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011920 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011921 PyObject *result;
11922
Martin v. Löwis18e16552006-02-15 17:27:45 +000011923 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011925 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011926 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011927 str1 = PyUnicode_FromObject(str1);
11928 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11929 return NULL;
11930 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011931 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011932 Py_DECREF(str1);
11933 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011934 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011935
11936 result = replace(self, str1, str2, maxcount);
11937
11938 Py_DECREF(str1);
11939 Py_DECREF(str2);
11940 return result;
11941}
11942
Alexander Belopolsky40018472011-02-26 01:02:56 +000011943static PyObject *
11944unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011946 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011947 Py_ssize_t isize;
11948 Py_ssize_t osize, squote, dquote, i, o;
11949 Py_UCS4 max, quote;
11950 int ikind, okind;
11951 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011952
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011953 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011954 return NULL;
11955
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011956 isize = PyUnicode_GET_LENGTH(unicode);
11957 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011958
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011959 /* Compute length of output, quote characters, and
11960 maximum character */
11961 osize = 2; /* quotes */
11962 max = 127;
11963 squote = dquote = 0;
11964 ikind = PyUnicode_KIND(unicode);
11965 for (i = 0; i < isize; i++) {
11966 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11967 switch (ch) {
11968 case '\'': squote++; osize++; break;
11969 case '"': dquote++; osize++; break;
11970 case '\\': case '\t': case '\r': case '\n':
11971 osize += 2; break;
11972 default:
11973 /* Fast-path ASCII */
11974 if (ch < ' ' || ch == 0x7f)
11975 osize += 4; /* \xHH */
11976 else if (ch < 0x7f)
11977 osize++;
11978 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11979 osize++;
11980 max = ch > max ? ch : max;
11981 }
11982 else if (ch < 0x100)
11983 osize += 4; /* \xHH */
11984 else if (ch < 0x10000)
11985 osize += 6; /* \uHHHH */
11986 else
11987 osize += 10; /* \uHHHHHHHH */
11988 }
11989 }
11990
11991 quote = '\'';
11992 if (squote) {
11993 if (dquote)
11994 /* Both squote and dquote present. Use squote,
11995 and escape them */
11996 osize += squote;
11997 else
11998 quote = '"';
11999 }
12000
12001 repr = PyUnicode_New(osize, max);
12002 if (repr == NULL)
12003 return NULL;
12004 okind = PyUnicode_KIND(repr);
12005 odata = PyUnicode_DATA(repr);
12006
12007 PyUnicode_WRITE(okind, odata, 0, quote);
12008 PyUnicode_WRITE(okind, odata, osize-1, quote);
12009
12010 for (i = 0, o = 1; i < isize; i++) {
12011 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012012
12013 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012014 if ((ch == quote) || (ch == '\\')) {
12015 PyUnicode_WRITE(okind, odata, o++, '\\');
12016 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012017 continue;
12018 }
12019
Benjamin Peterson29060642009-01-31 22:14:21 +000012020 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012021 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012022 PyUnicode_WRITE(okind, odata, o++, '\\');
12023 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012024 }
12025 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012026 PyUnicode_WRITE(okind, odata, o++, '\\');
12027 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012028 }
12029 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012030 PyUnicode_WRITE(okind, odata, o++, '\\');
12031 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012032 }
12033
12034 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012035 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 PyUnicode_WRITE(okind, odata, o++, '\\');
12037 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12039 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012040 }
12041
Georg Brandl559e5d72008-06-11 18:37:52 +000012042 /* Copy ASCII characters as-is */
12043 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012045 }
12046
Benjamin Peterson29060642009-01-31 22:14:21 +000012047 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012048 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012049 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012050 (categories Z* and C* except ASCII space)
12051 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012052 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012053 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 if (ch <= 0xff) {
12055 PyUnicode_WRITE(okind, odata, o++, '\\');
12056 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012057 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12058 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012059 }
12060 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012061 else if (ch >= 0x10000) {
12062 PyUnicode_WRITE(okind, odata, o++, '\\');
12063 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012064 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12066 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12069 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12070 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12071 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012072 }
12073 /* Map 16-bit characters to '\uxxxx' */
12074 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012075 PyUnicode_WRITE(okind, odata, o++, '\\');
12076 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012077 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12078 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12079 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12080 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012081 }
12082 }
12083 /* Copy characters as-is */
12084 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012086 }
12087 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012088 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012090 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012091 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012092}
12093
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012094PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012095 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096\n\
12097Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012098such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099arguments start and end are interpreted as in slice notation.\n\
12100\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012101Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102
12103static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012104unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012106 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012107 Py_ssize_t start;
12108 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012109 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012110
Jesus Ceaac451502011-04-20 17:09:23 +020012111 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12112 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012113 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 if (PyUnicode_READY(self) == -1)
12116 return NULL;
12117 if (PyUnicode_READY(substring) == -1)
12118 return NULL;
12119
Victor Stinner7931d9a2011-11-04 00:22:48 +010012120 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012121
12122 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012123
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012124 if (result == -2)
12125 return NULL;
12126
Christian Heimes217cfd12007-12-02 14:31:20 +000012127 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128}
12129
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012130PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012131 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012132\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012133Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134
12135static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012137{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012138 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012139 Py_ssize_t start;
12140 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012141 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142
Jesus Ceaac451502011-04-20 17:09:23 +020012143 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12144 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012145 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012146
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012147 if (PyUnicode_READY(self) == -1)
12148 return NULL;
12149 if (PyUnicode_READY(substring) == -1)
12150 return NULL;
12151
Victor Stinner7931d9a2011-11-04 00:22:48 +010012152 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012153
12154 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012155
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012156 if (result == -2)
12157 return NULL;
12158
Guido van Rossumd57fd912000-03-10 22:53:23 +000012159 if (result < 0) {
12160 PyErr_SetString(PyExc_ValueError, "substring not found");
12161 return NULL;
12162 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012163
Christian Heimes217cfd12007-12-02 14:31:20 +000012164 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012165}
12166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012167PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012168 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012170Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012171done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012172
12173static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012174unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012176 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012177 Py_UCS4 fillchar = ' ';
12178
Victor Stinnere9a29352011-10-01 02:14:59 +020012179 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012180 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012181
Victor Stinnere9a29352011-10-01 02:14:59 +020012182 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183 return NULL;
12184
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012185 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012187 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012188 }
12189
Victor Stinner7931d9a2011-11-04 00:22:48 +010012190 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191}
12192
Alexander Belopolsky40018472011-02-26 01:02:56 +000012193PyObject *
12194PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195{
12196 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012197
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198 s = PyUnicode_FromObject(s);
12199 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012200 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012201 if (sep != NULL) {
12202 sep = PyUnicode_FromObject(sep);
12203 if (sep == NULL) {
12204 Py_DECREF(s);
12205 return NULL;
12206 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012207 }
12208
Victor Stinner9310abb2011-10-05 00:59:23 +020012209 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012210
12211 Py_DECREF(s);
12212 Py_XDECREF(sep);
12213 return result;
12214}
12215
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012216PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012217 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012218\n\
12219Return a list of the words in S, using sep as the\n\
12220delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012221splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012222whitespace string is a separator and empty strings are\n\
12223removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012224
12225static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012226unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012227{
12228 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012229 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012230
Martin v. Löwis18e16552006-02-15 17:27:45 +000012231 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012232 return NULL;
12233
12234 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012235 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012236 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012237 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012238 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012239 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240}
12241
Thomas Wouters477c8d52006-05-27 19:21:47 +000012242PyObject *
12243PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12244{
12245 PyObject* str_obj;
12246 PyObject* sep_obj;
12247 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012248 int kind1, kind2, kind;
12249 void *buf1 = NULL, *buf2 = NULL;
12250 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012251
12252 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012253 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012254 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012255 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012257 Py_DECREF(str_obj);
12258 return NULL;
12259 }
12260
Victor Stinner14f8f022011-10-05 20:58:25 +020012261 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012263 kind = Py_MAX(kind1, kind2);
12264 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012265 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012266 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012267 if (!buf1)
12268 goto onError;
12269 buf2 = PyUnicode_DATA(sep_obj);
12270 if (kind2 != kind)
12271 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12272 if (!buf2)
12273 goto onError;
12274 len1 = PyUnicode_GET_LENGTH(str_obj);
12275 len2 = PyUnicode_GET_LENGTH(sep_obj);
12276
Victor Stinner14f8f022011-10-05 20:58:25 +020012277 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012278 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012279 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12280 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12281 else
12282 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012283 break;
12284 case PyUnicode_2BYTE_KIND:
12285 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12286 break;
12287 case PyUnicode_4BYTE_KIND:
12288 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12289 break;
12290 default:
12291 assert(0);
12292 out = 0;
12293 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012294
12295 Py_DECREF(sep_obj);
12296 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012297 if (kind1 != kind)
12298 PyMem_Free(buf1);
12299 if (kind2 != kind)
12300 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012301
12302 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012303 onError:
12304 Py_DECREF(sep_obj);
12305 Py_DECREF(str_obj);
12306 if (kind1 != kind && buf1)
12307 PyMem_Free(buf1);
12308 if (kind2 != kind && buf2)
12309 PyMem_Free(buf2);
12310 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012311}
12312
12313
12314PyObject *
12315PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12316{
12317 PyObject* str_obj;
12318 PyObject* sep_obj;
12319 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012320 int kind1, kind2, kind;
12321 void *buf1 = NULL, *buf2 = NULL;
12322 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012323
12324 str_obj = PyUnicode_FromObject(str_in);
12325 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012326 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012327 sep_obj = PyUnicode_FromObject(sep_in);
12328 if (!sep_obj) {
12329 Py_DECREF(str_obj);
12330 return NULL;
12331 }
12332
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012333 kind1 = PyUnicode_KIND(str_in);
12334 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012335 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012336 buf1 = PyUnicode_DATA(str_in);
12337 if (kind1 != kind)
12338 buf1 = _PyUnicode_AsKind(str_in, kind);
12339 if (!buf1)
12340 goto onError;
12341 buf2 = PyUnicode_DATA(sep_obj);
12342 if (kind2 != kind)
12343 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12344 if (!buf2)
12345 goto onError;
12346 len1 = PyUnicode_GET_LENGTH(str_obj);
12347 len2 = PyUnicode_GET_LENGTH(sep_obj);
12348
12349 switch(PyUnicode_KIND(str_in)) {
12350 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012351 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12352 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12353 else
12354 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012355 break;
12356 case PyUnicode_2BYTE_KIND:
12357 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12358 break;
12359 case PyUnicode_4BYTE_KIND:
12360 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12361 break;
12362 default:
12363 assert(0);
12364 out = 0;
12365 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012366
12367 Py_DECREF(sep_obj);
12368 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012369 if (kind1 != kind)
12370 PyMem_Free(buf1);
12371 if (kind2 != kind)
12372 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012373
12374 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012375 onError:
12376 Py_DECREF(sep_obj);
12377 Py_DECREF(str_obj);
12378 if (kind1 != kind && buf1)
12379 PyMem_Free(buf1);
12380 if (kind2 != kind && buf2)
12381 PyMem_Free(buf2);
12382 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012383}
12384
12385PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012386 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012387\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012388Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012389the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012390found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012391
12392static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012393unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012394{
Victor Stinner9310abb2011-10-05 00:59:23 +020012395 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012396}
12397
12398PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012399 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012400\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012401Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012402the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012403separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404
12405static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012406unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012407{
Victor Stinner9310abb2011-10-05 00:59:23 +020012408 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012409}
12410
Alexander Belopolsky40018472011-02-26 01:02:56 +000012411PyObject *
12412PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012413{
12414 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012415
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012416 s = PyUnicode_FromObject(s);
12417 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012418 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012419 if (sep != NULL) {
12420 sep = PyUnicode_FromObject(sep);
12421 if (sep == NULL) {
12422 Py_DECREF(s);
12423 return NULL;
12424 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012425 }
12426
Victor Stinner9310abb2011-10-05 00:59:23 +020012427 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012428
12429 Py_DECREF(s);
12430 Py_XDECREF(sep);
12431 return result;
12432}
12433
12434PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012435 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012436\n\
12437Return a list of the words in S, using sep as the\n\
12438delimiter string, starting at the end of the string and\n\
12439working to the front. If maxsplit is given, at most maxsplit\n\
12440splits are done. If sep is not specified, any whitespace string\n\
12441is a separator.");
12442
12443static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012444unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012445{
12446 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012447 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012448
Martin v. Löwis18e16552006-02-15 17:27:45 +000012449 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012450 return NULL;
12451
12452 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012453 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012454 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012455 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012456 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012457 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012458}
12459
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012460PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012461 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012462\n\
12463Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012464Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012465is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012466
12467static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012468unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012469{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012470 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012471 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012473 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12474 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012475 return NULL;
12476
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012477 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478}
12479
12480static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012481PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482{
Walter Dörwald346737f2007-05-31 10:44:43 +000012483 if (PyUnicode_CheckExact(self)) {
12484 Py_INCREF(self);
12485 return self;
12486 } else
12487 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012488 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012489}
12490
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012491PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012492 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012493\n\
12494Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012495and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012496
12497static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012498unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012500 return fixup(self, fixswapcase);
12501}
12502
Georg Brandlceee0772007-11-27 23:48:05 +000012503PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012504 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012505\n\
12506Return a translation table usable for str.translate().\n\
12507If there is only one argument, it must be a dictionary mapping Unicode\n\
12508ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012509Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012510If there are two arguments, they must be strings of equal length, and\n\
12511in the resulting dictionary, each character in x will be mapped to the\n\
12512character at the same position in y. If there is a third argument, it\n\
12513must be a string, whose characters will be mapped to None in the result.");
12514
12515static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012516unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012517{
12518 PyObject *x, *y = NULL, *z = NULL;
12519 PyObject *new = NULL, *key, *value;
12520 Py_ssize_t i = 0;
12521 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012522
Georg Brandlceee0772007-11-27 23:48:05 +000012523 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12524 return NULL;
12525 new = PyDict_New();
12526 if (!new)
12527 return NULL;
12528 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 int x_kind, y_kind, z_kind;
12530 void *x_data, *y_data, *z_data;
12531
Georg Brandlceee0772007-11-27 23:48:05 +000012532 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012533 if (!PyUnicode_Check(x)) {
12534 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12535 "be a string if there is a second argument");
12536 goto err;
12537 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012538 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012539 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12540 "arguments must have equal length");
12541 goto err;
12542 }
12543 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012544 x_kind = PyUnicode_KIND(x);
12545 y_kind = PyUnicode_KIND(y);
12546 x_data = PyUnicode_DATA(x);
12547 y_data = PyUnicode_DATA(y);
12548 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12549 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12550 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012551 if (!key || !value)
12552 goto err;
12553 res = PyDict_SetItem(new, key, value);
12554 Py_DECREF(key);
12555 Py_DECREF(value);
12556 if (res < 0)
12557 goto err;
12558 }
12559 /* create entries for deleting chars in z */
12560 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012561 z_kind = PyUnicode_KIND(z);
12562 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012563 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012564 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012565 if (!key)
12566 goto err;
12567 res = PyDict_SetItem(new, key, Py_None);
12568 Py_DECREF(key);
12569 if (res < 0)
12570 goto err;
12571 }
12572 }
12573 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 int kind;
12575 void *data;
12576
Georg Brandlceee0772007-11-27 23:48:05 +000012577 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012578 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012579 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12580 "to maketrans it must be a dict");
12581 goto err;
12582 }
12583 /* copy entries into the new dict, converting string keys to int keys */
12584 while (PyDict_Next(x, &i, &key, &value)) {
12585 if (PyUnicode_Check(key)) {
12586 /* convert string keys to integer keys */
12587 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012588 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012589 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12590 "table must be of length 1");
12591 goto err;
12592 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012593 kind = PyUnicode_KIND(key);
12594 data = PyUnicode_DATA(key);
12595 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012596 if (!newkey)
12597 goto err;
12598 res = PyDict_SetItem(new, newkey, value);
12599 Py_DECREF(newkey);
12600 if (res < 0)
12601 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012602 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012603 /* just keep integer keys */
12604 if (PyDict_SetItem(new, key, value) < 0)
12605 goto err;
12606 } else {
12607 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12608 "be strings or integers");
12609 goto err;
12610 }
12611 }
12612 }
12613 return new;
12614 err:
12615 Py_DECREF(new);
12616 return NULL;
12617}
12618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012619PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012620 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621\n\
12622Return a copy of the string S, where all characters have been mapped\n\
12623through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012624Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012625Unmapped characters are left untouched. Characters mapped to None\n\
12626are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627
12628static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012629unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012630{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012631 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632}
12633
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012634PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012635 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012637Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638
12639static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012640unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012641{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642 return fixup(self, fixupper);
12643}
12644
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012645PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012646 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012648Pad a numeric string S with zeros on the left, to fill a field\n\
12649of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650
12651static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012652unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012653{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012654 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012655 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012656 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012657 int kind;
12658 void *data;
12659 Py_UCS4 chr;
12660
12661 if (PyUnicode_READY(self) == -1)
12662 return NULL;
12663
Martin v. Löwis18e16552006-02-15 17:27:45 +000012664 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012665 return NULL;
12666
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012668 if (PyUnicode_CheckExact(self)) {
12669 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012670 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012671 }
12672 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012673 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012674 }
12675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012676 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012677
12678 u = pad(self, fill, 0, '0');
12679
Walter Dörwald068325e2002-04-15 13:36:47 +000012680 if (u == NULL)
12681 return NULL;
12682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012683 kind = PyUnicode_KIND(u);
12684 data = PyUnicode_DATA(u);
12685 chr = PyUnicode_READ(kind, data, fill);
12686
12687 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012689 PyUnicode_WRITE(kind, data, 0, chr);
12690 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012691 }
12692
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012693 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012694 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012695}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012696
12697#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012698static PyObject *
12699unicode__decimal2ascii(PyObject *self)
12700{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012701 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012702}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012703#endif
12704
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012705PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012706 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012708Return True if S starts with the specified prefix, False otherwise.\n\
12709With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012710With optional end, stop comparing S at that position.\n\
12711prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012712
12713static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012714unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012715 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012716{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012717 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012718 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012719 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012720 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012721 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722
Jesus Ceaac451502011-04-20 17:09:23 +020012723 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012724 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012725 if (PyTuple_Check(subobj)) {
12726 Py_ssize_t i;
12727 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012728 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012729 if (substring == NULL)
12730 return NULL;
12731 result = tailmatch(self, substring, start, end, -1);
12732 Py_DECREF(substring);
12733 if (result) {
12734 Py_RETURN_TRUE;
12735 }
12736 }
12737 /* nothing matched */
12738 Py_RETURN_FALSE;
12739 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012740 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012741 if (substring == NULL) {
12742 if (PyErr_ExceptionMatches(PyExc_TypeError))
12743 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12744 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012745 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012746 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012747 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012748 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012749 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012750}
12751
12752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012753PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012754 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012756Return True if S ends with the specified suffix, False otherwise.\n\
12757With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012758With optional end, stop comparing S at that position.\n\
12759suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760
12761static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012762unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012763 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012764{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012765 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012766 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012767 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012768 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012769 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770
Jesus Ceaac451502011-04-20 17:09:23 +020012771 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012772 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012773 if (PyTuple_Check(subobj)) {
12774 Py_ssize_t i;
12775 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012776 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012777 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012778 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012779 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012780 result = tailmatch(self, substring, start, end, +1);
12781 Py_DECREF(substring);
12782 if (result) {
12783 Py_RETURN_TRUE;
12784 }
12785 }
12786 Py_RETURN_FALSE;
12787 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012788 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012789 if (substring == NULL) {
12790 if (PyErr_ExceptionMatches(PyExc_TypeError))
12791 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12792 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012793 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012794 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012795 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012796 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012797 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012798}
12799
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012800#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012801
12802PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012803 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012804\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012805Return a formatted version of S, using substitutions from args and kwargs.\n\
12806The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012807
Eric Smith27bbca62010-11-04 17:06:58 +000012808PyDoc_STRVAR(format_map__doc__,
12809 "S.format_map(mapping) -> str\n\
12810\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012811Return a formatted version of S, using substitutions from mapping.\n\
12812The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012813
Eric Smith4a7d76d2008-05-30 18:10:19 +000012814static PyObject *
12815unicode__format__(PyObject* self, PyObject* args)
12816{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012817 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012818
12819 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12820 return NULL;
12821
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012822 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012823 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012824 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012825}
12826
Eric Smith8c663262007-08-25 02:26:07 +000012827PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012828 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012829\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012830Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012831
12832static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012833unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012834{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012835 Py_ssize_t size;
12836
12837 /* If it's a compact object, account for base structure +
12838 character data. */
12839 if (PyUnicode_IS_COMPACT_ASCII(v))
12840 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12841 else if (PyUnicode_IS_COMPACT(v))
12842 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012843 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012844 else {
12845 /* If it is a two-block object, account for base object, and
12846 for character block if present. */
12847 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012848 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012849 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012850 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012851 }
12852 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012853 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012854 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012855 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012856 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012857 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012858
12859 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012860}
12861
12862PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012863 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012864
12865static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012866unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012867{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012868 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012869 if (!copy)
12870 return NULL;
12871 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012872}
12873
Guido van Rossumd57fd912000-03-10 22:53:23 +000012874static PyMethodDef unicode_methods[] = {
12875
12876 /* Order is according to common usage: often used methods should
12877 appear first, since lookup is done sequentially. */
12878
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012879 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012880 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12881 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012882 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012883 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12884 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12885 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12886 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12887 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12888 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12889 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012890 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012891 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12892 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12893 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012894 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012895 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12896 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12897 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012898 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012899 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012900 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012901 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012902 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12903 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12904 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12905 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12906 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12907 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12908 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12909 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12910 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12911 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12912 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12913 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12914 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12915 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012916 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012917 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012918 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012919 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012920 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012921 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012922 {"maketrans", (PyCFunction) unicode_maketrans,
12923 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012924 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012925#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012926 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012927#endif
12928
12929#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012930 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012931 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012932#endif
12933
Benjamin Peterson14339b62009-01-31 16:36:08 +000012934 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012935 {NULL, NULL}
12936};
12937
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012938static PyObject *
12939unicode_mod(PyObject *v, PyObject *w)
12940{
Brian Curtindfc80e32011-08-10 20:28:54 -050012941 if (!PyUnicode_Check(v))
12942 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012943 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012944}
12945
12946static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012947 0, /*nb_add*/
12948 0, /*nb_subtract*/
12949 0, /*nb_multiply*/
12950 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012951};
12952
Guido van Rossumd57fd912000-03-10 22:53:23 +000012953static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012954 (lenfunc) unicode_length, /* sq_length */
12955 PyUnicode_Concat, /* sq_concat */
12956 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12957 (ssizeargfunc) unicode_getitem, /* sq_item */
12958 0, /* sq_slice */
12959 0, /* sq_ass_item */
12960 0, /* sq_ass_slice */
12961 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012962};
12963
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012964static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012965unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012966{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012967 if (PyUnicode_READY(self) == -1)
12968 return NULL;
12969
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012970 if (PyIndex_Check(item)) {
12971 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012972 if (i == -1 && PyErr_Occurred())
12973 return NULL;
12974 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012975 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012976 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012977 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012978 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012979 PyObject *result;
12980 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012981 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012982 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012984 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012985 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012986 return NULL;
12987 }
12988
12989 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012990 return PyUnicode_New(0, 0);
12991 } else if (start == 0 && step == 1 &&
12992 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012993 PyUnicode_CheckExact(self)) {
12994 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012995 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000012996 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012997 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020012998 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012999 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013000 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013001 src_kind = PyUnicode_KIND(self);
13002 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013003 if (!PyUnicode_IS_ASCII(self)) {
13004 kind_limit = kind_maxchar_limit(src_kind);
13005 max_char = 0;
13006 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13007 ch = PyUnicode_READ(src_kind, src_data, cur);
13008 if (ch > max_char) {
13009 max_char = ch;
13010 if (max_char >= kind_limit)
13011 break;
13012 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013013 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013014 }
Victor Stinner55c99112011-10-13 01:17:06 +020013015 else
13016 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013017 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013018 if (result == NULL)
13019 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013020 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013021 dest_data = PyUnicode_DATA(result);
13022
13023 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013024 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13025 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013026 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013027 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013028 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013029 } else {
13030 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13031 return NULL;
13032 }
13033}
13034
13035static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013036 (lenfunc)unicode_length, /* mp_length */
13037 (binaryfunc)unicode_subscript, /* mp_subscript */
13038 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013039};
13040
Guido van Rossumd57fd912000-03-10 22:53:23 +000013041
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042/* Helpers for PyUnicode_Format() */
13043
13044static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013045getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013046{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013047 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013048 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013049 (*p_argidx)++;
13050 if (arglen < 0)
13051 return args;
13052 else
13053 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054 }
13055 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013056 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013057 return NULL;
13058}
13059
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013060/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013061
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013062static PyObject *
13063formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013064{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013065 char *p;
13066 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013068
Guido van Rossumd57fd912000-03-10 22:53:23 +000013069 x = PyFloat_AsDouble(v);
13070 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013071 return NULL;
13072
Guido van Rossumd57fd912000-03-10 22:53:23 +000013073 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013074 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013075
Eric Smith0923d1d2009-04-16 20:16:10 +000013076 p = PyOS_double_to_string(x, type, prec,
13077 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013078 if (p == NULL)
13079 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013080 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013081 PyMem_Free(p);
13082 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083}
13084
Tim Peters38fd5b62000-09-21 05:43:11 +000013085static PyObject*
13086formatlong(PyObject *val, int flags, int prec, int type)
13087{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013088 char *buf;
13089 int len;
13090 PyObject *str; /* temporary string object. */
13091 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013092
Benjamin Peterson14339b62009-01-31 16:36:08 +000013093 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13094 if (!str)
13095 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013096 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013097 Py_DECREF(str);
13098 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013099}
13100
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013101static Py_UCS4
13102formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013103{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013104 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013105 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013106 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013107 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013108 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013109 goto onError;
13110 }
13111 else {
13112 /* Integer input truncated to a character */
13113 long x;
13114 x = PyLong_AsLong(v);
13115 if (x == -1 && PyErr_Occurred())
13116 goto onError;
13117
13118 if (x < 0 || x > 0x10ffff) {
13119 PyErr_SetString(PyExc_OverflowError,
13120 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013121 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013122 }
13123
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013124 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013125 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013126
Benjamin Peterson29060642009-01-31 22:14:21 +000013127 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013128 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013129 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013130 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013131}
13132
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013133static int
13134repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13135{
13136 int r;
13137 assert(count > 0);
13138 assert(PyUnicode_Check(obj));
13139 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013140 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013141 if (repeated == NULL)
13142 return -1;
13143 r = _PyAccu_Accumulate(acc, repeated);
13144 Py_DECREF(repeated);
13145 return r;
13146 }
13147 else {
13148 do {
13149 if (_PyAccu_Accumulate(acc, obj))
13150 return -1;
13151 } while (--count);
13152 return 0;
13153 }
13154}
13155
Alexander Belopolsky40018472011-02-26 01:02:56 +000013156PyObject *
13157PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013158{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013159 void *fmt;
13160 int fmtkind;
13161 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013162 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013163 int r;
13164 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013165 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013166 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013167 PyObject *temp = NULL;
13168 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013169 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013170 _PyAccu acc;
13171 static PyObject *plus, *minus, *blank, *zero, *percent;
13172
13173 if (!plus && !(plus = get_latin1_char('+')))
13174 return NULL;
13175 if (!minus && !(minus = get_latin1_char('-')))
13176 return NULL;
13177 if (!blank && !(blank = get_latin1_char(' ')))
13178 return NULL;
13179 if (!zero && !(zero = get_latin1_char('0')))
13180 return NULL;
13181 if (!percent && !(percent = get_latin1_char('%')))
13182 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013183
Guido van Rossumd57fd912000-03-10 22:53:23 +000013184 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013185 PyErr_BadInternalCall();
13186 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013187 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013188 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013189 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013190 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013191 if (_PyAccu_Init(&acc))
13192 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013193 fmt = PyUnicode_DATA(uformat);
13194 fmtkind = PyUnicode_KIND(uformat);
13195 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13196 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197
Guido van Rossumd57fd912000-03-10 22:53:23 +000013198 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013199 arglen = PyTuple_Size(args);
13200 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013201 }
13202 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013203 arglen = -1;
13204 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013205 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013206 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013207 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013208 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013209
13210 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013211 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013212 PyObject *nonfmt;
13213 Py_ssize_t nonfmtpos;
13214 nonfmtpos = fmtpos++;
13215 while (fmtcnt >= 0 &&
13216 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13217 fmtpos++;
13218 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013219 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013220 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013221 if (nonfmt == NULL)
13222 goto onError;
13223 r = _PyAccu_Accumulate(&acc, nonfmt);
13224 Py_DECREF(nonfmt);
13225 if (r)
13226 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013227 }
13228 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013229 /* Got a format specifier */
13230 int flags = 0;
13231 Py_ssize_t width = -1;
13232 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013233 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013234 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013235 int isnumok;
13236 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013237 void *pbuf = NULL;
13238 Py_ssize_t pindex, len;
13239 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013241 fmtpos++;
13242 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13243 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 Py_ssize_t keylen;
13245 PyObject *key;
13246 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013247
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 if (dict == NULL) {
13249 PyErr_SetString(PyExc_TypeError,
13250 "format requires a mapping");
13251 goto onError;
13252 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013253 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013255 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 /* Skip over balanced parentheses */
13257 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013258 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013259 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013260 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013261 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013262 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013263 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013264 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013265 if (fmtcnt < 0 || pcount > 0) {
13266 PyErr_SetString(PyExc_ValueError,
13267 "incomplete format key");
13268 goto onError;
13269 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013270 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013271 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013272 if (key == NULL)
13273 goto onError;
13274 if (args_owned) {
13275 Py_DECREF(args);
13276 args_owned = 0;
13277 }
13278 args = PyObject_GetItem(dict, key);
13279 Py_DECREF(key);
13280 if (args == NULL) {
13281 goto onError;
13282 }
13283 args_owned = 1;
13284 arglen = -1;
13285 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013286 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013287 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013288 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013289 case '-': flags |= F_LJUST; continue;
13290 case '+': flags |= F_SIGN; continue;
13291 case ' ': flags |= F_BLANK; continue;
13292 case '#': flags |= F_ALT; continue;
13293 case '0': flags |= F_ZERO; continue;
13294 }
13295 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013296 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013297 if (c == '*') {
13298 v = getnextarg(args, arglen, &argidx);
13299 if (v == NULL)
13300 goto onError;
13301 if (!PyLong_Check(v)) {
13302 PyErr_SetString(PyExc_TypeError,
13303 "* wants int");
13304 goto onError;
13305 }
13306 width = PyLong_AsLong(v);
13307 if (width == -1 && PyErr_Occurred())
13308 goto onError;
13309 if (width < 0) {
13310 flags |= F_LJUST;
13311 width = -width;
13312 }
13313 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013314 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013315 }
13316 else if (c >= '0' && c <= '9') {
13317 width = c - '0';
13318 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013319 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013320 if (c < '0' || c > '9')
13321 break;
13322 if ((width*10) / 10 != width) {
13323 PyErr_SetString(PyExc_ValueError,
13324 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013325 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013326 }
13327 width = width*10 + (c - '0');
13328 }
13329 }
13330 if (c == '.') {
13331 prec = 0;
13332 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013333 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013334 if (c == '*') {
13335 v = getnextarg(args, arglen, &argidx);
13336 if (v == NULL)
13337 goto onError;
13338 if (!PyLong_Check(v)) {
13339 PyErr_SetString(PyExc_TypeError,
13340 "* wants int");
13341 goto onError;
13342 }
13343 prec = PyLong_AsLong(v);
13344 if (prec == -1 && PyErr_Occurred())
13345 goto onError;
13346 if (prec < 0)
13347 prec = 0;
13348 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013349 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013350 }
13351 else if (c >= '0' && c <= '9') {
13352 prec = c - '0';
13353 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013354 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 if (c < '0' || c > '9')
13356 break;
13357 if ((prec*10) / 10 != prec) {
13358 PyErr_SetString(PyExc_ValueError,
13359 "prec too big");
13360 goto onError;
13361 }
13362 prec = prec*10 + (c - '0');
13363 }
13364 }
13365 } /* prec */
13366 if (fmtcnt >= 0) {
13367 if (c == 'h' || c == 'l' || c == 'L') {
13368 if (--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 }
13371 }
13372 if (fmtcnt < 0) {
13373 PyErr_SetString(PyExc_ValueError,
13374 "incomplete format");
13375 goto onError;
13376 }
13377 if (c != '%') {
13378 v = getnextarg(args, arglen, &argidx);
13379 if (v == NULL)
13380 goto onError;
13381 }
13382 sign = 0;
13383 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013384 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013385 switch (c) {
13386
13387 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013388 _PyAccu_Accumulate(&acc, percent);
13389 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013390
13391 case 's':
13392 case 'r':
13393 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013394 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 temp = v;
13396 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013397 }
13398 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013399 if (c == 's')
13400 temp = PyObject_Str(v);
13401 else if (c == 'r')
13402 temp = PyObject_Repr(v);
13403 else
13404 temp = PyObject_ASCII(v);
13405 if (temp == NULL)
13406 goto onError;
13407 if (PyUnicode_Check(temp))
13408 /* nothing to do */;
13409 else {
13410 Py_DECREF(temp);
13411 PyErr_SetString(PyExc_TypeError,
13412 "%s argument has non-string str()");
13413 goto onError;
13414 }
13415 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013416 if (PyUnicode_READY(temp) == -1) {
13417 Py_CLEAR(temp);
13418 goto onError;
13419 }
13420 pbuf = PyUnicode_DATA(temp);
13421 kind = PyUnicode_KIND(temp);
13422 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013423 if (prec >= 0 && len > prec)
13424 len = prec;
13425 break;
13426
13427 case 'i':
13428 case 'd':
13429 case 'u':
13430 case 'o':
13431 case 'x':
13432 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 isnumok = 0;
13434 if (PyNumber_Check(v)) {
13435 PyObject *iobj=NULL;
13436
13437 if (PyLong_Check(v)) {
13438 iobj = v;
13439 Py_INCREF(iobj);
13440 }
13441 else {
13442 iobj = PyNumber_Long(v);
13443 }
13444 if (iobj!=NULL) {
13445 if (PyLong_Check(iobj)) {
13446 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013447 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013448 Py_DECREF(iobj);
13449 if (!temp)
13450 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013451 if (PyUnicode_READY(temp) == -1) {
13452 Py_CLEAR(temp);
13453 goto onError;
13454 }
13455 pbuf = PyUnicode_DATA(temp);
13456 kind = PyUnicode_KIND(temp);
13457 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013458 sign = 1;
13459 }
13460 else {
13461 Py_DECREF(iobj);
13462 }
13463 }
13464 }
13465 if (!isnumok) {
13466 PyErr_Format(PyExc_TypeError,
13467 "%%%c format: a number is required, "
13468 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13469 goto onError;
13470 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013471 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013472 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013473 fillobj = zero;
13474 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013475 break;
13476
13477 case 'e':
13478 case 'E':
13479 case 'f':
13480 case 'F':
13481 case 'g':
13482 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013483 temp = formatfloat(v, flags, prec, c);
13484 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013486 if (PyUnicode_READY(temp) == -1) {
13487 Py_CLEAR(temp);
13488 goto onError;
13489 }
13490 pbuf = PyUnicode_DATA(temp);
13491 kind = PyUnicode_KIND(temp);
13492 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013493 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013494 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013496 fillobj = zero;
13497 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013498 break;
13499
13500 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013501 {
13502 Py_UCS4 ch = formatchar(v);
13503 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013504 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013505 temp = _PyUnicode_FromUCS4(&ch, 1);
13506 if (temp == NULL)
13507 goto onError;
13508 pbuf = PyUnicode_DATA(temp);
13509 kind = PyUnicode_KIND(temp);
13510 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013511 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013512 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013513
13514 default:
13515 PyErr_Format(PyExc_ValueError,
13516 "unsupported format character '%c' (0x%x) "
13517 "at index %zd",
13518 (31<=c && c<=126) ? (char)c : '?',
13519 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013520 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 goto onError;
13522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013523 /* pbuf is initialized here. */
13524 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013526 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13527 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013528 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013529 pindex++;
13530 }
13531 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13532 signobj = plus;
13533 len--;
13534 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 }
13536 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013537 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013538 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013539 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013540 else
13541 sign = 0;
13542 }
13543 if (width < len)
13544 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013546 if (fill != ' ') {
13547 assert(signobj != NULL);
13548 if (_PyAccu_Accumulate(&acc, signobj))
13549 goto onError;
13550 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 if (width > len)
13552 width--;
13553 }
13554 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013555 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013556 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013557 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013558 second = get_latin1_char(
13559 PyUnicode_READ(kind, pbuf, pindex + 1));
13560 pindex += 2;
13561 if (second == NULL ||
13562 _PyAccu_Accumulate(&acc, zero) ||
13563 _PyAccu_Accumulate(&acc, second))
13564 goto onError;
13565 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013566 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 width -= 2;
13568 if (width < 0)
13569 width = 0;
13570 len -= 2;
13571 }
13572 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013573 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013574 if (repeat_accumulate(&acc, fillobj, width - len))
13575 goto onError;
13576 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013577 }
13578 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013579 if (sign) {
13580 assert(signobj != NULL);
13581 if (_PyAccu_Accumulate(&acc, signobj))
13582 goto onError;
13583 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013584 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013585 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13586 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013587 second = get_latin1_char(
13588 PyUnicode_READ(kind, pbuf, pindex + 1));
13589 pindex += 2;
13590 if (second == NULL ||
13591 _PyAccu_Accumulate(&acc, zero) ||
13592 _PyAccu_Accumulate(&acc, second))
13593 goto onError;
13594 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013595 }
13596 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013597 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013598 if (temp != NULL) {
13599 assert(pbuf == PyUnicode_DATA(temp));
13600 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013601 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013602 else {
13603 const char *p = (const char *) pbuf;
13604 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013605 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013606 v = PyUnicode_FromKindAndData(kind, p, len);
13607 }
13608 if (v == NULL)
13609 goto onError;
13610 r = _PyAccu_Accumulate(&acc, v);
13611 Py_DECREF(v);
13612 if (r)
13613 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013614 if (width > len && repeat_accumulate(&acc, blank, width - len))
13615 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013616 if (dict && (argidx < arglen) && c != '%') {
13617 PyErr_SetString(PyExc_TypeError,
13618 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013619 goto onError;
13620 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013621 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013622 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013623 } /* until end */
13624 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013625 PyErr_SetString(PyExc_TypeError,
13626 "not all arguments converted during string formatting");
13627 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013628 }
13629
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013630 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013631 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013633 }
13634 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013635 Py_XDECREF(temp);
13636 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013637 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013638
Benjamin Peterson29060642009-01-31 22:14:21 +000013639 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013640 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013641 Py_XDECREF(temp);
13642 Py_XDECREF(second);
13643 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013644 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013645 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013646 }
13647 return NULL;
13648}
13649
Jeremy Hylton938ace62002-07-17 16:30:39 +000013650static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013651unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13652
Tim Peters6d6c1a32001-08-02 04:15:00 +000013653static PyObject *
13654unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13655{
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013657 static char *kwlist[] = {"object", "encoding", "errors", 0};
13658 char *encoding = NULL;
13659 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013660
Benjamin Peterson14339b62009-01-31 16:36:08 +000013661 if (type != &PyUnicode_Type)
13662 return unicode_subtype_new(type, args, kwds);
13663 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013664 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013665 return NULL;
13666 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013667 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013668 if (encoding == NULL && errors == NULL)
13669 return PyObject_Str(x);
13670 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013671 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013672}
13673
Guido van Rossume023fe02001-08-30 03:12:59 +000013674static PyObject *
13675unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13676{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013677 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013678 Py_ssize_t length, char_size;
13679 int share_wstr, share_utf8;
13680 unsigned int kind;
13681 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013682
Benjamin Peterson14339b62009-01-31 16:36:08 +000013683 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013684
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013685 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013686 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013687 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013688 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013689 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013690 return NULL;
13691
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013692 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013693 if (self == NULL) {
13694 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013695 return NULL;
13696 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013697 kind = PyUnicode_KIND(unicode);
13698 length = PyUnicode_GET_LENGTH(unicode);
13699
13700 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013701#ifdef Py_DEBUG
13702 _PyUnicode_HASH(self) = -1;
13703#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013704 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013705#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013706 _PyUnicode_STATE(self).interned = 0;
13707 _PyUnicode_STATE(self).kind = kind;
13708 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013709 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013710 _PyUnicode_STATE(self).ready = 1;
13711 _PyUnicode_WSTR(self) = NULL;
13712 _PyUnicode_UTF8_LENGTH(self) = 0;
13713 _PyUnicode_UTF8(self) = NULL;
13714 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013715 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013716
13717 share_utf8 = 0;
13718 share_wstr = 0;
13719 if (kind == PyUnicode_1BYTE_KIND) {
13720 char_size = 1;
13721 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13722 share_utf8 = 1;
13723 }
13724 else if (kind == PyUnicode_2BYTE_KIND) {
13725 char_size = 2;
13726 if (sizeof(wchar_t) == 2)
13727 share_wstr = 1;
13728 }
13729 else {
13730 assert(kind == PyUnicode_4BYTE_KIND);
13731 char_size = 4;
13732 if (sizeof(wchar_t) == 4)
13733 share_wstr = 1;
13734 }
13735
13736 /* Ensure we won't overflow the length. */
13737 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13738 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013739 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013740 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013741 data = PyObject_MALLOC((length + 1) * char_size);
13742 if (data == NULL) {
13743 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013744 goto onError;
13745 }
13746
Victor Stinnerc3c74152011-10-02 20:39:55 +020013747 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013748 if (share_utf8) {
13749 _PyUnicode_UTF8_LENGTH(self) = length;
13750 _PyUnicode_UTF8(self) = data;
13751 }
13752 if (share_wstr) {
13753 _PyUnicode_WSTR_LENGTH(self) = length;
13754 _PyUnicode_WSTR(self) = (wchar_t *)data;
13755 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013756
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013757 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013758 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013759 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013760#ifdef Py_DEBUG
13761 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13762#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013763 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013764 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013765
13766onError:
13767 Py_DECREF(unicode);
13768 Py_DECREF(self);
13769 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013770}
13771
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013772PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013773 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013774\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013775Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013776encoding defaults to the current default string encoding.\n\
13777errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013778
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013779static PyObject *unicode_iter(PyObject *seq);
13780
Guido van Rossumd57fd912000-03-10 22:53:23 +000013781PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013782 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013783 "str", /* tp_name */
13784 sizeof(PyUnicodeObject), /* tp_size */
13785 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013786 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013787 (destructor)unicode_dealloc, /* tp_dealloc */
13788 0, /* tp_print */
13789 0, /* tp_getattr */
13790 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013791 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013792 unicode_repr, /* tp_repr */
13793 &unicode_as_number, /* tp_as_number */
13794 &unicode_as_sequence, /* tp_as_sequence */
13795 &unicode_as_mapping, /* tp_as_mapping */
13796 (hashfunc) unicode_hash, /* tp_hash*/
13797 0, /* tp_call*/
13798 (reprfunc) unicode_str, /* tp_str */
13799 PyObject_GenericGetAttr, /* tp_getattro */
13800 0, /* tp_setattro */
13801 0, /* tp_as_buffer */
13802 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013803 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013804 unicode_doc, /* tp_doc */
13805 0, /* tp_traverse */
13806 0, /* tp_clear */
13807 PyUnicode_RichCompare, /* tp_richcompare */
13808 0, /* tp_weaklistoffset */
13809 unicode_iter, /* tp_iter */
13810 0, /* tp_iternext */
13811 unicode_methods, /* tp_methods */
13812 0, /* tp_members */
13813 0, /* tp_getset */
13814 &PyBaseObject_Type, /* tp_base */
13815 0, /* tp_dict */
13816 0, /* tp_descr_get */
13817 0, /* tp_descr_set */
13818 0, /* tp_dictoffset */
13819 0, /* tp_init */
13820 0, /* tp_alloc */
13821 unicode_new, /* tp_new */
13822 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013823};
13824
13825/* Initialize the Unicode implementation */
13826
Victor Stinner3a50e702011-10-18 21:21:00 +020013827int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013828{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013829 int i;
13830
Thomas Wouters477c8d52006-05-27 19:21:47 +000013831 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013832 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013833 0x000A, /* LINE FEED */
13834 0x000D, /* CARRIAGE RETURN */
13835 0x001C, /* FILE SEPARATOR */
13836 0x001D, /* GROUP SEPARATOR */
13837 0x001E, /* RECORD SEPARATOR */
13838 0x0085, /* NEXT LINE */
13839 0x2028, /* LINE SEPARATOR */
13840 0x2029, /* PARAGRAPH SEPARATOR */
13841 };
13842
Fred Drakee4315f52000-05-09 19:53:39 +000013843 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013844 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013845 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013846 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013847 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013848
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013849 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013850 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013851 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013852 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013853
13854 /* initialize the linebreak bloom filter */
13855 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013856 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013857 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013858
13859 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013860
13861#ifdef HAVE_MBCS
13862 winver.dwOSVersionInfoSize = sizeof(winver);
13863 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13864 PyErr_SetFromWindowsErr(0);
13865 return -1;
13866 }
13867#endif
13868 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013869}
13870
13871/* Finalize the Unicode implementation */
13872
Christian Heimesa156e092008-02-16 07:38:31 +000013873int
13874PyUnicode_ClearFreeList(void)
13875{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013876 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013877}
13878
Guido van Rossumd57fd912000-03-10 22:53:23 +000013879void
Thomas Wouters78890102000-07-22 19:25:51 +000013880_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013881{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013882 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013883
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013884 Py_XDECREF(unicode_empty);
13885 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013886
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013887 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013888 if (unicode_latin1[i]) {
13889 Py_DECREF(unicode_latin1[i]);
13890 unicode_latin1[i] = NULL;
13891 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013892 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013893 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013894 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013895}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013896
Walter Dörwald16807132007-05-25 13:52:07 +000013897void
13898PyUnicode_InternInPlace(PyObject **p)
13899{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013900 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013901 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013902#ifdef Py_DEBUG
13903 assert(s != NULL);
13904 assert(_PyUnicode_CHECK(s));
13905#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013906 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013907 return;
13908#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013909 /* If it's a subclass, we don't really know what putting
13910 it in the interned dict might do. */
13911 if (!PyUnicode_CheckExact(s))
13912 return;
13913 if (PyUnicode_CHECK_INTERNED(s))
13914 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013915 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013916 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013917 return;
13918 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013919 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013920 if (interned == NULL) {
13921 interned = PyDict_New();
13922 if (interned == NULL) {
13923 PyErr_Clear(); /* Don't leave an exception */
13924 return;
13925 }
13926 }
13927 /* It might be that the GetItem call fails even
13928 though the key is present in the dictionary,
13929 namely when this happens during a stack overflow. */
13930 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013931 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013932 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013933
Benjamin Peterson29060642009-01-31 22:14:21 +000013934 if (t) {
13935 Py_INCREF(t);
13936 Py_DECREF(*p);
13937 *p = t;
13938 return;
13939 }
Walter Dörwald16807132007-05-25 13:52:07 +000013940
Benjamin Peterson14339b62009-01-31 16:36:08 +000013941 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013942 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013943 PyErr_Clear();
13944 PyThreadState_GET()->recursion_critical = 0;
13945 return;
13946 }
13947 PyThreadState_GET()->recursion_critical = 0;
13948 /* The two references in interned are not counted by refcnt.
13949 The deallocator will take care of this */
13950 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013951 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013952}
13953
13954void
13955PyUnicode_InternImmortal(PyObject **p)
13956{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 PyUnicode_InternInPlace(p);
13958 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013959 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013960 Py_INCREF(*p);
13961 }
Walter Dörwald16807132007-05-25 13:52:07 +000013962}
13963
13964PyObject *
13965PyUnicode_InternFromString(const char *cp)
13966{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 PyObject *s = PyUnicode_FromString(cp);
13968 if (s == NULL)
13969 return NULL;
13970 PyUnicode_InternInPlace(&s);
13971 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013972}
13973
Alexander Belopolsky40018472011-02-26 01:02:56 +000013974void
13975_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013976{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013977 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013978 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013979 Py_ssize_t i, n;
13980 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013981
Benjamin Peterson14339b62009-01-31 16:36:08 +000013982 if (interned == NULL || !PyDict_Check(interned))
13983 return;
13984 keys = PyDict_Keys(interned);
13985 if (keys == NULL || !PyList_Check(keys)) {
13986 PyErr_Clear();
13987 return;
13988 }
Walter Dörwald16807132007-05-25 13:52:07 +000013989
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13991 detector, interned unicode strings are not forcibly deallocated;
13992 rather, we give them their stolen references back, and then clear
13993 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013994
Benjamin Peterson14339b62009-01-31 16:36:08 +000013995 n = PyList_GET_SIZE(keys);
13996 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013997 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013998 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013999 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014000 if (PyUnicode_READY(s) == -1) {
14001 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014002 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014003 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014004 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014005 case SSTATE_NOT_INTERNED:
14006 /* XXX Shouldn't happen */
14007 break;
14008 case SSTATE_INTERNED_IMMORTAL:
14009 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014010 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014011 break;
14012 case SSTATE_INTERNED_MORTAL:
14013 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014014 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014015 break;
14016 default:
14017 Py_FatalError("Inconsistent interned string state.");
14018 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014019 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014020 }
14021 fprintf(stderr, "total size of all interned strings: "
14022 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14023 "mortal/immortal\n", mortal_size, immortal_size);
14024 Py_DECREF(keys);
14025 PyDict_Clear(interned);
14026 Py_DECREF(interned);
14027 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014028}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014029
14030
14031/********************* Unicode Iterator **************************/
14032
14033typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 PyObject_HEAD
14035 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014036 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014037} unicodeiterobject;
14038
14039static void
14040unicodeiter_dealloc(unicodeiterobject *it)
14041{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 _PyObject_GC_UNTRACK(it);
14043 Py_XDECREF(it->it_seq);
14044 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014045}
14046
14047static int
14048unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14049{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014050 Py_VISIT(it->it_seq);
14051 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014052}
14053
14054static PyObject *
14055unicodeiter_next(unicodeiterobject *it)
14056{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014057 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014058
Benjamin Peterson14339b62009-01-31 16:36:08 +000014059 assert(it != NULL);
14060 seq = it->it_seq;
14061 if (seq == NULL)
14062 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014063 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014065 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14066 int kind = PyUnicode_KIND(seq);
14067 void *data = PyUnicode_DATA(seq);
14068 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14069 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014070 if (item != NULL)
14071 ++it->it_index;
14072 return item;
14073 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014074
Benjamin Peterson14339b62009-01-31 16:36:08 +000014075 Py_DECREF(seq);
14076 it->it_seq = NULL;
14077 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014078}
14079
14080static PyObject *
14081unicodeiter_len(unicodeiterobject *it)
14082{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 Py_ssize_t len = 0;
14084 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014085 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014086 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014087}
14088
14089PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14090
14091static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014092 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014093 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014095};
14096
14097PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014098 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14099 "str_iterator", /* tp_name */
14100 sizeof(unicodeiterobject), /* tp_basicsize */
14101 0, /* tp_itemsize */
14102 /* methods */
14103 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14104 0, /* tp_print */
14105 0, /* tp_getattr */
14106 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014107 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 0, /* tp_repr */
14109 0, /* tp_as_number */
14110 0, /* tp_as_sequence */
14111 0, /* tp_as_mapping */
14112 0, /* tp_hash */
14113 0, /* tp_call */
14114 0, /* tp_str */
14115 PyObject_GenericGetAttr, /* tp_getattro */
14116 0, /* tp_setattro */
14117 0, /* tp_as_buffer */
14118 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14119 0, /* tp_doc */
14120 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14121 0, /* tp_clear */
14122 0, /* tp_richcompare */
14123 0, /* tp_weaklistoffset */
14124 PyObject_SelfIter, /* tp_iter */
14125 (iternextfunc)unicodeiter_next, /* tp_iternext */
14126 unicodeiter_methods, /* tp_methods */
14127 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014128};
14129
14130static PyObject *
14131unicode_iter(PyObject *seq)
14132{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014133 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014134
Benjamin Peterson14339b62009-01-31 16:36:08 +000014135 if (!PyUnicode_Check(seq)) {
14136 PyErr_BadInternalCall();
14137 return NULL;
14138 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014139 if (PyUnicode_READY(seq) == -1)
14140 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014141 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14142 if (it == NULL)
14143 return NULL;
14144 it->it_index = 0;
14145 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014146 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014147 _PyObject_GC_TRACK(it);
14148 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014149}
14150
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014151
14152size_t
14153Py_UNICODE_strlen(const Py_UNICODE *u)
14154{
14155 int res = 0;
14156 while(*u++)
14157 res++;
14158 return res;
14159}
14160
14161Py_UNICODE*
14162Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14163{
14164 Py_UNICODE *u = s1;
14165 while ((*u++ = *s2++));
14166 return s1;
14167}
14168
14169Py_UNICODE*
14170Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14171{
14172 Py_UNICODE *u = s1;
14173 while ((*u++ = *s2++))
14174 if (n-- == 0)
14175 break;
14176 return s1;
14177}
14178
14179Py_UNICODE*
14180Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14181{
14182 Py_UNICODE *u1 = s1;
14183 u1 += Py_UNICODE_strlen(u1);
14184 Py_UNICODE_strcpy(u1, s2);
14185 return s1;
14186}
14187
14188int
14189Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14190{
14191 while (*s1 && *s2 && *s1 == *s2)
14192 s1++, s2++;
14193 if (*s1 && *s2)
14194 return (*s1 < *s2) ? -1 : +1;
14195 if (*s1)
14196 return 1;
14197 if (*s2)
14198 return -1;
14199 return 0;
14200}
14201
14202int
14203Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14204{
14205 register Py_UNICODE u1, u2;
14206 for (; n != 0; n--) {
14207 u1 = *s1;
14208 u2 = *s2;
14209 if (u1 != u2)
14210 return (u1 < u2) ? -1 : +1;
14211 if (u1 == '\0')
14212 return 0;
14213 s1++;
14214 s2++;
14215 }
14216 return 0;
14217}
14218
14219Py_UNICODE*
14220Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14221{
14222 const Py_UNICODE *p;
14223 for (p = s; *p; p++)
14224 if (*p == c)
14225 return (Py_UNICODE*)p;
14226 return NULL;
14227}
14228
14229Py_UNICODE*
14230Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14231{
14232 const Py_UNICODE *p;
14233 p = s + Py_UNICODE_strlen(s);
14234 while (p != s) {
14235 p--;
14236 if (*p == c)
14237 return (Py_UNICODE*)p;
14238 }
14239 return NULL;
14240}
Victor Stinner331ea922010-08-10 16:37:20 +000014241
Victor Stinner71133ff2010-09-01 23:43:53 +000014242Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014243PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014244{
Victor Stinner577db2c2011-10-11 22:12:48 +020014245 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014246 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014247
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014248 if (!PyUnicode_Check(unicode)) {
14249 PyErr_BadArgument();
14250 return NULL;
14251 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014252 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014253 if (u == NULL)
14254 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014255 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014256 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014257 PyErr_NoMemory();
14258 return NULL;
14259 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014260 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014261 size *= sizeof(Py_UNICODE);
14262 copy = PyMem_Malloc(size);
14263 if (copy == NULL) {
14264 PyErr_NoMemory();
14265 return NULL;
14266 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014267 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014268 return copy;
14269}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014270
Georg Brandl66c221e2010-10-14 07:04:07 +000014271/* A _string module, to export formatter_parser and formatter_field_name_split
14272 to the string.Formatter class implemented in Python. */
14273
14274static PyMethodDef _string_methods[] = {
14275 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14276 METH_O, PyDoc_STR("split the argument as a field name")},
14277 {"formatter_parser", (PyCFunction) formatter_parser,
14278 METH_O, PyDoc_STR("parse the argument as a format string")},
14279 {NULL, NULL}
14280};
14281
14282static struct PyModuleDef _string_module = {
14283 PyModuleDef_HEAD_INIT,
14284 "_string",
14285 PyDoc_STR("string helper module"),
14286 0,
14287 _string_methods,
14288 NULL,
14289 NULL,
14290 NULL,
14291 NULL
14292};
14293
14294PyMODINIT_FUNC
14295PyInit__string(void)
14296{
14297 return PyModule_Create(&_string_module);
14298}
14299
14300
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014301#ifdef __cplusplus
14302}
14303#endif