blob: 6798ef814523d16e23079396a641033b9eb17676 [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) {
Victor Stinner77faf692011-11-20 18:56:05 +0100395 if (ascii->state.ascii == 0) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200396 assert(maxchar >= 128);
Victor Stinner77faf692011-11-20 18:56:05 +0100397 assert(maxchar <= 255);
398 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200399 else
400 assert(maxchar < 128);
401 }
Victor Stinner77faf692011-11-20 18:56:05 +0100402 else if (kind == PyUnicode_2BYTE_KIND) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200403 assert(maxchar >= 0x100);
Victor Stinner77faf692011-11-20 18:56:05 +0100404 assert(maxchar <= 0xFFFF);
405 }
406 else {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200407 assert(maxchar >= 0x10000);
Victor Stinner77faf692011-11-20 18:56:05 +0100408 assert(maxchar <= 0x10FFFF);
409 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200410 }
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400411 return 1;
412}
Victor Stinner910337b2011-10-03 03:20:16 +0200413#endif
414
Victor Stinner3a50e702011-10-18 21:21:00 +0200415#ifdef HAVE_MBCS
416static OSVERSIONINFOEX winver;
417#endif
418
Thomas Wouters477c8d52006-05-27 19:21:47 +0000419/* --- Bloom Filters ----------------------------------------------------- */
420
421/* stuff to implement simple "bloom filters" for Unicode characters.
422 to keep things simple, we use a single bitmask, using the least 5
423 bits from each unicode characters as the bit index. */
424
425/* the linebreak mask is set up by Unicode_Init below */
426
Antoine Pitrouf068f942010-01-13 14:19:12 +0000427#if LONG_BIT >= 128
428#define BLOOM_WIDTH 128
429#elif LONG_BIT >= 64
430#define BLOOM_WIDTH 64
431#elif LONG_BIT >= 32
432#define BLOOM_WIDTH 32
433#else
434#error "LONG_BIT is smaller than 32"
435#endif
436
Thomas Wouters477c8d52006-05-27 19:21:47 +0000437#define BLOOM_MASK unsigned long
438
439static BLOOM_MASK bloom_linebreak;
440
Antoine Pitrouf068f942010-01-13 14:19:12 +0000441#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
442#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Benjamin Peterson29060642009-01-31 22:14:21 +0000444#define BLOOM_LINEBREAK(ch) \
445 ((ch) < 128U ? ascii_linebreak[(ch)] : \
446 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000447
Alexander Belopolsky40018472011-02-26 01:02:56 +0000448Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200449make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450{
451 /* calculate simple bloom-style bitmask for a given unicode string */
452
Antoine Pitrouf068f942010-01-13 14:19:12 +0000453 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 Py_ssize_t i;
455
456 mask = 0;
457 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200458 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000459
460 return mask;
461}
462
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200463#define BLOOM_MEMBER(mask, chr, str) \
464 (BLOOM(mask, chr) \
465 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000466
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200467/* Compilation of templated routines */
468
469#include "stringlib/asciilib.h"
470#include "stringlib/fastsearch.h"
471#include "stringlib/partition.h"
472#include "stringlib/split.h"
473#include "stringlib/count.h"
474#include "stringlib/find.h"
475#include "stringlib/find_max_char.h"
476#include "stringlib/localeutil.h"
477#include "stringlib/undef.h"
478
479#include "stringlib/ucs1lib.h"
480#include "stringlib/fastsearch.h"
481#include "stringlib/partition.h"
482#include "stringlib/split.h"
483#include "stringlib/count.h"
484#include "stringlib/find.h"
485#include "stringlib/find_max_char.h"
486#include "stringlib/localeutil.h"
487#include "stringlib/undef.h"
488
489#include "stringlib/ucs2lib.h"
490#include "stringlib/fastsearch.h"
491#include "stringlib/partition.h"
492#include "stringlib/split.h"
493#include "stringlib/count.h"
494#include "stringlib/find.h"
495#include "stringlib/find_max_char.h"
496#include "stringlib/localeutil.h"
497#include "stringlib/undef.h"
498
499#include "stringlib/ucs4lib.h"
500#include "stringlib/fastsearch.h"
501#include "stringlib/partition.h"
502#include "stringlib/split.h"
503#include "stringlib/count.h"
504#include "stringlib/find.h"
505#include "stringlib/find_max_char.h"
506#include "stringlib/localeutil.h"
507#include "stringlib/undef.h"
508
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200509#include "stringlib/unicodedefs.h"
510#include "stringlib/fastsearch.h"
511#include "stringlib/count.h"
512#include "stringlib/find.h"
513
Guido van Rossumd57fd912000-03-10 22:53:23 +0000514/* --- Unicode Object ----------------------------------------------------- */
515
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200516static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200517fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
520 Py_ssize_t size, Py_UCS4 ch,
521 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200522{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200523 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
524
525 switch (kind) {
526 case PyUnicode_1BYTE_KIND:
527 {
528 Py_UCS1 ch1 = (Py_UCS1) ch;
529 if (ch1 == ch)
530 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
531 else
532 return -1;
533 }
534 case PyUnicode_2BYTE_KIND:
535 {
536 Py_UCS2 ch2 = (Py_UCS2) ch;
537 if (ch2 == ch)
538 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
539 else
540 return -1;
541 }
542 case PyUnicode_4BYTE_KIND:
543 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
544 default:
545 assert(0);
546 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200547 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200548}
549
Victor Stinnerfe226c02011-10-03 03:52:20 +0200550static PyObject*
551resize_compact(PyObject *unicode, Py_ssize_t length)
552{
553 Py_ssize_t char_size;
554 Py_ssize_t struct_size;
555 Py_ssize_t new_size;
556 int share_wstr;
557
558 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200559 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200560 if (PyUnicode_IS_COMPACT_ASCII(unicode))
561 struct_size = sizeof(PyASCIIObject);
562 else
563 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200564 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200565
566 _Py_DEC_REFTOTAL;
567 _Py_ForgetReference(unicode);
568
569 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
570 PyErr_NoMemory();
571 return NULL;
572 }
573 new_size = (struct_size + (length + 1) * char_size);
574
575 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
576 if (unicode == NULL) {
577 PyObject_Del(unicode);
578 PyErr_NoMemory();
579 return NULL;
580 }
581 _Py_NewReference(unicode);
582 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200583 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200585 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
586 _PyUnicode_WSTR_LENGTH(unicode) = length;
587 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200588 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
589 length, 0);
590 return unicode;
591}
592
Alexander Belopolsky40018472011-02-26 01:02:56 +0000593static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200594resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000595{
Victor Stinner95663112011-10-04 01:03:50 +0200596 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200597 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200598 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000599
Victor Stinner95663112011-10-04 01:03:50 +0200600 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200601
602 if (PyUnicode_IS_READY(unicode)) {
603 Py_ssize_t char_size;
604 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200605 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200606 void *data;
607
608 data = _PyUnicode_DATA_ANY(unicode);
609 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200610 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200611 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
612 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200613 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
614 {
615 PyObject_DEL(_PyUnicode_UTF8(unicode));
616 _PyUnicode_UTF8(unicode) = NULL;
617 _PyUnicode_UTF8_LENGTH(unicode) = 0;
618 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200619
620 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
621 PyErr_NoMemory();
622 return -1;
623 }
624 new_size = (length + 1) * char_size;
625
626 data = (PyObject *)PyObject_REALLOC(data, new_size);
627 if (data == NULL) {
628 PyErr_NoMemory();
629 return -1;
630 }
631 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200632 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200633 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_WSTR_LENGTH(unicode) = length;
635 }
636 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200637 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200638 _PyUnicode_UTF8_LENGTH(unicode) = length;
639 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 _PyUnicode_LENGTH(unicode) = length;
641 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200642 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200643 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200644 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200645 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200646 }
Victor Stinner95663112011-10-04 01:03:50 +0200647 assert(_PyUnicode_WSTR(unicode) != NULL);
648
649 /* check for integer overflow */
650 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
651 PyErr_NoMemory();
652 return -1;
653 }
654 wstr = _PyUnicode_WSTR(unicode);
655 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
656 if (!wstr) {
657 PyErr_NoMemory();
658 return -1;
659 }
660 _PyUnicode_WSTR(unicode) = wstr;
661 _PyUnicode_WSTR(unicode)[length] = 0;
662 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200663 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000664 return 0;
665}
666
Victor Stinnerfe226c02011-10-03 03:52:20 +0200667static PyObject*
668resize_copy(PyObject *unicode, Py_ssize_t length)
669{
670 Py_ssize_t copy_length;
671 if (PyUnicode_IS_COMPACT(unicode)) {
672 PyObject *copy;
673 assert(PyUnicode_IS_READY(unicode));
674
675 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
676 if (copy == NULL)
677 return NULL;
678
679 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200680 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200682 }
683 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200684 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200685 assert(_PyUnicode_WSTR(unicode) != NULL);
686 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200687 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200688 if (w == NULL)
689 return NULL;
690 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
691 copy_length = Py_MIN(copy_length, length);
692 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
693 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200694 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200695 }
696}
697
Guido van Rossumd57fd912000-03-10 22:53:23 +0000698/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000699 Ux0000 terminated; some code (e.g. new_identifier)
700 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000701
702 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000703 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000704
705*/
706
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200707#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200708static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200709#endif
710
Alexander Belopolsky40018472011-02-26 01:02:56 +0000711static PyUnicodeObject *
712_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000713{
714 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200715 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000716
Thomas Wouters477c8d52006-05-27 19:21:47 +0000717 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000718 if (length == 0 && unicode_empty != NULL) {
719 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200720 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000721 }
722
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000723 /* Ensure we won't overflow the size. */
724 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
725 return (PyUnicodeObject *)PyErr_NoMemory();
726 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200727 if (length < 0) {
728 PyErr_SetString(PyExc_SystemError,
729 "Negative size passed to _PyUnicode_New");
730 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000731 }
732
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200733#ifdef Py_DEBUG
734 ++unicode_old_new_calls;
735#endif
736
737 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
738 if (unicode == NULL)
739 return NULL;
740 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
741 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
742 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000743 PyErr_NoMemory();
744 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000745 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200746
Jeremy Hyltond8082792003-09-16 19:41:39 +0000747 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000748 * the caller fails before initializing str -- unicode_resize()
749 * reads str[0], and the Keep-Alive optimization can keep memory
750 * allocated for str alive across a call to unicode_dealloc(unicode).
751 * We don't want unicode_resize to read uninitialized memory in
752 * that case.
753 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200754 _PyUnicode_WSTR(unicode)[0] = 0;
755 _PyUnicode_WSTR(unicode)[length] = 0;
756 _PyUnicode_WSTR_LENGTH(unicode) = length;
757 _PyUnicode_HASH(unicode) = -1;
758 _PyUnicode_STATE(unicode).interned = 0;
759 _PyUnicode_STATE(unicode).kind = 0;
760 _PyUnicode_STATE(unicode).compact = 0;
761 _PyUnicode_STATE(unicode).ready = 0;
762 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200763 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200764 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200765 _PyUnicode_UTF8(unicode) = NULL;
766 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100767 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000768 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769
Benjamin Peterson29060642009-01-31 22:14:21 +0000770 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000771 /* XXX UNREF/NEWREF interface should be more symmetrical */
772 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000773 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000774 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000776}
777
Victor Stinnerf42dc442011-10-02 23:33:16 +0200778static const char*
779unicode_kind_name(PyObject *unicode)
780{
Victor Stinner42dfd712011-10-03 14:41:45 +0200781 /* don't check consistency: unicode_kind_name() is called from
782 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200783 if (!PyUnicode_IS_COMPACT(unicode))
784 {
785 if (!PyUnicode_IS_READY(unicode))
786 return "wstr";
787 switch(PyUnicode_KIND(unicode))
788 {
789 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200790 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200791 return "legacy ascii";
792 else
793 return "legacy latin1";
794 case PyUnicode_2BYTE_KIND:
795 return "legacy UCS2";
796 case PyUnicode_4BYTE_KIND:
797 return "legacy UCS4";
798 default:
799 return "<legacy invalid kind>";
800 }
801 }
802 assert(PyUnicode_IS_READY(unicode));
803 switch(PyUnicode_KIND(unicode))
804 {
805 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200806 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200807 return "ascii";
808 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200811 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200812 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200813 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200814 default:
815 return "<invalid compact kind>";
816 }
817}
818
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200819#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200820static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821
822/* Functions wrapping macros for use in debugger */
823char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200824 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200825}
826
827void *_PyUnicode_compact_data(void *unicode) {
828 return _PyUnicode_COMPACT_DATA(unicode);
829}
830void *_PyUnicode_data(void *unicode){
831 printf("obj %p\n", unicode);
832 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
833 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
834 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
835 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
836 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
837 return PyUnicode_DATA(unicode);
838}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200839
840void
841_PyUnicode_Dump(PyObject *op)
842{
843 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
845 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
846 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200847
Victor Stinnera849a4b2011-10-03 12:12:11 +0200848 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200849 {
850 if (ascii->state.ascii)
851 data = (ascii + 1);
852 else
853 data = (compact + 1);
854 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 else
856 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200857 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
858
Victor Stinnera849a4b2011-10-03 12:12:11 +0200859 if (ascii->wstr == data)
860 printf("shared ");
861 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200862
Victor Stinnera3b334d2011-10-03 13:53:37 +0200863 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200864 printf(" (%zu), ", compact->wstr_length);
865 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
866 printf("shared ");
867 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200868 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200869 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200870}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200871#endif
872
873PyObject *
874PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
875{
876 PyObject *obj;
877 PyCompactUnicodeObject *unicode;
878 void *data;
879 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200880 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200881 Py_ssize_t char_size;
882 Py_ssize_t struct_size;
883
884 /* Optimization for empty strings */
885 if (size == 0 && unicode_empty != NULL) {
886 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200887 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200888 }
889
890#ifdef Py_DEBUG
891 ++unicode_new_new_calls;
892#endif
893
Victor Stinner9e9d6892011-10-04 01:02:02 +0200894 is_ascii = 0;
895 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200896 struct_size = sizeof(PyCompactUnicodeObject);
897 if (maxchar < 128) {
898 kind_state = PyUnicode_1BYTE_KIND;
899 char_size = 1;
900 is_ascii = 1;
901 struct_size = sizeof(PyASCIIObject);
902 }
903 else if (maxchar < 256) {
904 kind_state = PyUnicode_1BYTE_KIND;
905 char_size = 1;
906 }
907 else if (maxchar < 65536) {
908 kind_state = PyUnicode_2BYTE_KIND;
909 char_size = 2;
910 if (sizeof(wchar_t) == 2)
911 is_sharing = 1;
912 }
913 else {
914 kind_state = PyUnicode_4BYTE_KIND;
915 char_size = 4;
916 if (sizeof(wchar_t) == 4)
917 is_sharing = 1;
918 }
919
920 /* Ensure we won't overflow the size. */
921 if (size < 0) {
922 PyErr_SetString(PyExc_SystemError,
923 "Negative size passed to PyUnicode_New");
924 return NULL;
925 }
926 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
927 return PyErr_NoMemory();
928
929 /* Duplicated allocation code from _PyObject_New() instead of a call to
930 * PyObject_New() so we are able to allocate space for the object and
931 * it's data buffer.
932 */
933 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
934 if (obj == NULL)
935 return PyErr_NoMemory();
936 obj = PyObject_INIT(obj, &PyUnicode_Type);
937 if (obj == NULL)
938 return NULL;
939
940 unicode = (PyCompactUnicodeObject *)obj;
941 if (is_ascii)
942 data = ((PyASCIIObject*)obj) + 1;
943 else
944 data = unicode + 1;
945 _PyUnicode_LENGTH(unicode) = size;
946 _PyUnicode_HASH(unicode) = -1;
947 _PyUnicode_STATE(unicode).interned = 0;
948 _PyUnicode_STATE(unicode).kind = kind_state;
949 _PyUnicode_STATE(unicode).compact = 1;
950 _PyUnicode_STATE(unicode).ready = 1;
951 _PyUnicode_STATE(unicode).ascii = is_ascii;
952 if (is_ascii) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 }
956 else if (kind_state == PyUnicode_1BYTE_KIND) {
957 ((char*)data)[size] = 0;
958 _PyUnicode_WSTR(unicode) = NULL;
959 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 }
963 else {
964 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200965 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200966 if (kind_state == PyUnicode_2BYTE_KIND)
967 ((Py_UCS2*)data)[size] = 0;
968 else /* kind_state == PyUnicode_4BYTE_KIND */
969 ((Py_UCS4*)data)[size] = 0;
970 if (is_sharing) {
971 _PyUnicode_WSTR_LENGTH(unicode) = size;
972 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
973 }
974 else {
975 _PyUnicode_WSTR_LENGTH(unicode) = 0;
976 _PyUnicode_WSTR(unicode) = NULL;
977 }
978 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100979 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200980 return obj;
981}
982
983#if SIZEOF_WCHAR_T == 2
984/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
985 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200986 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987
988 This function assumes that unicode can hold one more code point than wstr
989 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200990static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200991unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200992 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200993{
994 const wchar_t *iter;
995 Py_UCS4 *ucs4_out;
996
Victor Stinner910337b2011-10-03 03:20:16 +0200997 assert(unicode != NULL);
998 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200999 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
1000 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
1001
1002 for (iter = begin; iter < end; ) {
1003 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1004 _PyUnicode_GET_LENGTH(unicode)));
1005 if (*iter >= 0xD800 && *iter <= 0xDBFF
1006 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1007 {
1008 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1009 iter += 2;
1010 }
1011 else {
1012 *ucs4_out++ = *iter;
1013 iter++;
1014 }
1015 }
1016 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1017 _PyUnicode_GET_LENGTH(unicode)));
1018
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001019}
1020#endif
1021
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022static int
1023_PyUnicode_Dirty(PyObject *unicode)
1024{
Victor Stinner910337b2011-10-03 03:20:16 +02001025 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001026 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001027 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001028 "Cannot modify a string having more than 1 reference");
1029 return -1;
1030 }
1031 _PyUnicode_DIRTY(unicode);
1032 return 0;
1033}
1034
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001035static int
1036_copy_characters(PyObject *to, Py_ssize_t to_start,
1037 PyObject *from, Py_ssize_t from_start,
1038 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001040 unsigned int from_kind, to_kind;
1041 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001042 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001043
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001044 assert(PyUnicode_Check(from));
1045 assert(PyUnicode_Check(to));
1046 assert(PyUnicode_IS_READY(from));
1047 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001049 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1050 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1051 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001053 if (how_many == 0)
1054 return 0;
1055
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001057 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001058 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001059 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001060
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001061#ifdef Py_DEBUG
1062 if (!check_maxchar
1063 && (from_kind > to_kind
1064 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001065 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001066 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1067 Py_UCS4 ch;
1068 Py_ssize_t i;
1069 for (i=0; i < how_many; i++) {
1070 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1071 assert(ch <= to_maxchar);
1072 }
1073 }
1074#endif
1075 fast = (from_kind == to_kind);
1076 if (check_maxchar
1077 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1078 {
1079 /* deny latin1 => ascii */
1080 fast = 0;
1081 }
1082
1083 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001084 Py_MEMCPY((char*)to_data + to_kind * to_start,
1085 (char*)from_data + from_kind * from_start,
1086 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001087 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001088 else if (from_kind == PyUnicode_1BYTE_KIND
1089 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001090 {
1091 _PyUnicode_CONVERT_BYTES(
1092 Py_UCS1, Py_UCS2,
1093 PyUnicode_1BYTE_DATA(from) + from_start,
1094 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1095 PyUnicode_2BYTE_DATA(to) + to_start
1096 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001097 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001098 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001099 && to_kind == PyUnicode_4BYTE_KIND)
1100 {
1101 _PyUnicode_CONVERT_BYTES(
1102 Py_UCS1, Py_UCS4,
1103 PyUnicode_1BYTE_DATA(from) + from_start,
1104 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1105 PyUnicode_4BYTE_DATA(to) + to_start
1106 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001107 }
1108 else if (from_kind == PyUnicode_2BYTE_KIND
1109 && to_kind == PyUnicode_4BYTE_KIND)
1110 {
1111 _PyUnicode_CONVERT_BYTES(
1112 Py_UCS2, Py_UCS4,
1113 PyUnicode_2BYTE_DATA(from) + from_start,
1114 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1115 PyUnicode_4BYTE_DATA(to) + to_start
1116 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001117 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001118 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 /* check if max_char(from substring) <= max_char(to) */
1120 if (from_kind > to_kind
1121 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001122 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001123 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001124 /* slow path to check for character overflow */
1125 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001126 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001127 Py_ssize_t i;
1128
Victor Stinner56c161a2011-10-06 02:47:11 +02001129#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001130 for (i=0; i < how_many; i++) {
1131 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001132 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001133 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1134 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001135#else
1136 if (!check_maxchar) {
1137 for (i=0; i < how_many; i++) {
1138 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1139 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1140 }
1141 }
1142 else {
1143 for (i=0; i < how_many; i++) {
1144 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1145 if (ch > to_maxchar)
1146 return 1;
1147 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1148 }
1149 }
1150#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001152 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001153 assert(0 && "inconsistent state");
1154 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001155 }
1156 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001157 return 0;
1158}
1159
1160static void
1161copy_characters(PyObject *to, Py_ssize_t to_start,
1162 PyObject *from, Py_ssize_t from_start,
1163 Py_ssize_t how_many)
1164{
1165 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1166}
1167
1168Py_ssize_t
1169PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1170 PyObject *from, Py_ssize_t from_start,
1171 Py_ssize_t how_many)
1172{
1173 int err;
1174
1175 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1176 PyErr_BadInternalCall();
1177 return -1;
1178 }
1179
1180 if (PyUnicode_READY(from))
1181 return -1;
1182 if (PyUnicode_READY(to))
1183 return -1;
1184
1185 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1186 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1187 PyErr_Format(PyExc_SystemError,
1188 "Cannot write %zi characters at %zi "
1189 "in a string of %zi characters",
1190 how_many, to_start, PyUnicode_GET_LENGTH(to));
1191 return -1;
1192 }
1193
1194 if (how_many == 0)
1195 return 0;
1196
1197 if (_PyUnicode_Dirty(to))
1198 return -1;
1199
1200 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1201 if (err) {
1202 PyErr_Format(PyExc_SystemError,
1203 "Cannot copy %s characters "
1204 "into a string of %s characters",
1205 unicode_kind_name(from),
1206 unicode_kind_name(to));
1207 return -1;
1208 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001209 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001210}
1211
Victor Stinner17222162011-09-28 22:15:37 +02001212/* Find the maximum code point and count the number of surrogate pairs so a
1213 correct string length can be computed before converting a string to UCS4.
1214 This function counts single surrogates as a character and not as a pair.
1215
1216 Return 0 on success, or -1 on error. */
1217static int
1218find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1219 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220{
1221 const wchar_t *iter;
1222
Victor Stinnerc53be962011-10-02 21:33:54 +02001223 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001224 *num_surrogates = 0;
1225 *maxchar = 0;
1226
1227 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001228 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001229 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001230#if SIZEOF_WCHAR_T != 2
1231 if (*maxchar >= 0x10000)
1232 return 0;
1233#endif
1234 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001235#if SIZEOF_WCHAR_T == 2
1236 if (*iter >= 0xD800 && *iter <= 0xDBFF
1237 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1238 {
1239 Py_UCS4 surrogate_val;
1240 surrogate_val = (((iter[0] & 0x3FF)<<10)
1241 | (iter[1] & 0x3FF)) + 0x10000;
1242 ++(*num_surrogates);
1243 if (surrogate_val > *maxchar)
1244 *maxchar = surrogate_val;
1245 iter += 2;
1246 }
1247 else
1248 iter++;
1249#else
1250 iter++;
1251#endif
1252 }
1253 return 0;
1254}
1255
1256#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001257static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258#endif
1259
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001260static int
1261unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001262{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001263 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001264 wchar_t *end;
1265 Py_UCS4 maxchar = 0;
1266 Py_ssize_t num_surrogates;
1267#if SIZEOF_WCHAR_T == 2
1268 Py_ssize_t length_wo_surrogates;
1269#endif
1270
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001271 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001272 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001273
Georg Brandl7597add2011-10-05 16:36:47 +02001274 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001275 strings were created using _PyObject_New() and where no canonical
1276 representation (the str field) has been set yet aka strings
1277 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001278 assert(_PyUnicode_CHECK(unicode));
1279 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001280 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001281 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001282 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001283 /* Actually, it should neither be interned nor be anything else: */
1284 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001285
1286#ifdef Py_DEBUG
1287 ++unicode_ready_calls;
1288#endif
1289
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001290#ifdef Py_DEBUG
1291 assert(!replace || Py_REFCNT(unicode) == 1);
1292#else
1293 if (replace && Py_REFCNT(unicode) != 1)
1294 replace = 0;
1295#endif
1296 if (replace) {
1297 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1298 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1299 /* Optimization for empty strings */
1300 if (len == 0) {
1301 Py_INCREF(unicode_empty);
1302 Py_DECREF(*p_obj);
1303 *p_obj = unicode_empty;
1304 return 0;
1305 }
1306 if (len == 1 && wstr[0] < 256) {
1307 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1308 if (latin1_char == NULL)
1309 return -1;
1310 Py_DECREF(*p_obj);
1311 *p_obj = latin1_char;
1312 return 0;
1313 }
1314 }
1315
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001317 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001318 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001319 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320
1321 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001322 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1323 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 PyErr_NoMemory();
1325 return -1;
1326 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001327 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001328 _PyUnicode_WSTR(unicode), end,
1329 PyUnicode_1BYTE_DATA(unicode));
1330 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1331 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1332 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1333 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001334 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001335 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001337 }
1338 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001339 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001340 _PyUnicode_UTF8(unicode) = NULL;
1341 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001342 }
1343 PyObject_FREE(_PyUnicode_WSTR(unicode));
1344 _PyUnicode_WSTR(unicode) = NULL;
1345 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1346 }
1347 /* In this case we might have to convert down from 4-byte native
1348 wchar_t to 2-byte unicode. */
1349 else if (maxchar < 65536) {
1350 assert(num_surrogates == 0 &&
1351 "FindMaxCharAndNumSurrogatePairs() messed up");
1352
Victor Stinner506f5922011-09-28 22:34:18 +02001353#if SIZEOF_WCHAR_T == 2
1354 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001355 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001356 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1357 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1358 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001359 _PyUnicode_UTF8(unicode) = NULL;
1360 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001361#else
1362 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001363 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001364 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001365 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001366 PyErr_NoMemory();
1367 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001368 }
Victor Stinner506f5922011-09-28 22:34:18 +02001369 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1370 _PyUnicode_WSTR(unicode), end,
1371 PyUnicode_2BYTE_DATA(unicode));
1372 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1373 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1374 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001375 _PyUnicode_UTF8(unicode) = NULL;
1376 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001377 PyObject_FREE(_PyUnicode_WSTR(unicode));
1378 _PyUnicode_WSTR(unicode) = NULL;
1379 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1380#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001381 }
1382 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1383 else {
1384#if SIZEOF_WCHAR_T == 2
1385 /* in case the native representation is 2-bytes, we need to allocate a
1386 new normalized 4-byte version. */
1387 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001388 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1389 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001390 PyErr_NoMemory();
1391 return -1;
1392 }
1393 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1394 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001395 _PyUnicode_UTF8(unicode) = NULL;
1396 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001397 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1398 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001399 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001400 PyObject_FREE(_PyUnicode_WSTR(unicode));
1401 _PyUnicode_WSTR(unicode) = NULL;
1402 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1403#else
1404 assert(num_surrogates == 0);
1405
Victor Stinnerc3c74152011-10-02 20:39:55 +02001406 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001407 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001408 _PyUnicode_UTF8(unicode) = NULL;
1409 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001410 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1411#endif
1412 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1413 }
1414 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001415 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001416 return 0;
1417}
1418
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001419int
1420_PyUnicode_ReadyReplace(PyObject **op)
1421{
1422 return unicode_ready(op, 1);
1423}
1424
1425int
1426_PyUnicode_Ready(PyObject *op)
1427{
1428 return unicode_ready(&op, 0);
1429}
1430
Alexander Belopolsky40018472011-02-26 01:02:56 +00001431static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001432unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001433{
Walter Dörwald16807132007-05-25 13:52:07 +00001434 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001435 case SSTATE_NOT_INTERNED:
1436 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001437
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 case SSTATE_INTERNED_MORTAL:
1439 /* revive dead object temporarily for DelItem */
1440 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001441 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 Py_FatalError(
1443 "deletion of interned string failed");
1444 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001445
Benjamin Peterson29060642009-01-31 22:14:21 +00001446 case SSTATE_INTERNED_IMMORTAL:
1447 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001448
Benjamin Peterson29060642009-01-31 22:14:21 +00001449 default:
1450 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001451 }
1452
Victor Stinner03490912011-10-03 23:45:12 +02001453 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001454 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001455 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001456 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001457
1458 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001459 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001460 }
1461 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001462 if (_PyUnicode_DATA_ANY(unicode))
1463 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001464 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001465 }
1466}
1467
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001468#ifdef Py_DEBUG
1469static int
1470unicode_is_singleton(PyObject *unicode)
1471{
1472 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1473 if (unicode == unicode_empty)
1474 return 1;
1475 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1476 {
1477 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1478 if (ch < 256 && unicode_latin1[ch] == unicode)
1479 return 1;
1480 }
1481 return 0;
1482}
1483#endif
1484
Alexander Belopolsky40018472011-02-26 01:02:56 +00001485static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001486unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001487{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001488 if (Py_REFCNT(unicode) != 1)
1489 return 0;
1490 if (PyUnicode_CHECK_INTERNED(unicode))
1491 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001492#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001493 /* singleton refcount is greater than 1 */
1494 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001495#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001496 return 1;
1497}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001498
Victor Stinnerfe226c02011-10-03 03:52:20 +02001499static int
1500unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1501{
1502 PyObject *unicode;
1503 Py_ssize_t old_length;
1504
1505 assert(p_unicode != NULL);
1506 unicode = *p_unicode;
1507
1508 assert(unicode != NULL);
1509 assert(PyUnicode_Check(unicode));
1510 assert(0 <= length);
1511
Victor Stinner910337b2011-10-03 03:20:16 +02001512 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001513 old_length = PyUnicode_WSTR_LENGTH(unicode);
1514 else
1515 old_length = PyUnicode_GET_LENGTH(unicode);
1516 if (old_length == length)
1517 return 0;
1518
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001519 if (length == 0) {
1520 Py_DECREF(*p_unicode);
1521 *p_unicode = unicode_empty;
1522 Py_INCREF(*p_unicode);
1523 return 0;
1524 }
1525
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 if (!unicode_resizable(unicode)) {
1527 PyObject *copy = resize_copy(unicode, length);
1528 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001529 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001530 Py_DECREF(*p_unicode);
1531 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001532 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001533 }
1534
Victor Stinnerfe226c02011-10-03 03:52:20 +02001535 if (PyUnicode_IS_COMPACT(unicode)) {
1536 *p_unicode = resize_compact(unicode, length);
1537 if (*p_unicode == NULL)
1538 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001539 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001540 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001541 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001542 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001543}
1544
Alexander Belopolsky40018472011-02-26 01:02:56 +00001545int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001546PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001547{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001548 PyObject *unicode;
1549 if (p_unicode == NULL) {
1550 PyErr_BadInternalCall();
1551 return -1;
1552 }
1553 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001554 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001555 {
1556 PyErr_BadInternalCall();
1557 return -1;
1558 }
1559 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001560}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001561
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001562static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001563unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001564{
1565 PyObject *result;
1566 assert(PyUnicode_IS_READY(*p_unicode));
1567 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1568 return 0;
1569 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1570 maxchar);
1571 if (result == NULL)
1572 return -1;
1573 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1574 PyUnicode_GET_LENGTH(*p_unicode));
1575 Py_DECREF(*p_unicode);
1576 *p_unicode = result;
1577 return 0;
1578}
1579
1580static int
1581unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1582 Py_UCS4 ch)
1583{
1584 if (unicode_widen(p_unicode, ch) < 0)
1585 return -1;
1586 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1587 PyUnicode_DATA(*p_unicode),
1588 (*pos)++, ch);
1589 return 0;
1590}
1591
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592static PyObject*
1593get_latin1_char(unsigned char ch)
1594{
Victor Stinnera464fc12011-10-02 20:39:30 +02001595 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001596 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001597 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 if (!unicode)
1599 return NULL;
1600 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001601 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602 unicode_latin1[ch] = unicode;
1603 }
1604 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001605 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001606}
1607
Alexander Belopolsky40018472011-02-26 01:02:56 +00001608PyObject *
1609PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001610{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001611 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001612 Py_UCS4 maxchar = 0;
1613 Py_ssize_t num_surrogates;
1614
1615 if (u == NULL)
1616 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001617
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001618 /* If the Unicode data is known at construction time, we can apply
1619 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001620
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001621 /* Optimization for empty strings */
1622 if (size == 0 && unicode_empty != NULL) {
1623 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001624 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001625 }
Tim Petersced69f82003-09-16 20:30:58 +00001626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001627 /* Single character Unicode objects in the Latin-1 range are
1628 shared when using this constructor */
1629 if (size == 1 && *u < 256)
1630 return get_latin1_char((unsigned char)*u);
1631
1632 /* If not empty and not single character, copy the Unicode data
1633 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001634 if (find_maxchar_surrogates(u, u + size,
1635 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001636 return NULL;
1637
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001638 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001640 if (!unicode)
1641 return NULL;
1642
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001643 switch (PyUnicode_KIND(unicode)) {
1644 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001645 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001646 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1647 break;
1648 case PyUnicode_2BYTE_KIND:
1649#if Py_UNICODE_SIZE == 2
1650 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1651#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001652 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001653 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1654#endif
1655 break;
1656 case PyUnicode_4BYTE_KIND:
1657#if SIZEOF_WCHAR_T == 2
1658 /* This is the only case which has to process surrogates, thus
1659 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001660 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001661#else
1662 assert(num_surrogates == 0);
1663 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1664#endif
1665 break;
1666 default:
1667 assert(0 && "Impossible state");
1668 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001669
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001670 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001671 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001672}
1673
Alexander Belopolsky40018472011-02-26 01:02:56 +00001674PyObject *
1675PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001676{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001677 if (size < 0) {
1678 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001679 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001680 return NULL;
1681 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001682
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001684 some optimizations which share commonly used objects.
1685 Also, this means the input must be UTF-8, so fall back to the
1686 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001687 if (u != NULL) {
1688
Benjamin Peterson29060642009-01-31 22:14:21 +00001689 /* Optimization for empty strings */
1690 if (size == 0 && unicode_empty != NULL) {
1691 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001692 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001693 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001694
1695 /* Single characters are shared when using this constructor.
1696 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001697 if (size == 1 && (unsigned char)*u < 128)
1698 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001699
1700 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001701 }
1702
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001703 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001704}
1705
Alexander Belopolsky40018472011-02-26 01:02:56 +00001706PyObject *
1707PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001708{
1709 size_t size = strlen(u);
1710 if (size > PY_SSIZE_T_MAX) {
1711 PyErr_SetString(PyExc_OverflowError, "input too long");
1712 return NULL;
1713 }
1714
1715 return PyUnicode_FromStringAndSize(u, size);
1716}
1717
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001718PyObject *
1719_PyUnicode_FromId(_Py_Identifier *id)
1720{
1721 if (!id->object) {
1722 id->object = PyUnicode_FromString(id->string);
1723 if (!id->object)
1724 return NULL;
1725 PyUnicode_InternInPlace(&id->object);
1726 assert(!id->next);
1727 id->next = static_strings;
1728 static_strings = id;
1729 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001730 return id->object;
1731}
1732
1733void
1734_PyUnicode_ClearStaticStrings()
1735{
1736 _Py_Identifier *i;
1737 for (i = static_strings; i; i = i->next) {
1738 Py_DECREF(i->object);
1739 i->object = NULL;
1740 i->next = NULL;
1741 }
1742}
1743
Victor Stinnere57b1c02011-09-28 22:20:48 +02001744static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001745unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001746{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001747 PyObject *res;
1748#ifdef Py_DEBUG
1749 const unsigned char *p;
1750 const unsigned char *end = s + size;
1751 for (p=s; p < end; p++) {
1752 assert(*p < 128);
1753 }
1754#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001755 if (size == 1)
1756 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001757 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001758 if (!res)
1759 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001760 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001761 return res;
1762}
1763
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001764static Py_UCS4
1765kind_maxchar_limit(unsigned int kind)
1766{
1767 switch(kind) {
1768 case PyUnicode_1BYTE_KIND:
1769 return 0x80;
1770 case PyUnicode_2BYTE_KIND:
1771 return 0x100;
1772 case PyUnicode_4BYTE_KIND:
1773 return 0x10000;
1774 default:
1775 assert(0 && "invalid kind");
1776 return 0x10ffff;
1777 }
1778}
1779
Victor Stinner702c7342011-10-05 13:50:52 +02001780static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001781_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001782{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001783 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001784 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001785
1786 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001787 if (size == 1)
1788 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001789 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001790 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 if (!res)
1792 return NULL;
1793 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001794 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001795 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001796}
1797
Victor Stinnere57b1c02011-09-28 22:20:48 +02001798static PyObject*
1799_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001800{
1801 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001802 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001803
1804 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001805 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001806 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001807 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001808 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 if (!res)
1810 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001811 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001812 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001813 else {
1814 _PyUnicode_CONVERT_BYTES(
1815 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1816 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001817 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001818 return res;
1819}
1820
Victor Stinnere57b1c02011-09-28 22:20:48 +02001821static PyObject*
1822_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001823{
1824 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001825 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001826
1827 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001828 if (size == 1 && u[0] < 256)
1829 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001830 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001831 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001832 if (!res)
1833 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001834 if (max_char < 256)
1835 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1836 PyUnicode_1BYTE_DATA(res));
1837 else if (max_char < 0x10000)
1838 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1839 PyUnicode_2BYTE_DATA(res));
1840 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001841 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001842 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001843 return res;
1844}
1845
1846PyObject*
1847PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1848{
1849 switch(kind) {
1850 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001851 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001852 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001853 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001854 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001855 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001856 default:
1857 assert(0 && "invalid kind");
1858 PyErr_SetString(PyExc_SystemError, "invalid kind");
1859 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001860 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001861}
1862
Victor Stinner25a4b292011-10-06 12:31:55 +02001863/* Ensure that a string uses the most efficient storage, if it is not the
1864 case: create a new string with of the right kind. Write NULL into *p_unicode
1865 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001866static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001867unicode_adjust_maxchar(PyObject **p_unicode)
1868{
1869 PyObject *unicode, *copy;
1870 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001871 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001872 unsigned int kind;
1873
1874 assert(p_unicode != NULL);
1875 unicode = *p_unicode;
1876 assert(PyUnicode_IS_READY(unicode));
1877 if (PyUnicode_IS_ASCII(unicode))
1878 return;
1879
1880 len = PyUnicode_GET_LENGTH(unicode);
1881 kind = PyUnicode_KIND(unicode);
1882 if (kind == PyUnicode_1BYTE_KIND) {
1883 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001884 max_char = ucs1lib_find_max_char(u, u + len);
1885 if (max_char >= 128)
1886 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001887 }
1888 else if (kind == PyUnicode_2BYTE_KIND) {
1889 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001890 max_char = ucs2lib_find_max_char(u, u + len);
1891 if (max_char >= 256)
1892 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001893 }
1894 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001895 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001896 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001897 max_char = ucs4lib_find_max_char(u, u + len);
1898 if (max_char >= 0x10000)
1899 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001900 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001901 copy = PyUnicode_New(len, max_char);
1902 copy_characters(copy, 0, unicode, 0, len);
1903 Py_DECREF(unicode);
1904 *p_unicode = copy;
1905}
1906
Victor Stinner034f6cf2011-09-30 02:26:44 +02001907PyObject*
1908PyUnicode_Copy(PyObject *unicode)
1909{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001910 Py_ssize_t size;
1911 PyObject *copy;
1912 void *data;
1913
Victor Stinner034f6cf2011-09-30 02:26:44 +02001914 if (!PyUnicode_Check(unicode)) {
1915 PyErr_BadInternalCall();
1916 return NULL;
1917 }
1918 if (PyUnicode_READY(unicode))
1919 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001920
1921 size = PyUnicode_GET_LENGTH(unicode);
1922 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1923 if (!copy)
1924 return NULL;
1925 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1926
1927 data = PyUnicode_DATA(unicode);
1928 switch (PyUnicode_KIND(unicode))
1929 {
1930 case PyUnicode_1BYTE_KIND:
1931 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1932 break;
1933 case PyUnicode_2BYTE_KIND:
1934 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1935 break;
1936 case PyUnicode_4BYTE_KIND:
1937 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1938 break;
1939 default:
1940 assert(0);
1941 break;
1942 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001943 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001944 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001945}
1946
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947
Victor Stinnerbc603d12011-10-02 01:00:40 +02001948/* Widen Unicode objects to larger buffers. Don't write terminating null
1949 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001950
1951void*
1952_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1953{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001954 Py_ssize_t len;
1955 void *result;
1956 unsigned int skind;
1957
1958 if (PyUnicode_READY(s))
1959 return NULL;
1960
1961 len = PyUnicode_GET_LENGTH(s);
1962 skind = PyUnicode_KIND(s);
1963 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001964 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001965 return NULL;
1966 }
1967 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001968 case PyUnicode_2BYTE_KIND:
1969 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1970 if (!result)
1971 return PyErr_NoMemory();
1972 assert(skind == PyUnicode_1BYTE_KIND);
1973 _PyUnicode_CONVERT_BYTES(
1974 Py_UCS1, Py_UCS2,
1975 PyUnicode_1BYTE_DATA(s),
1976 PyUnicode_1BYTE_DATA(s) + len,
1977 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001978 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001979 case PyUnicode_4BYTE_KIND:
1980 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1981 if (!result)
1982 return PyErr_NoMemory();
1983 if (skind == PyUnicode_2BYTE_KIND) {
1984 _PyUnicode_CONVERT_BYTES(
1985 Py_UCS2, Py_UCS4,
1986 PyUnicode_2BYTE_DATA(s),
1987 PyUnicode_2BYTE_DATA(s) + len,
1988 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001989 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001990 else {
1991 assert(skind == PyUnicode_1BYTE_KIND);
1992 _PyUnicode_CONVERT_BYTES(
1993 Py_UCS1, Py_UCS4,
1994 PyUnicode_1BYTE_DATA(s),
1995 PyUnicode_1BYTE_DATA(s) + len,
1996 result);
1997 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001999 default:
2000 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002001 }
Victor Stinner01698042011-10-04 00:04:26 +02002002 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002003 return NULL;
2004}
2005
2006static Py_UCS4*
2007as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2008 int copy_null)
2009{
2010 int kind;
2011 void *data;
2012 Py_ssize_t len, targetlen;
2013 if (PyUnicode_READY(string) == -1)
2014 return NULL;
2015 kind = PyUnicode_KIND(string);
2016 data = PyUnicode_DATA(string);
2017 len = PyUnicode_GET_LENGTH(string);
2018 targetlen = len;
2019 if (copy_null)
2020 targetlen++;
2021 if (!target) {
2022 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2023 PyErr_NoMemory();
2024 return NULL;
2025 }
2026 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2027 if (!target) {
2028 PyErr_NoMemory();
2029 return NULL;
2030 }
2031 }
2032 else {
2033 if (targetsize < targetlen) {
2034 PyErr_Format(PyExc_SystemError,
2035 "string is longer than the buffer");
2036 if (copy_null && 0 < targetsize)
2037 target[0] = 0;
2038 return NULL;
2039 }
2040 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002041 if (kind == PyUnicode_1BYTE_KIND) {
2042 Py_UCS1 *start = (Py_UCS1 *) data;
2043 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002044 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002045 else if (kind == PyUnicode_2BYTE_KIND) {
2046 Py_UCS2 *start = (Py_UCS2 *) data;
2047 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2048 }
2049 else {
2050 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002051 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002052 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002053 if (copy_null)
2054 target[len] = 0;
2055 return target;
2056}
2057
2058Py_UCS4*
2059PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2060 int copy_null)
2061{
Antoine Pitroude20b0b2011-11-10 21:47:38 +01002062 if (target == NULL || targetsize < 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002063 PyErr_BadInternalCall();
2064 return NULL;
2065 }
2066 return as_ucs4(string, target, targetsize, copy_null);
2067}
2068
2069Py_UCS4*
2070PyUnicode_AsUCS4Copy(PyObject *string)
2071{
2072 return as_ucs4(string, NULL, 0, 1);
2073}
2074
2075#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002076
Alexander Belopolsky40018472011-02-26 01:02:56 +00002077PyObject *
2078PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002079{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002080 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002081 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002082 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002083 PyErr_BadInternalCall();
2084 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002085 }
2086
Martin v. Löwis790465f2008-04-05 20:41:37 +00002087 if (size == -1) {
2088 size = wcslen(w);
2089 }
2090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002092}
2093
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002094#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002095
Walter Dörwald346737f2007-05-31 10:44:43 +00002096static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002097makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2098 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002099{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002100 *fmt++ = '%';
2101 if (width) {
2102 if (zeropad)
2103 *fmt++ = '0';
2104 fmt += sprintf(fmt, "%d", width);
2105 }
2106 if (precision)
2107 fmt += sprintf(fmt, ".%d", precision);
2108 if (longflag)
2109 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002110 else if (longlongflag) {
2111 /* longlongflag should only ever be nonzero on machines with
2112 HAVE_LONG_LONG defined */
2113#ifdef HAVE_LONG_LONG
2114 char *f = PY_FORMAT_LONG_LONG;
2115 while (*f)
2116 *fmt++ = *f++;
2117#else
2118 /* we shouldn't ever get here */
2119 assert(0);
2120 *fmt++ = 'l';
2121#endif
2122 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002123 else if (size_tflag) {
2124 char *f = PY_FORMAT_SIZE_T;
2125 while (*f)
2126 *fmt++ = *f++;
2127 }
2128 *fmt++ = c;
2129 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002130}
2131
Victor Stinner96865452011-03-01 23:44:09 +00002132/* helper for PyUnicode_FromFormatV() */
2133
2134static const char*
2135parse_format_flags(const char *f,
2136 int *p_width, int *p_precision,
2137 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2138{
2139 int width, precision, longflag, longlongflag, size_tflag;
2140
2141 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2142 f++;
2143 width = 0;
2144 while (Py_ISDIGIT((unsigned)*f))
2145 width = (width*10) + *f++ - '0';
2146 precision = 0;
2147 if (*f == '.') {
2148 f++;
2149 while (Py_ISDIGIT((unsigned)*f))
2150 precision = (precision*10) + *f++ - '0';
2151 if (*f == '%') {
2152 /* "%.3%s" => f points to "3" */
2153 f--;
2154 }
2155 }
2156 if (*f == '\0') {
2157 /* bogus format "%.1" => go backward, f points to "1" */
2158 f--;
2159 }
2160 if (p_width != NULL)
2161 *p_width = width;
2162 if (p_precision != NULL)
2163 *p_precision = precision;
2164
2165 /* Handle %ld, %lu, %lld and %llu. */
2166 longflag = 0;
2167 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002168 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002169
2170 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002171 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002172 longflag = 1;
2173 ++f;
2174 }
2175#ifdef HAVE_LONG_LONG
2176 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002177 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002178 longlongflag = 1;
2179 f += 2;
2180 }
2181#endif
2182 }
2183 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002184 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002185 size_tflag = 1;
2186 ++f;
2187 }
2188 if (p_longflag != NULL)
2189 *p_longflag = longflag;
2190 if (p_longlongflag != NULL)
2191 *p_longlongflag = longlongflag;
2192 if (p_size_tflag != NULL)
2193 *p_size_tflag = size_tflag;
2194 return f;
2195}
2196
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002197/* maximum number of characters required for output of %ld. 21 characters
2198 allows for 64-bit integers (in decimal) and an optional sign. */
2199#define MAX_LONG_CHARS 21
2200/* maximum number of characters required for output of %lld.
2201 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2202 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2203#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2204
Walter Dörwaldd2034312007-05-18 16:29:38 +00002205PyObject *
2206PyUnicode_FromFormatV(const char *format, va_list vargs)
2207{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002208 va_list count;
2209 Py_ssize_t callcount = 0;
2210 PyObject **callresults = NULL;
2211 PyObject **callresult = NULL;
2212 Py_ssize_t n = 0;
2213 int width = 0;
2214 int precision = 0;
2215 int zeropad;
2216 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002217 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002218 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002219 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002220 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2221 Py_UCS4 argmaxchar;
2222 Py_ssize_t numbersize = 0;
2223 char *numberresults = NULL;
2224 char *numberresult = NULL;
2225 Py_ssize_t i;
2226 int kind;
2227 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002228
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002229 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002230 /* step 1: count the number of %S/%R/%A/%s format specifications
2231 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2232 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002233 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002234 * also estimate a upper bound for all the number formats in the string,
2235 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002237 for (f = format; *f; f++) {
2238 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002239 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002240 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2241 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2242 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2243 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002244
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002245 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002246#ifdef HAVE_LONG_LONG
2247 if (longlongflag) {
2248 if (width < MAX_LONG_LONG_CHARS)
2249 width = MAX_LONG_LONG_CHARS;
2250 }
2251 else
2252#endif
2253 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2254 including sign. Decimal takes the most space. This
2255 isn't enough for octal. If a width is specified we
2256 need more (which we allocate later). */
2257 if (width < MAX_LONG_CHARS)
2258 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002259
2260 /* account for the size + '\0' to separate numbers
2261 inside of the numberresults buffer */
2262 numbersize += (width + 1);
2263 }
2264 }
2265 else if ((unsigned char)*f > 127) {
2266 PyErr_Format(PyExc_ValueError,
2267 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2268 "string, got a non-ASCII byte: 0x%02x",
2269 (unsigned char)*f);
2270 return NULL;
2271 }
2272 }
2273 /* step 2: allocate memory for the results of
2274 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2275 if (callcount) {
2276 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2277 if (!callresults) {
2278 PyErr_NoMemory();
2279 return NULL;
2280 }
2281 callresult = callresults;
2282 }
2283 /* step 2.5: allocate memory for the results of formating numbers */
2284 if (numbersize) {
2285 numberresults = PyObject_Malloc(numbersize);
2286 if (!numberresults) {
2287 PyErr_NoMemory();
2288 goto fail;
2289 }
2290 numberresult = numberresults;
2291 }
2292
2293 /* step 3: format numbers and figure out how large a buffer we need */
2294 for (f = format; *f; f++) {
2295 if (*f == '%') {
2296 const char* p;
2297 int longflag;
2298 int longlongflag;
2299 int size_tflag;
2300 int numprinted;
2301
2302 p = f;
2303 zeropad = (f[1] == '0');
2304 f = parse_format_flags(f, &width, &precision,
2305 &longflag, &longlongflag, &size_tflag);
2306 switch (*f) {
2307 case 'c':
2308 {
2309 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002310 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002311 n++;
2312 break;
2313 }
2314 case '%':
2315 n++;
2316 break;
2317 case 'i':
2318 case 'd':
2319 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2320 width, precision, *f);
2321 if (longflag)
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, long));
2324#ifdef HAVE_LONG_LONG
2325 else if (longlongflag)
2326 numprinted = sprintf(numberresult, fmt,
2327 va_arg(count, PY_LONG_LONG));
2328#endif
2329 else if (size_tflag)
2330 numprinted = sprintf(numberresult, fmt,
2331 va_arg(count, Py_ssize_t));
2332 else
2333 numprinted = sprintf(numberresult, fmt,
2334 va_arg(count, int));
2335 n += numprinted;
2336 /* advance by +1 to skip over the '\0' */
2337 numberresult += (numprinted + 1);
2338 assert(*(numberresult - 1) == '\0');
2339 assert(*(numberresult - 2) != '\0');
2340 assert(numprinted >= 0);
2341 assert(numberresult <= numberresults + numbersize);
2342 break;
2343 case 'u':
2344 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2345 width, precision, 'u');
2346 if (longflag)
2347 numprinted = sprintf(numberresult, fmt,
2348 va_arg(count, unsigned long));
2349#ifdef HAVE_LONG_LONG
2350 else if (longlongflag)
2351 numprinted = sprintf(numberresult, fmt,
2352 va_arg(count, unsigned PY_LONG_LONG));
2353#endif
2354 else if (size_tflag)
2355 numprinted = sprintf(numberresult, fmt,
2356 va_arg(count, size_t));
2357 else
2358 numprinted = sprintf(numberresult, fmt,
2359 va_arg(count, unsigned int));
2360 n += numprinted;
2361 numberresult += (numprinted + 1);
2362 assert(*(numberresult - 1) == '\0');
2363 assert(*(numberresult - 2) != '\0');
2364 assert(numprinted >= 0);
2365 assert(numberresult <= numberresults + numbersize);
2366 break;
2367 case 'x':
2368 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2369 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2370 n += numprinted;
2371 numberresult += (numprinted + 1);
2372 assert(*(numberresult - 1) == '\0');
2373 assert(*(numberresult - 2) != '\0');
2374 assert(numprinted >= 0);
2375 assert(numberresult <= numberresults + numbersize);
2376 break;
2377 case 'p':
2378 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2379 /* %p is ill-defined: ensure leading 0x. */
2380 if (numberresult[1] == 'X')
2381 numberresult[1] = 'x';
2382 else if (numberresult[1] != 'x') {
2383 memmove(numberresult + 2, numberresult,
2384 strlen(numberresult) + 1);
2385 numberresult[0] = '0';
2386 numberresult[1] = 'x';
2387 numprinted += 2;
2388 }
2389 n += numprinted;
2390 numberresult += (numprinted + 1);
2391 assert(*(numberresult - 1) == '\0');
2392 assert(*(numberresult - 2) != '\0');
2393 assert(numprinted >= 0);
2394 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002395 break;
2396 case 's':
2397 {
2398 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002399 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002400 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2401 if (!str)
2402 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 /* since PyUnicode_DecodeUTF8 returns already flexible
2404 unicode objects, there is no need to call ready on them */
2405 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002406 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002407 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002408 /* Remember the str and switch to the next slot */
2409 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002410 break;
2411 }
2412 case 'U':
2413 {
2414 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002415 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 if (PyUnicode_READY(obj) == -1)
2417 goto fail;
2418 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002419 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002420 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002421 break;
2422 }
2423 case 'V':
2424 {
2425 PyObject *obj = va_arg(count, PyObject *);
2426 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002427 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002428 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002429 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002430 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 if (PyUnicode_READY(obj) == -1)
2432 goto fail;
2433 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002434 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002435 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002436 *callresult++ = NULL;
2437 }
2438 else {
2439 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2440 if (!str_obj)
2441 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002442 if (PyUnicode_READY(str_obj)) {
2443 Py_DECREF(str_obj);
2444 goto fail;
2445 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002446 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002447 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002448 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002449 *callresult++ = str_obj;
2450 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002451 break;
2452 }
2453 case 'S':
2454 {
2455 PyObject *obj = va_arg(count, PyObject *);
2456 PyObject *str;
2457 assert(obj);
2458 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002461 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002462 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002463 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002464 /* Remember the str and switch to the next slot */
2465 *callresult++ = str;
2466 break;
2467 }
2468 case 'R':
2469 {
2470 PyObject *obj = va_arg(count, PyObject *);
2471 PyObject *repr;
2472 assert(obj);
2473 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002476 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002477 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002478 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002479 /* Remember the repr and switch to the next slot */
2480 *callresult++ = repr;
2481 break;
2482 }
2483 case 'A':
2484 {
2485 PyObject *obj = va_arg(count, PyObject *);
2486 PyObject *ascii;
2487 assert(obj);
2488 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002491 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002492 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002493 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 /* Remember the repr and switch to the next slot */
2495 *callresult++ = ascii;
2496 break;
2497 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002498 default:
2499 /* if we stumble upon an unknown
2500 formatting code, copy the rest of
2501 the format string to the output
2502 string. (we cannot just skip the
2503 code, since there's no way to know
2504 what's in the argument list) */
2505 n += strlen(p);
2506 goto expand;
2507 }
2508 } else
2509 n++;
2510 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002511 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002512 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002513 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002514 we don't have to resize the string.
2515 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002516 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002517 if (!string)
2518 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 kind = PyUnicode_KIND(string);
2520 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002521 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002522 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002523
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002524 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002525 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002526 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002527
2528 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002529 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2530 /* checking for == because the last argument could be a empty
2531 string, which causes i to point to end, the assert at the end of
2532 the loop */
2533 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002534
Benjamin Peterson14339b62009-01-31 16:36:08 +00002535 switch (*f) {
2536 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002537 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002538 const int ordinal = va_arg(vargs, int);
2539 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002541 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002542 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002543 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002544 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002545 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002546 case 'p':
2547 /* unused, since we already have the result */
2548 if (*f == 'p')
2549 (void) va_arg(vargs, void *);
2550 else
2551 (void) va_arg(vargs, int);
2552 /* extract the result from numberresults and append. */
2553 for (; *numberresult; ++i, ++numberresult)
2554 PyUnicode_WRITE(kind, data, i, *numberresult);
2555 /* skip over the separating '\0' */
2556 assert(*numberresult == '\0');
2557 numberresult++;
2558 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002559 break;
2560 case 's':
2561 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002562 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002563 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002564 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002565 size = PyUnicode_GET_LENGTH(*callresult);
2566 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002567 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002568 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002569 /* We're done with the unicode()/repr() => forget it */
2570 Py_DECREF(*callresult);
2571 /* switch to next unicode()/repr() result */
2572 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002573 break;
2574 }
2575 case 'U':
2576 {
2577 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 Py_ssize_t size;
2579 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2580 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002581 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002582 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002583 break;
2584 }
2585 case 'V':
2586 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002588 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002589 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002590 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 size = PyUnicode_GET_LENGTH(obj);
2592 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002593 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002594 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002595 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 size = PyUnicode_GET_LENGTH(*callresult);
2597 assert(PyUnicode_KIND(*callresult) <=
2598 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002599 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002600 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002601 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002602 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002603 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002604 break;
2605 }
2606 case 'S':
2607 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002608 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002609 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002610 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002611 /* unused, since we already have the result */
2612 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002613 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002614 copy_characters(string, i, *callresult, 0, size);
2615 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002616 /* We're done with the unicode()/repr() => forget it */
2617 Py_DECREF(*callresult);
2618 /* switch to next unicode()/repr() result */
2619 ++callresult;
2620 break;
2621 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002622 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002624 break;
2625 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002626 for (; *p; ++p, ++i)
2627 PyUnicode_WRITE(kind, data, i, *p);
2628 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002629 goto end;
2630 }
Victor Stinner1205f272010-09-11 00:54:47 +00002631 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002632 else {
2633 assert(i < PyUnicode_GET_LENGTH(string));
2634 PyUnicode_WRITE(kind, data, i++, *f);
2635 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002637 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002638
Benjamin Peterson29060642009-01-31 22:14:21 +00002639 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002640 if (callresults)
2641 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002642 if (numberresults)
2643 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002644 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002645 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002646 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 if (callresults) {
2648 PyObject **callresult2 = callresults;
2649 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002650 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002651 ++callresult2;
2652 }
2653 PyObject_Free(callresults);
2654 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002655 if (numberresults)
2656 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002657 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002658}
2659
Walter Dörwaldd2034312007-05-18 16:29:38 +00002660PyObject *
2661PyUnicode_FromFormat(const char *format, ...)
2662{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002663 PyObject* ret;
2664 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002665
2666#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002668#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002669 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002671 ret = PyUnicode_FromFormatV(format, vargs);
2672 va_end(vargs);
2673 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002674}
2675
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002676#ifdef HAVE_WCHAR_H
2677
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2679 convert a Unicode object to a wide character string.
2680
Victor Stinnerd88d9832011-09-06 02:00:05 +02002681 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002682 character) required to convert the unicode object. Ignore size argument.
2683
Victor Stinnerd88d9832011-09-06 02:00:05 +02002684 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002685 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002686 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002687static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002688unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002689 wchar_t *w,
2690 Py_ssize_t size)
2691{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002692 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002693 const wchar_t *wstr;
2694
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002695 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002696 if (wstr == NULL)
2697 return -1;
2698
Victor Stinner5593d8a2010-10-02 11:11:27 +00002699 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002700 if (size > res)
2701 size = res + 1;
2702 else
2703 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002705 return res;
2706 }
2707 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002708 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002709}
2710
2711Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002712PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002713 wchar_t *w,
2714 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002715{
2716 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002717 PyErr_BadInternalCall();
2718 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002719 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002720 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002721}
2722
Victor Stinner137c34c2010-09-29 10:25:54 +00002723wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002724PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002725 Py_ssize_t *size)
2726{
2727 wchar_t* buffer;
2728 Py_ssize_t buflen;
2729
2730 if (unicode == NULL) {
2731 PyErr_BadInternalCall();
2732 return NULL;
2733 }
2734
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002735 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002736 if (buflen == -1)
2737 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002738 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002739 PyErr_NoMemory();
2740 return NULL;
2741 }
2742
Victor Stinner137c34c2010-09-29 10:25:54 +00002743 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2744 if (buffer == NULL) {
2745 PyErr_NoMemory();
2746 return NULL;
2747 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002748 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002749 if (buflen == -1)
2750 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002751 if (size != NULL)
2752 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002753 return buffer;
2754}
2755
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002756#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002757
Alexander Belopolsky40018472011-02-26 01:02:56 +00002758PyObject *
2759PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002760{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002761 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002762 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002763 PyErr_SetString(PyExc_ValueError,
2764 "chr() arg not in range(0x110000)");
2765 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002766 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 if (ordinal < 256)
2769 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002770
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002771 v = PyUnicode_New(1, ordinal);
2772 if (v == NULL)
2773 return NULL;
2774 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002775 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002776 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002777}
2778
Alexander Belopolsky40018472011-02-26 01:02:56 +00002779PyObject *
2780PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002781{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002782 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002784 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002785 if (PyUnicode_READY(obj))
2786 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002787 Py_INCREF(obj);
2788 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002789 }
2790 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002791 /* For a Unicode subtype that's not a Unicode object,
2792 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002793 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002794 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002795 PyErr_Format(PyExc_TypeError,
2796 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002797 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002798 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002799}
2800
Alexander Belopolsky40018472011-02-26 01:02:56 +00002801PyObject *
2802PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002803 const char *encoding,
2804 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002805{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002806 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002807 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002808
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002810 PyErr_BadInternalCall();
2811 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002812 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002813
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002814 /* Decoding bytes objects is the most common case and should be fast */
2815 if (PyBytes_Check(obj)) {
2816 if (PyBytes_GET_SIZE(obj) == 0) {
2817 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002818 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002819 }
2820 else {
2821 v = PyUnicode_Decode(
2822 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2823 encoding, errors);
2824 }
2825 return v;
2826 }
2827
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002828 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002829 PyErr_SetString(PyExc_TypeError,
2830 "decoding str is not supported");
2831 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002832 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002833
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002834 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2835 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2836 PyErr_Format(PyExc_TypeError,
2837 "coercing to str: need bytes, bytearray "
2838 "or buffer-like object, %.80s found",
2839 Py_TYPE(obj)->tp_name);
2840 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002841 }
Tim Petersced69f82003-09-16 20:30:58 +00002842
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002843 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002844 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002845 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002846 }
Tim Petersced69f82003-09-16 20:30:58 +00002847 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002848 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002849
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002850 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002851 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002852}
2853
Victor Stinner600d3be2010-06-10 12:00:55 +00002854/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002855 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2856 1 on success. */
2857static int
2858normalize_encoding(const char *encoding,
2859 char *lower,
2860 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002861{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002862 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002863 char *l;
2864 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002865
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002866 if (encoding == NULL) {
2867 strcpy(lower, "utf-8");
2868 return 1;
2869 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002870 e = encoding;
2871 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002872 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002873 while (*e) {
2874 if (l == l_end)
2875 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002876 if (Py_ISUPPER(*e)) {
2877 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002878 }
2879 else if (*e == '_') {
2880 *l++ = '-';
2881 e++;
2882 }
2883 else {
2884 *l++ = *e++;
2885 }
2886 }
2887 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002888 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002889}
2890
Alexander Belopolsky40018472011-02-26 01:02:56 +00002891PyObject *
2892PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002893 Py_ssize_t size,
2894 const char *encoding,
2895 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002896{
2897 PyObject *buffer = NULL, *unicode;
2898 Py_buffer info;
2899 char lower[11]; /* Enough for any encoding shortcut */
2900
Fred Drakee4315f52000-05-09 19:53:39 +00002901 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002902 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002903 if ((strcmp(lower, "utf-8") == 0) ||
2904 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002905 return PyUnicode_DecodeUTF8(s, size, errors);
2906 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002907 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002908 (strcmp(lower, "iso-8859-1") == 0))
2909 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002910#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002911 else if (strcmp(lower, "mbcs") == 0)
2912 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002913#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002914 else if (strcmp(lower, "ascii") == 0)
2915 return PyUnicode_DecodeASCII(s, size, errors);
2916 else if (strcmp(lower, "utf-16") == 0)
2917 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2918 else if (strcmp(lower, "utf-32") == 0)
2919 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2920 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002921
2922 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002923 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002924 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002925 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002926 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002927 if (buffer == NULL)
2928 goto onError;
2929 unicode = PyCodec_Decode(buffer, encoding, errors);
2930 if (unicode == NULL)
2931 goto onError;
2932 if (!PyUnicode_Check(unicode)) {
2933 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002934 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002935 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002936 Py_DECREF(unicode);
2937 goto onError;
2938 }
2939 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002940#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002941 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002942 Py_DECREF(unicode);
2943 return NULL;
2944 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002945#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002946 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002947 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002948
Benjamin Peterson29060642009-01-31 22:14:21 +00002949 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002950 Py_XDECREF(buffer);
2951 return NULL;
2952}
2953
Alexander Belopolsky40018472011-02-26 01:02:56 +00002954PyObject *
2955PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002956 const char *encoding,
2957 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002958{
2959 PyObject *v;
2960
2961 if (!PyUnicode_Check(unicode)) {
2962 PyErr_BadArgument();
2963 goto onError;
2964 }
2965
2966 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002967 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002968
2969 /* Decode via the codec registry */
2970 v = PyCodec_Decode(unicode, encoding, errors);
2971 if (v == NULL)
2972 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002973 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002974 return v;
2975
Benjamin Peterson29060642009-01-31 22:14:21 +00002976 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002977 return NULL;
2978}
2979
Alexander Belopolsky40018472011-02-26 01:02:56 +00002980PyObject *
2981PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002982 const char *encoding,
2983 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002984{
2985 PyObject *v;
2986
2987 if (!PyUnicode_Check(unicode)) {
2988 PyErr_BadArgument();
2989 goto onError;
2990 }
2991
2992 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002993 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002994
2995 /* Decode via the codec registry */
2996 v = PyCodec_Decode(unicode, encoding, errors);
2997 if (v == NULL)
2998 goto onError;
2999 if (!PyUnicode_Check(v)) {
3000 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003001 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003002 Py_TYPE(v)->tp_name);
3003 Py_DECREF(v);
3004 goto onError;
3005 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003006 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003007 return v;
3008
Benjamin Peterson29060642009-01-31 22:14:21 +00003009 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003010 return NULL;
3011}
3012
Alexander Belopolsky40018472011-02-26 01:02:56 +00003013PyObject *
3014PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003015 Py_ssize_t size,
3016 const char *encoding,
3017 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003018{
3019 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003020
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021 unicode = PyUnicode_FromUnicode(s, size);
3022 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003023 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003024 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3025 Py_DECREF(unicode);
3026 return v;
3027}
3028
Alexander Belopolsky40018472011-02-26 01:02:56 +00003029PyObject *
3030PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003031 const char *encoding,
3032 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003033{
3034 PyObject *v;
3035
3036 if (!PyUnicode_Check(unicode)) {
3037 PyErr_BadArgument();
3038 goto onError;
3039 }
3040
3041 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003042 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003043
3044 /* Encode via the codec registry */
3045 v = PyCodec_Encode(unicode, encoding, errors);
3046 if (v == NULL)
3047 goto onError;
3048 return v;
3049
Benjamin Peterson29060642009-01-31 22:14:21 +00003050 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003051 return NULL;
3052}
3053
Victor Stinnerad158722010-10-27 00:25:46 +00003054PyObject *
3055PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003056{
Victor Stinner99b95382011-07-04 14:23:54 +02003057#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003058 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Victor Stinnerad158722010-10-27 00:25:46 +00003059#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003060 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003061#else
Victor Stinner793b5312011-04-27 00:24:21 +02003062 PyInterpreterState *interp = PyThreadState_GET()->interp;
3063 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3064 cannot use it to encode and decode filenames before it is loaded. Load
3065 the Python codec requires to encode at least its own filename. Use the C
3066 version of the locale codec until the codec registry is initialized and
3067 the Python codec is loaded.
3068
3069 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3070 cannot only rely on it: check also interp->fscodec_initialized for
3071 subinterpreters. */
3072 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003073 return PyUnicode_AsEncodedString(unicode,
3074 Py_FileSystemDefaultEncoding,
3075 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003076 }
3077 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003078 /* locale encoding with surrogateescape */
3079 wchar_t *wchar;
3080 char *bytes;
3081 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003082 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003083
3084 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3085 if (wchar == NULL)
3086 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003087 bytes = _Py_wchar2char(wchar, &error_pos);
3088 if (bytes == NULL) {
3089 if (error_pos != (size_t)-1) {
3090 char *errmsg = strerror(errno);
3091 PyObject *exc = NULL;
3092 if (errmsg == NULL)
3093 errmsg = "Py_wchar2char() failed";
3094 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003095 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003096 error_pos, error_pos+1,
3097 errmsg);
3098 Py_XDECREF(exc);
3099 }
3100 else
3101 PyErr_NoMemory();
3102 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003103 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003104 }
3105 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003106
3107 bytes_obj = PyBytes_FromString(bytes);
3108 PyMem_Free(bytes);
3109 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003110 }
Victor Stinnerad158722010-10-27 00:25:46 +00003111#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003112}
3113
Alexander Belopolsky40018472011-02-26 01:02:56 +00003114PyObject *
3115PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003116 const char *encoding,
3117 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003118{
3119 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003120 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003121
Guido van Rossumd57fd912000-03-10 22:53:23 +00003122 if (!PyUnicode_Check(unicode)) {
3123 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003124 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003125 }
Fred Drakee4315f52000-05-09 19:53:39 +00003126
Fred Drakee4315f52000-05-09 19:53:39 +00003127 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003128 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003129 if ((strcmp(lower, "utf-8") == 0) ||
3130 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003131 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003132 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003133 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003134 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003135 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003136 }
Victor Stinner37296e82010-06-10 13:36:23 +00003137 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003138 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003139 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003140 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003141#ifdef HAVE_MBCS
Victor Stinnerac931b12011-11-20 18:27:03 +01003142 else if (strcmp(lower, "mbcs") == 0)
3143 return PyUnicode_EncodeCodePage(CP_ACP, unicode, 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;
Victor Stinner24729f32011-11-10 20:31:37 +01003847 Py_UCS4 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 */
Victor Stinner24729f32011-11-10 20:31:37 +01003876 Py_UCS4 outCh = (Py_UCS4)(base64buffer >> (base64bits-16));
Antoine Pitrou244651a2009-05-04 18:56:13 +00003877 base64bits -= 16;
3878 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3879 if (surrogate) {
3880 /* expecting a second surrogate */
3881 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003882 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3883 | (outCh & 0x3FF)) + 0x10000;
3884 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3885 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003886 surrogate = 0;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003887 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003888 }
3889 else {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003890 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3891 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003892 surrogate = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003893 }
3894 }
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003895 if (outCh >= 0xD800 && outCh <= 0xDBFF) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003896 /* first surrogate */
3897 surrogate = outCh;
3898 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003899 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003900 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3901 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003902 }
3903 }
3904 }
3905 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003906 inShift = 0;
3907 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003908 if (surrogate) {
Antoine Pitrou78edf752011-11-15 01:44:16 +01003909 if (unicode_putchar(&unicode, &outpos, surrogate) < 0)
3910 goto onError;
Antoine Pitrou5418ee02011-11-15 01:42:21 +01003911 surrogate = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003912 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003913 if (base64bits > 0) { /* left-over bits */
3914 if (base64bits >= 6) {
3915 /* We've seen at least one base-64 character */
3916 errmsg = "partial character in shift sequence";
3917 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003918 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003919 else {
3920 /* Some bits remain; they should be zero */
3921 if (base64buffer != 0) {
3922 errmsg = "non-zero padding bits in shift sequence";
3923 goto utf7Error;
3924 }
3925 }
3926 }
3927 if (ch != '-') {
3928 /* '-' is absorbed; other terminating
3929 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003930 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3931 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003932 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003933 }
3934 }
3935 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003936 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003937 s++; /* consume '+' */
3938 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003939 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003940 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3941 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003942 }
3943 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003944 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003945 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003946 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003947 }
3948 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003949 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003950 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3951 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003952 s++;
3953 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003954 else {
3955 startinpos = s-starts;
3956 s++;
3957 errmsg = "unexpected special character";
3958 goto utf7Error;
3959 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003960 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003961utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003962 endinpos = s-starts;
3963 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003964 errors, &errorHandler,
3965 "utf7", errmsg,
3966 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003967 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003968 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003969 }
3970
Antoine Pitrou244651a2009-05-04 18:56:13 +00003971 /* end of string */
3972
3973 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3974 /* if we're in an inconsistent state, that's an error */
3975 if (surrogate ||
3976 (base64bits >= 6) ||
3977 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003978 endinpos = size;
3979 if (unicode_decode_call_errorhandler(
3980 errors, &errorHandler,
3981 "utf7", "unterminated shift sequence",
3982 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003983 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003984 goto onError;
3985 if (s < e)
3986 goto restart;
3987 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003988 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003989
3990 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003991 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003992 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003993 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003994 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 }
3996 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003997 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003998 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003999 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004000
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004001 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004002 goto onError;
4003
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004004 Py_XDECREF(errorHandler);
4005 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004006#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004007 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004008 Py_DECREF(unicode);
4009 return NULL;
4010 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004011#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004012 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004013 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004014
Benjamin Peterson29060642009-01-31 22:14:21 +00004015 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004016 Py_XDECREF(errorHandler);
4017 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004018 Py_DECREF(unicode);
4019 return NULL;
4020}
4021
4022
Alexander Belopolsky40018472011-02-26 01:02:56 +00004023PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004024_PyUnicode_EncodeUTF7(PyObject *str,
4025 int base64SetO,
4026 int base64WhiteSpace,
4027 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004028{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004029 int kind;
4030 void *data;
4031 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004032 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004033 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004034 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004035 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004036 unsigned int base64bits = 0;
4037 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004038 char * out;
4039 char * start;
4040
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004041 if (PyUnicode_READY(str) < 0)
4042 return NULL;
4043 kind = PyUnicode_KIND(str);
4044 data = PyUnicode_DATA(str);
4045 len = PyUnicode_GET_LENGTH(str);
4046
4047 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004048 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004049
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004050 /* It might be possible to tighten this worst case */
4051 allocated = 8 * len;
4052 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004053 return PyErr_NoMemory();
4054
Antoine Pitrou244651a2009-05-04 18:56:13 +00004055 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004056 if (v == NULL)
4057 return NULL;
4058
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004059 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004060 for (i = 0; i < len; ++i) {
Victor Stinner0e368262011-11-10 20:12:49 +01004061 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004062
Antoine Pitrou244651a2009-05-04 18:56:13 +00004063 if (inShift) {
4064 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4065 /* shifting out */
4066 if (base64bits) { /* output remaining bits */
4067 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4068 base64buffer = 0;
4069 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004070 }
4071 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004072 /* Characters not in the BASE64 set implicitly unshift the sequence
4073 so no '-' is required, except if the character is itself a '-' */
4074 if (IS_BASE64(ch) || ch == '-') {
4075 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004076 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004077 *out++ = (char) ch;
4078 }
4079 else {
4080 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004081 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004082 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004083 else { /* not in a shift sequence */
4084 if (ch == '+') {
4085 *out++ = '+';
4086 *out++ = '-';
4087 }
4088 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4089 *out++ = (char) ch;
4090 }
4091 else {
4092 *out++ = '+';
4093 inShift = 1;
4094 goto encode_char;
4095 }
4096 }
4097 continue;
4098encode_char:
Antoine Pitrou244651a2009-05-04 18:56:13 +00004099 if (ch >= 0x10000) {
4100 /* code first surrogate */
4101 base64bits += 16;
4102 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4103 while (base64bits >= 6) {
4104 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4105 base64bits -= 6;
4106 }
4107 /* prepare second surrogate */
4108 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4109 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004110 base64bits += 16;
4111 base64buffer = (base64buffer << 16) | ch;
4112 while (base64bits >= 6) {
4113 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4114 base64bits -= 6;
4115 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004116 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004117 if (base64bits)
4118 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4119 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004120 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004121 if (_PyBytes_Resize(&v, out - start) < 0)
4122 return NULL;
4123 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004124}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004125PyObject *
4126PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4127 Py_ssize_t size,
4128 int base64SetO,
4129 int base64WhiteSpace,
4130 const char *errors)
4131{
4132 PyObject *result;
4133 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4134 if (tmp == NULL)
4135 return NULL;
Victor Stinner0e368262011-11-10 20:12:49 +01004136 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004137 base64WhiteSpace, errors);
4138 Py_DECREF(tmp);
4139 return result;
4140}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004141
Antoine Pitrou244651a2009-05-04 18:56:13 +00004142#undef IS_BASE64
4143#undef FROM_BASE64
4144#undef TO_BASE64
4145#undef DECODE_DIRECT
4146#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004147
Guido van Rossumd57fd912000-03-10 22:53:23 +00004148/* --- UTF-8 Codec -------------------------------------------------------- */
4149
Tim Petersced69f82003-09-16 20:30:58 +00004150static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004151char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004152 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4153 illegal prefix. See RFC 3629 for details */
4154 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4155 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004156 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004157 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4158 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4159 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4160 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4162 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 +00004163 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4164 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004165 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4166 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4167 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4168 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4169 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 +00004170};
4171
Alexander Belopolsky40018472011-02-26 01:02:56 +00004172PyObject *
4173PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004174 Py_ssize_t size,
4175 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004176{
Walter Dörwald69652032004-09-07 20:24:22 +00004177 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4178}
4179
Antoine Pitrouab868312009-01-10 15:40:25 +00004180/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4181#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4182
4183/* Mask to quickly check whether a C 'long' contains a
4184 non-ASCII, UTF8-encoded char. */
4185#if (SIZEOF_LONG == 8)
4186# define ASCII_CHAR_MASK 0x8080808080808080L
4187#elif (SIZEOF_LONG == 4)
4188# define ASCII_CHAR_MASK 0x80808080L
4189#else
4190# error C 'long' size should be either 4 or 8!
4191#endif
4192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004193/* Scans a UTF-8 string and returns the maximum character to be expected,
4194 the size of the decoded unicode string and if any major errors were
4195 encountered.
4196
4197 This function does check basic UTF-8 sanity, it does however NOT CHECK
4198 if the string contains surrogates, and if all continuation bytes are
4199 within the correct ranges, these checks are performed in
4200 PyUnicode_DecodeUTF8Stateful.
4201
4202 If it sets has_errors to 1, it means the value of unicode_size and max_char
4203 will be bogus and you should not rely on useful information in them.
4204 */
4205static Py_UCS4
4206utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4207 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4208 int *has_errors)
4209{
4210 Py_ssize_t n;
4211 Py_ssize_t char_count = 0;
4212 Py_UCS4 max_char = 127, new_max;
4213 Py_UCS4 upper_bound;
4214 const unsigned char *p = (const unsigned char *)s;
4215 const unsigned char *end = p + string_size;
4216 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4217 int err = 0;
4218
4219 for (; p < end && !err; ++p, ++char_count) {
4220 /* Only check value if it's not a ASCII char... */
4221 if (*p < 0x80) {
4222 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4223 an explanation. */
4224 if (!((size_t) p & LONG_PTR_MASK)) {
4225 /* Help register allocation */
4226 register const unsigned char *_p = p;
4227 while (_p < aligned_end) {
4228 unsigned long value = *(unsigned long *) _p;
4229 if (value & ASCII_CHAR_MASK)
4230 break;
4231 _p += SIZEOF_LONG;
4232 char_count += SIZEOF_LONG;
4233 }
4234 p = _p;
4235 if (p == end)
4236 break;
4237 }
4238 }
4239 if (*p >= 0x80) {
4240 n = utf8_code_length[*p];
4241 new_max = max_char;
4242 switch (n) {
4243 /* invalid start byte */
4244 case 0:
4245 err = 1;
4246 break;
4247 case 2:
4248 /* Code points between 0x00FF and 0x07FF inclusive.
4249 Approximate the upper bound of the code point,
4250 if this flips over 255 we can be sure it will be more
4251 than 255 and the string will need 2 bytes per code coint,
4252 if it stays under or equal to 255, we can be sure 1 byte
4253 is enough.
4254 ((*p & 0b00011111) << 6) | 0b00111111 */
4255 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4256 if (max_char < upper_bound)
4257 new_max = upper_bound;
4258 /* Ensure we track at least that we left ASCII space. */
4259 if (new_max < 128)
4260 new_max = 128;
4261 break;
4262 case 3:
4263 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4264 always > 255 and <= 65535 and will always need 2 bytes. */
4265 if (max_char < 65535)
4266 new_max = 65535;
4267 break;
4268 case 4:
4269 /* Code point will be above 0xFFFF for sure in this case. */
4270 new_max = 65537;
4271 break;
4272 /* Internal error, this should be caught by the first if */
4273 case 1:
4274 default:
4275 assert(0 && "Impossible case in utf8_max_char_and_size");
4276 err = 1;
4277 }
4278 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004279 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004280 --n;
4281 /* Check if the follow up chars are all valid continuation bytes */
4282 if (n >= 1) {
4283 const unsigned char *cont;
4284 if ((p + n) >= end) {
4285 if (consumed == 0)
4286 /* incomplete data, non-incremental decoding */
4287 err = 1;
4288 break;
4289 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004290 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004291 if ((*cont & 0xc0) != 0x80) {
4292 err = 1;
4293 break;
4294 }
4295 }
4296 p += n;
4297 }
4298 else
4299 err = 1;
4300 max_char = new_max;
4301 }
4302 }
4303
4304 if (unicode_size)
4305 *unicode_size = char_count;
4306 if (has_errors)
4307 *has_errors = err;
4308 return max_char;
4309}
4310
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004311/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4312 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4313 onError. Potential resizing overallocates, so the result needs to shrink
4314 at the end.
4315*/
4316#define WRITE_MAYBE_FAIL(index, value) \
4317 do { \
4318 if (has_errors) { \
4319 Py_ssize_t pos = index; \
4320 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4321 unicode_resize(&unicode, pos + pos/8) < 0) \
4322 goto onError; \
4323 if (unicode_putchar(&unicode, &pos, value) < 0) \
4324 goto onError; \
4325 } \
4326 else \
4327 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004328 } while (0)
4329
Alexander Belopolsky40018472011-02-26 01:02:56 +00004330PyObject *
4331PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004332 Py_ssize_t size,
4333 const char *errors,
4334 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004335{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004336 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004337 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004338 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004339 Py_ssize_t startinpos;
4340 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004341 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004342 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004343 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004344 PyObject *errorHandler = NULL;
4345 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004346 Py_UCS4 maxchar = 0;
4347 Py_ssize_t unicode_size;
4348 Py_ssize_t i;
4349 int kind;
4350 void *data;
4351 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004352
Walter Dörwald69652032004-09-07 20:24:22 +00004353 if (size == 0) {
4354 if (consumed)
4355 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004356 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004357 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004358 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4359 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004360 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004361 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004362 code below widens and resizes as necessary. */
4363 unicode = PyUnicode_New(size, 127);
4364 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004365 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004366 if (!unicode)
4367 return NULL;
4368 /* When the string is ASCII only, just use memcpy and return.
4369 unicode_size may be != size if there is an incomplete UTF-8
4370 sequence at the end of the ASCII block. */
4371 if (!has_errors && maxchar < 128 && size == unicode_size) {
4372 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4373 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004374 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004375 kind = PyUnicode_KIND(unicode);
4376 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004377 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004378 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004379 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004380 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004381
4382 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004383 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004384
4385 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004386 /* Fast path for runs of ASCII characters. Given that common UTF-8
4387 input will consist of an overwhelming majority of ASCII
4388 characters, we try to optimize for this case by checking
4389 as many characters as a C 'long' can contain.
4390 First, check if we can do an aligned read, as most CPUs have
4391 a penalty for unaligned reads.
4392 */
4393 if (!((size_t) s & LONG_PTR_MASK)) {
4394 /* Help register allocation */
4395 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004396 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004397 while (_s < aligned_end) {
4398 /* Read a whole long at a time (either 4 or 8 bytes),
4399 and do a fast unrolled copy if it only contains ASCII
4400 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004401 unsigned long value = *(unsigned long *) _s;
4402 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004403 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004404 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4405 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4406 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4407 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004408#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4410 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4411 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4412 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004413#endif
4414 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004415 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004416 }
4417 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004418 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004419 if (s == e)
4420 break;
4421 ch = (unsigned char)*s;
4422 }
4423 }
4424
4425 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004426 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004427 s++;
4428 continue;
4429 }
4430
4431 n = utf8_code_length[ch];
4432
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004433 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004434 if (consumed)
4435 break;
4436 else {
4437 errmsg = "unexpected end of data";
4438 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004439 endinpos = startinpos+1;
4440 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4441 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004442 goto utf8Error;
4443 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004444 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004445
4446 switch (n) {
4447
4448 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004449 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004450 startinpos = s-starts;
4451 endinpos = startinpos+1;
4452 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004453
4454 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004455 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004456 startinpos = s-starts;
4457 endinpos = startinpos+1;
4458 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004459
4460 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004461 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004462 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004463 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004464 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004465 goto utf8Error;
4466 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004467 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004468 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004469 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004470 break;
4471
4472 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004473 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4474 will result in surrogates in range d800-dfff. Surrogates are
4475 not valid UTF-8 so they are rejected.
4476 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4477 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004478 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004479 (s[2] & 0xc0) != 0x80 ||
4480 ((unsigned char)s[0] == 0xE0 &&
4481 (unsigned char)s[1] < 0xA0) ||
4482 ((unsigned char)s[0] == 0xED &&
4483 (unsigned char)s[1] > 0x9F)) {
4484 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004485 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004486 endinpos = startinpos + 1;
4487
4488 /* if s[1] first two bits are 1 and 0, then the invalid
4489 continuation byte is s[2], so increment endinpos by 1,
4490 if not, s[1] is invalid and endinpos doesn't need to
4491 be incremented. */
4492 if ((s[1] & 0xC0) == 0x80)
4493 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004494 goto utf8Error;
4495 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004496 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004497 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004498 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004499 break;
4500
4501 case 4:
4502 if ((s[1] & 0xc0) != 0x80 ||
4503 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004504 (s[3] & 0xc0) != 0x80 ||
4505 ((unsigned char)s[0] == 0xF0 &&
4506 (unsigned char)s[1] < 0x90) ||
4507 ((unsigned char)s[0] == 0xF4 &&
4508 (unsigned char)s[1] > 0x8F)) {
4509 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004510 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004511 endinpos = startinpos + 1;
4512 if ((s[1] & 0xC0) == 0x80) {
4513 endinpos++;
4514 if ((s[2] & 0xC0) == 0x80)
4515 endinpos++;
4516 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004517 goto utf8Error;
4518 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004519 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004520 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4521 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4522
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004523 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004524 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004525 }
4526 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004527 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004528
Benjamin Peterson29060642009-01-31 22:14:21 +00004529 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004530 if (!has_errors) {
4531 PyObject *tmp;
4532 Py_ssize_t k;
4533 /* We encountered some error that wasn't detected in the original scan,
4534 e.g. an encoded surrogate character. The original maxchar computation may
4535 have been incorrect, so redo it now. */
4536 for (k = 0, maxchar = 0; k < i; k++)
4537 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4538 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4539 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004540 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004541 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004542 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004543 unicode = tmp;
4544 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004545 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004546 if (unicode_decode_call_errorhandler(
4547 errors, &errorHandler,
4548 "utf8", errmsg,
4549 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004550 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004551 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004552 /* Update data because unicode_decode_call_errorhandler might have
4553 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004554 data = PyUnicode_DATA(unicode);
4555 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004556 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004557 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004558 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004559 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004560
Walter Dörwald69652032004-09-07 20:24:22 +00004561 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004562 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004563
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004564 /* Adjust length and ready string when it contained errors and
4565 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004566 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004567 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004568 goto onError;
4569 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004570
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004571 Py_XDECREF(errorHandler);
4572 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004573 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004574 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004575
Benjamin Peterson29060642009-01-31 22:14:21 +00004576 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004577 Py_XDECREF(errorHandler);
4578 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004579 Py_DECREF(unicode);
4580 return NULL;
4581}
4582
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004583#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004584
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004585#ifdef __APPLE__
4586
4587/* Simplified UTF-8 decoder using surrogateescape error handler,
4588 used to decode the command line arguments on Mac OS X. */
4589
4590wchar_t*
4591_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4592{
4593 int n;
4594 const char *e;
4595 wchar_t *unicode, *p;
4596
4597 /* Note: size will always be longer than the resulting Unicode
4598 character count */
4599 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4600 PyErr_NoMemory();
4601 return NULL;
4602 }
4603 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4604 if (!unicode)
4605 return NULL;
4606
4607 /* Unpack UTF-8 encoded data */
4608 p = unicode;
4609 e = s + size;
4610 while (s < e) {
4611 Py_UCS4 ch = (unsigned char)*s;
4612
4613 if (ch < 0x80) {
4614 *p++ = (wchar_t)ch;
4615 s++;
4616 continue;
4617 }
4618
4619 n = utf8_code_length[ch];
4620 if (s + n > e) {
4621 goto surrogateescape;
4622 }
4623
4624 switch (n) {
4625 case 0:
4626 case 1:
4627 goto surrogateescape;
4628
4629 case 2:
4630 if ((s[1] & 0xc0) != 0x80)
4631 goto surrogateescape;
4632 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4633 assert ((ch > 0x007F) && (ch <= 0x07FF));
4634 *p++ = (wchar_t)ch;
4635 break;
4636
4637 case 3:
4638 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4639 will result in surrogates in range d800-dfff. Surrogates are
4640 not valid UTF-8 so they are rejected.
4641 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4642 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4643 if ((s[1] & 0xc0) != 0x80 ||
4644 (s[2] & 0xc0) != 0x80 ||
4645 ((unsigned char)s[0] == 0xE0 &&
4646 (unsigned char)s[1] < 0xA0) ||
4647 ((unsigned char)s[0] == 0xED &&
4648 (unsigned char)s[1] > 0x9F)) {
4649
4650 goto surrogateescape;
4651 }
4652 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4653 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004654 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004655 break;
4656
4657 case 4:
4658 if ((s[1] & 0xc0) != 0x80 ||
4659 (s[2] & 0xc0) != 0x80 ||
4660 (s[3] & 0xc0) != 0x80 ||
4661 ((unsigned char)s[0] == 0xF0 &&
4662 (unsigned char)s[1] < 0x90) ||
4663 ((unsigned char)s[0] == 0xF4 &&
4664 (unsigned char)s[1] > 0x8F)) {
4665 goto surrogateescape;
4666 }
4667 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4668 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4669 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4670
4671#if SIZEOF_WCHAR_T == 4
4672 *p++ = (wchar_t)ch;
4673#else
4674 /* compute and append the two surrogates: */
4675
4676 /* translate from 10000..10FFFF to 0..FFFF */
4677 ch -= 0x10000;
4678
4679 /* high surrogate = top 10 bits added to D800 */
4680 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4681
4682 /* low surrogate = bottom 10 bits added to DC00 */
4683 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4684#endif
4685 break;
4686 }
4687 s += n;
4688 continue;
4689
4690 surrogateescape:
4691 *p++ = 0xDC00 + ch;
4692 s++;
4693 }
4694 *p = L'\0';
4695 return unicode;
4696}
4697
4698#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004699
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004700/* Primary internal function which creates utf8 encoded bytes objects.
4701
4702 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004703 and allocate exactly as much space needed at the end. Else allocate the
4704 maximum possible needed (4 result bytes per Unicode character), and return
4705 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004706*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004707PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004708_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004709{
Tim Peters602f7402002-04-27 18:03:26 +00004710#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004711
Guido van Rossum98297ee2007-11-06 21:34:58 +00004712 Py_ssize_t i; /* index into s of next input byte */
4713 PyObject *result; /* result string object */
4714 char *p; /* next free byte in output buffer */
4715 Py_ssize_t nallocated; /* number of result bytes allocated */
4716 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004717 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004718 PyObject *errorHandler = NULL;
4719 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004720 int kind;
4721 void *data;
4722 Py_ssize_t size;
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004723 PyObject *rep = NULL;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004724
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004725 if (!PyUnicode_Check(unicode)) {
4726 PyErr_BadArgument();
4727 return NULL;
4728 }
4729
4730 if (PyUnicode_READY(unicode) == -1)
4731 return NULL;
4732
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004733 if (PyUnicode_UTF8(unicode))
4734 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4735 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004736
4737 kind = PyUnicode_KIND(unicode);
4738 data = PyUnicode_DATA(unicode);
4739 size = PyUnicode_GET_LENGTH(unicode);
4740
Tim Peters602f7402002-04-27 18:03:26 +00004741 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004742
Tim Peters602f7402002-04-27 18:03:26 +00004743 if (size <= MAX_SHORT_UNICHARS) {
4744 /* Write into the stack buffer; nallocated can't overflow.
4745 * At the end, we'll allocate exactly as much heap space as it
4746 * turns out we need.
4747 */
4748 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004749 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004750 p = stackbuf;
4751 }
4752 else {
4753 /* Overallocate on the heap, and give the excess back at the end. */
4754 nallocated = size * 4;
4755 if (nallocated / 4 != size) /* overflow! */
4756 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004757 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004758 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004759 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004760 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004761 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004762
Tim Peters602f7402002-04-27 18:03:26 +00004763 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004764 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004765
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004766 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004767 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004768 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004769
Guido van Rossumd57fd912000-03-10 22:53:23 +00004770 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004771 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004772 *p++ = (char)(0xc0 | (ch >> 6));
4773 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004774 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004775 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004776 Py_ssize_t repsize, k, startpos;
4777 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004778 rep = unicode_encode_call_errorhandler(
4779 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004780 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004781 if (!rep)
4782 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004783
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004784 if (PyBytes_Check(rep))
4785 repsize = PyBytes_GET_SIZE(rep);
4786 else
Victor Stinner9e30aa52011-11-21 02:49:52 +01004787 repsize = PyUnicode_GET_LENGTH(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004788
4789 if (repsize > 4) {
4790 Py_ssize_t offset;
4791
4792 if (result == NULL)
4793 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004794 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004795 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004796
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004797 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4798 /* integer overflow */
4799 PyErr_NoMemory();
4800 goto error;
4801 }
4802 nallocated += repsize - 4;
4803 if (result != NULL) {
4804 if (_PyBytes_Resize(&result, nallocated) < 0)
4805 goto error;
4806 } else {
4807 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004808 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004809 goto error;
4810 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4811 }
4812 p = PyBytes_AS_STRING(result) + offset;
4813 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004815 if (PyBytes_Check(rep)) {
4816 char *prep = PyBytes_AS_STRING(rep);
4817 for(k = repsize; k > 0; k--)
4818 *p++ = *prep++;
4819 } else /* rep is unicode */ {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004820 enum PyUnicode_Kind repkind;
4821 void *repdata;
4822
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004823 if (PyUnicode_READY(rep) < 0)
Victor Stinnera98b28c2011-11-10 20:21:49 +01004824 goto error;
Victor Stinnera98b28c2011-11-10 20:21:49 +01004825 repkind = PyUnicode_KIND(rep);
4826 repdata = PyUnicode_DATA(rep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004827
4828 for(k=0; k<repsize; k++) {
Victor Stinnera98b28c2011-11-10 20:21:49 +01004829 Py_UCS4 c = PyUnicode_READ(repkind, repdata, k);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004831 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004832 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004833 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004834 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004835 goto error;
4836 }
Victor Stinnera98b28c2011-11-10 20:21:49 +01004837 *p++ = (char)c;
Victor Stinner31be90b2010-04-22 19:38:16 +00004838 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004839 }
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004840 Py_CLEAR(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004841 } else if (ch < 0x10000) {
4842 *p++ = (char)(0xe0 | (ch >> 12));
4843 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4844 *p++ = (char)(0x80 | (ch & 0x3f));
4845 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004846 /* Encode UCS4 Unicode ordinals */
4847 *p++ = (char)(0xf0 | (ch >> 18));
4848 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4849 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4850 *p++ = (char)(0x80 | (ch & 0x3f));
4851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004852 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004853
Guido van Rossum98297ee2007-11-06 21:34:58 +00004854 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004855 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004856 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004857 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004858 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004859 }
4860 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004861 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004862 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004863 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004864 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004866
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004867 Py_XDECREF(errorHandler);
4868 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004869 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004870 error:
Antoine Pitrou31b92a52011-11-12 18:35:19 +01004871 Py_XDECREF(rep);
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004872 Py_XDECREF(errorHandler);
4873 Py_XDECREF(exc);
4874 Py_XDECREF(result);
4875 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004876
Tim Peters602f7402002-04-27 18:03:26 +00004877#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004878}
4879
Alexander Belopolsky40018472011-02-26 01:02:56 +00004880PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004881PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4882 Py_ssize_t size,
4883 const char *errors)
4884{
4885 PyObject *v, *unicode;
4886
4887 unicode = PyUnicode_FromUnicode(s, size);
4888 if (unicode == NULL)
4889 return NULL;
4890 v = _PyUnicode_AsUTF8String(unicode, errors);
4891 Py_DECREF(unicode);
4892 return v;
4893}
4894
4895PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004896PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004897{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004898 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004899}
4900
Walter Dörwald41980ca2007-08-16 21:55:45 +00004901/* --- UTF-32 Codec ------------------------------------------------------- */
4902
4903PyObject *
4904PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004905 Py_ssize_t size,
4906 const char *errors,
4907 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004908{
4909 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4910}
4911
4912PyObject *
4913PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004914 Py_ssize_t size,
4915 const char *errors,
4916 int *byteorder,
4917 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004918{
4919 const char *starts = s;
4920 Py_ssize_t startinpos;
4921 Py_ssize_t endinpos;
4922 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004923 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004924 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004925 int bo = 0; /* assume native ordering by default */
4926 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004927 /* Offsets from q for retrieving bytes in the right order. */
4928#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4929 int iorder[] = {0, 1, 2, 3};
4930#else
4931 int iorder[] = {3, 2, 1, 0};
4932#endif
4933 PyObject *errorHandler = NULL;
4934 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004935
Walter Dörwald41980ca2007-08-16 21:55:45 +00004936 q = (unsigned char *)s;
4937 e = q + size;
4938
4939 if (byteorder)
4940 bo = *byteorder;
4941
4942 /* Check for BOM marks (U+FEFF) in the input and adjust current
4943 byte order setting accordingly. In native mode, the leading BOM
4944 mark is skipped, in all other modes, it is copied to the output
4945 stream as-is (giving a ZWNBSP character). */
4946 if (bo == 0) {
4947 if (size >= 4) {
4948 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004949 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004950#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004951 if (bom == 0x0000FEFF) {
4952 q += 4;
4953 bo = -1;
4954 }
4955 else if (bom == 0xFFFE0000) {
4956 q += 4;
4957 bo = 1;
4958 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004959#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004960 if (bom == 0x0000FEFF) {
4961 q += 4;
4962 bo = 1;
4963 }
4964 else if (bom == 0xFFFE0000) {
4965 q += 4;
4966 bo = -1;
4967 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004968#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004969 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004970 }
4971
4972 if (bo == -1) {
4973 /* force LE */
4974 iorder[0] = 0;
4975 iorder[1] = 1;
4976 iorder[2] = 2;
4977 iorder[3] = 3;
4978 }
4979 else if (bo == 1) {
4980 /* force BE */
4981 iorder[0] = 3;
4982 iorder[1] = 2;
4983 iorder[2] = 1;
4984 iorder[3] = 0;
4985 }
4986
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004987 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004988 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004989 if (!unicode)
4990 return NULL;
4991 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004992 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004993 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004994
Walter Dörwald41980ca2007-08-16 21:55:45 +00004995 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004996 Py_UCS4 ch;
4997 /* remaining bytes at the end? (size should be divisible by 4) */
4998 if (e-q<4) {
4999 if (consumed)
5000 break;
5001 errmsg = "truncated data";
5002 startinpos = ((const char *)q)-starts;
5003 endinpos = ((const char *)e)-starts;
5004 goto utf32Error;
5005 /* The remaining input chars are ignored if the callback
5006 chooses to skip the input */
5007 }
5008 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5009 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005010
Benjamin Peterson29060642009-01-31 22:14:21 +00005011 if (ch >= 0x110000)
5012 {
5013 errmsg = "codepoint not in range(0x110000)";
5014 startinpos = ((const char *)q)-starts;
5015 endinpos = startinpos+4;
5016 goto utf32Error;
5017 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005018 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5019 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005020 q += 4;
5021 continue;
5022 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005023 if (unicode_decode_call_errorhandler(
5024 errors, &errorHandler,
5025 "utf32", errmsg,
5026 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005027 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005028 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005029 }
5030
5031 if (byteorder)
5032 *byteorder = bo;
5033
5034 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005035 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005036
5037 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005038 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005039 goto onError;
5040
5041 Py_XDECREF(errorHandler);
5042 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005043#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005044 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005045 Py_DECREF(unicode);
5046 return NULL;
5047 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005048#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005049 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005050 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051
Benjamin Peterson29060642009-01-31 22:14:21 +00005052 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005053 Py_DECREF(unicode);
5054 Py_XDECREF(errorHandler);
5055 Py_XDECREF(exc);
5056 return NULL;
5057}
5058
5059PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005060_PyUnicode_EncodeUTF32(PyObject *str,
5061 const char *errors,
5062 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005063{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005064 int kind;
5065 void *data;
5066 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005067 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005068 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005069 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005070 /* Offsets from p for storing byte pairs in the right order. */
5071#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5072 int iorder[] = {0, 1, 2, 3};
5073#else
5074 int iorder[] = {3, 2, 1, 0};
5075#endif
5076
Benjamin Peterson29060642009-01-31 22:14:21 +00005077#define STORECHAR(CH) \
5078 do { \
5079 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5080 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5081 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5082 p[iorder[0]] = (CH) & 0xff; \
5083 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005084 } while(0)
5085
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005086 if (!PyUnicode_Check(str)) {
5087 PyErr_BadArgument();
5088 return NULL;
5089 }
5090 if (PyUnicode_READY(str) < 0)
5091 return NULL;
5092 kind = PyUnicode_KIND(str);
5093 data = PyUnicode_DATA(str);
5094 len = PyUnicode_GET_LENGTH(str);
5095
5096 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005097 bytesize = nsize * 4;
5098 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005099 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005100 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005101 if (v == NULL)
5102 return NULL;
5103
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005104 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005105 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005106 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005107 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005108 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005109
5110 if (byteorder == -1) {
5111 /* force LE */
5112 iorder[0] = 0;
5113 iorder[1] = 1;
5114 iorder[2] = 2;
5115 iorder[3] = 3;
5116 }
5117 else if (byteorder == 1) {
5118 /* force BE */
5119 iorder[0] = 3;
5120 iorder[1] = 2;
5121 iorder[2] = 1;
5122 iorder[3] = 0;
5123 }
5124
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005125 for (i = 0; i < len; i++)
5126 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005127
5128 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005129 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005130#undef STORECHAR
5131}
5132
Alexander Belopolsky40018472011-02-26 01:02:56 +00005133PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005134PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5135 Py_ssize_t size,
5136 const char *errors,
5137 int byteorder)
5138{
5139 PyObject *result;
5140 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5141 if (tmp == NULL)
5142 return NULL;
5143 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5144 Py_DECREF(tmp);
5145 return result;
5146}
5147
5148PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005149PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005150{
Victor Stinnerb960b342011-11-20 19:12:52 +01005151 return _PyUnicode_EncodeUTF32(unicode, NULL, 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005152}
5153
Guido van Rossumd57fd912000-03-10 22:53:23 +00005154/* --- UTF-16 Codec ------------------------------------------------------- */
5155
Tim Peters772747b2001-08-09 22:21:55 +00005156PyObject *
5157PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005158 Py_ssize_t size,
5159 const char *errors,
5160 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005161{
Walter Dörwald69652032004-09-07 20:24:22 +00005162 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5163}
5164
Antoine Pitrouab868312009-01-10 15:40:25 +00005165/* Two masks for fast checking of whether a C 'long' may contain
5166 UTF16-encoded surrogate characters. This is an efficient heuristic,
5167 assuming that non-surrogate characters with a code point >= 0x8000 are
5168 rare in most input.
5169 FAST_CHAR_MASK is used when the input is in native byte ordering,
5170 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005171*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005172#if (SIZEOF_LONG == 8)
5173# define FAST_CHAR_MASK 0x8000800080008000L
5174# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5175#elif (SIZEOF_LONG == 4)
5176# define FAST_CHAR_MASK 0x80008000L
5177# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5178#else
5179# error C 'long' size should be either 4 or 8!
5180#endif
5181
Walter Dörwald69652032004-09-07 20:24:22 +00005182PyObject *
5183PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005184 Py_ssize_t size,
5185 const char *errors,
5186 int *byteorder,
5187 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005188{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005189 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005190 Py_ssize_t startinpos;
5191 Py_ssize_t endinpos;
5192 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005193 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005194 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005195 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005196 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005197 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005198 /* Offsets from q for retrieving byte pairs in the right order. */
5199#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5200 int ihi = 1, ilo = 0;
5201#else
5202 int ihi = 0, ilo = 1;
5203#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005204 PyObject *errorHandler = NULL;
5205 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005206
5207 /* Note: size will always be longer than the resulting Unicode
5208 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005209 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005210 if (!unicode)
5211 return NULL;
5212 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005213 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005214 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005215
Tim Peters772747b2001-08-09 22:21:55 +00005216 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005217 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005218
5219 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005220 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005221
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005222 /* Check for BOM marks (U+FEFF) in the input and adjust current
5223 byte order setting accordingly. In native mode, the leading BOM
5224 mark is skipped, in all other modes, it is copied to the output
5225 stream as-is (giving a ZWNBSP character). */
5226 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005227 if (size >= 2) {
Victor Stinner24729f32011-11-10 20:31:37 +01005228 const Py_UCS4 bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005229#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005230 if (bom == 0xFEFF) {
5231 q += 2;
5232 bo = -1;
5233 }
5234 else if (bom == 0xFFFE) {
5235 q += 2;
5236 bo = 1;
5237 }
Tim Petersced69f82003-09-16 20:30:58 +00005238#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005239 if (bom == 0xFEFF) {
5240 q += 2;
5241 bo = 1;
5242 }
5243 else if (bom == 0xFFFE) {
5244 q += 2;
5245 bo = -1;
5246 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005247#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005248 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005249 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005250
Tim Peters772747b2001-08-09 22:21:55 +00005251 if (bo == -1) {
5252 /* force LE */
5253 ihi = 1;
5254 ilo = 0;
5255 }
5256 else if (bo == 1) {
5257 /* force BE */
5258 ihi = 0;
5259 ilo = 1;
5260 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005261#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5262 native_ordering = ilo < ihi;
5263#else
5264 native_ordering = ilo > ihi;
5265#endif
Tim Peters772747b2001-08-09 22:21:55 +00005266
Antoine Pitrouab868312009-01-10 15:40:25 +00005267 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005268 while (q < e) {
Victor Stinner24729f32011-11-10 20:31:37 +01005269 Py_UCS4 ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005270 /* First check for possible aligned read of a C 'long'. Unaligned
5271 reads are more expensive, better to defer to another iteration. */
5272 if (!((size_t) q & LONG_PTR_MASK)) {
5273 /* Fast path for runs of non-surrogate chars. */
5274 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005275 int kind = PyUnicode_KIND(unicode);
5276 void *data = PyUnicode_DATA(unicode);
5277 while (_q < aligned_end) {
5278 unsigned long block = * (unsigned long *) _q;
5279 unsigned short *pblock = (unsigned short*)&block;
5280 Py_UCS4 maxch;
5281 if (native_ordering) {
5282 /* Can use buffer directly */
5283 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005284 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005285 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005286 else {
5287 /* Need to byte-swap */
5288 unsigned char *_p = (unsigned char*)pblock;
5289 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005290 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005291 _p[0] = _q[1];
5292 _p[1] = _q[0];
5293 _p[2] = _q[3];
5294 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005295#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005296 _p[4] = _q[5];
5297 _p[5] = _q[4];
5298 _p[6] = _q[7];
5299 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005300#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005301 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005302 maxch = Py_MAX(pblock[0], pblock[1]);
5303#if SIZEOF_LONG == 8
5304 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5305#endif
5306 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5307 if (unicode_widen(&unicode, maxch) < 0)
5308 goto onError;
5309 kind = PyUnicode_KIND(unicode);
5310 data = PyUnicode_DATA(unicode);
5311 }
5312 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5313 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5314#if SIZEOF_LONG == 8
5315 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5316 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5317#endif
5318 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005319 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005320 q = _q;
5321 if (q >= e)
5322 break;
5323 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005324 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005325
Benjamin Peterson14339b62009-01-31 16:36:08 +00005326 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005327
5328 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005329 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5330 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 continue;
5332 }
5333
5334 /* UTF-16 code pair: */
5335 if (q > e) {
5336 errmsg = "unexpected end of data";
5337 startinpos = (((const char *)q) - 2) - starts;
5338 endinpos = ((const char *)e) + 1 - starts;
5339 goto utf16Error;
5340 }
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005341 if (Py_UNICODE_IS_HIGH_SURROGATE(ch)) {
5342 Py_UCS4 ch2 = (q[ihi] << 8) | q[ilo];
Benjamin Peterson29060642009-01-31 22:14:21 +00005343 q += 2;
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005344 if (Py_UNICODE_IS_LOW_SURROGATE(ch2)) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005345 if (unicode_putchar(&unicode, &outpos,
Victor Stinner2e9cfad2011-11-20 18:40:27 +01005346 Py_UNICODE_JOIN_SURROGATES(ch, ch2)) < 0)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005347 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005348 continue;
5349 }
5350 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005351 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005352 startinpos = (((const char *)q)-4)-starts;
5353 endinpos = startinpos+2;
5354 goto utf16Error;
5355 }
5356
Benjamin Peterson14339b62009-01-31 16:36:08 +00005357 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005358 errmsg = "illegal encoding";
5359 startinpos = (((const char *)q)-2)-starts;
5360 endinpos = startinpos+2;
5361 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005362
Benjamin Peterson29060642009-01-31 22:14:21 +00005363 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005364 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005365 errors,
5366 &errorHandler,
5367 "utf16", errmsg,
5368 &starts,
5369 (const char **)&e,
5370 &startinpos,
5371 &endinpos,
5372 &exc,
5373 (const char **)&q,
5374 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005375 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005376 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005377 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005378 /* remaining byte at the end? (size should be even) */
5379 if (e == q) {
5380 if (!consumed) {
5381 errmsg = "truncated data";
5382 startinpos = ((const char *)q) - starts;
5383 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005384 if (unicode_decode_call_errorhandler(
5385 errors,
5386 &errorHandler,
5387 "utf16", errmsg,
5388 &starts,
5389 (const char **)&e,
5390 &startinpos,
5391 &endinpos,
5392 &exc,
5393 (const char **)&q,
5394 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005395 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005396 goto onError;
5397 /* The remaining input chars are ignored if the callback
5398 chooses to skip the input */
5399 }
5400 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005401
5402 if (byteorder)
5403 *byteorder = bo;
5404
Walter Dörwald69652032004-09-07 20:24:22 +00005405 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005406 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005407
Guido van Rossumd57fd912000-03-10 22:53:23 +00005408 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005409 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005410 goto onError;
5411
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005412 Py_XDECREF(errorHandler);
5413 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005414 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005415 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005416
Benjamin Peterson29060642009-01-31 22:14:21 +00005417 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005418 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005419 Py_XDECREF(errorHandler);
5420 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421 return NULL;
5422}
5423
Antoine Pitrouab868312009-01-10 15:40:25 +00005424#undef FAST_CHAR_MASK
5425#undef SWAPPED_FAST_CHAR_MASK
5426
Tim Peters772747b2001-08-09 22:21:55 +00005427PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005428_PyUnicode_EncodeUTF16(PyObject *str,
5429 const char *errors,
5430 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005431{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005432 int kind;
5433 void *data;
5434 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005435 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005436 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005437 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005438 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005439 /* Offsets from p for storing byte pairs in the right order. */
5440#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5441 int ihi = 1, ilo = 0;
5442#else
5443 int ihi = 0, ilo = 1;
5444#endif
5445
Benjamin Peterson29060642009-01-31 22:14:21 +00005446#define STORECHAR(CH) \
5447 do { \
5448 p[ihi] = ((CH) >> 8) & 0xff; \
5449 p[ilo] = (CH) & 0xff; \
5450 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005451 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005452
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005453 if (!PyUnicode_Check(str)) {
5454 PyErr_BadArgument();
5455 return NULL;
5456 }
5457 if (PyUnicode_READY(str) < 0)
5458 return NULL;
5459 kind = PyUnicode_KIND(str);
5460 data = PyUnicode_DATA(str);
5461 len = PyUnicode_GET_LENGTH(str);
Victor Stinner0e368262011-11-10 20:12:49 +01005462
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005463 pairs = 0;
5464 if (kind == PyUnicode_4BYTE_KIND)
5465 for (i = 0; i < len; i++)
5466 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5467 pairs++;
5468 /* 2 * (len + pairs + (byteorder == 0)) */
5469 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005470 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005471 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005472 bytesize = nsize * 2;
5473 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005474 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005475 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005476 if (v == NULL)
5477 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005478
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005479 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005480 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005481 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005482 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005483 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005484
5485 if (byteorder == -1) {
5486 /* force LE */
5487 ihi = 1;
5488 ilo = 0;
5489 }
5490 else if (byteorder == 1) {
5491 /* force BE */
5492 ihi = 0;
5493 ilo = 1;
5494 }
5495
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005496 for (i = 0; i < len; i++) {
5497 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5498 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005499 if (ch >= 0x10000) {
5500 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5501 ch = 0xD800 | ((ch-0x10000) >> 10);
5502 }
Tim Peters772747b2001-08-09 22:21:55 +00005503 STORECHAR(ch);
5504 if (ch2)
5505 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005506 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005507
5508 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005509 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005510#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005511}
5512
Alexander Belopolsky40018472011-02-26 01:02:56 +00005513PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005514PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5515 Py_ssize_t size,
5516 const char *errors,
5517 int byteorder)
5518{
5519 PyObject *result;
5520 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5521 if (tmp == NULL)
5522 return NULL;
5523 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5524 Py_DECREF(tmp);
5525 return result;
5526}
5527
5528PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005529PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005530{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005531 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005532}
5533
5534/* --- Unicode Escape Codec ----------------------------------------------- */
5535
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005536/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5537 if all the escapes in the string make it still a valid ASCII string.
5538 Returns -1 if any escapes were found which cause the string to
5539 pop out of ASCII range. Otherwise returns the length of the
5540 required buffer to hold the string.
5541 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005542static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005543length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5544{
5545 const unsigned char *p = (const unsigned char *)s;
5546 const unsigned char *end = p + size;
5547 Py_ssize_t length = 0;
5548
5549 if (size < 0)
5550 return -1;
5551
5552 for (; p < end; ++p) {
5553 if (*p > 127) {
5554 /* Non-ASCII */
5555 return -1;
5556 }
5557 else if (*p != '\\') {
5558 /* Normal character */
5559 ++length;
5560 }
5561 else {
5562 /* Backslash-escape, check next char */
5563 ++p;
5564 /* Escape sequence reaches till end of string or
5565 non-ASCII follow-up. */
5566 if (p >= end || *p > 127)
5567 return -1;
5568 switch (*p) {
5569 case '\n':
5570 /* backslash + \n result in zero characters */
5571 break;
5572 case '\\': case '\'': case '\"':
5573 case 'b': case 'f': case 't':
5574 case 'n': case 'r': case 'v': case 'a':
5575 ++length;
5576 break;
5577 case '0': case '1': case '2': case '3':
5578 case '4': case '5': case '6': case '7':
5579 case 'x': case 'u': case 'U': case 'N':
5580 /* these do not guarantee ASCII characters */
5581 return -1;
5582 default:
5583 /* count the backslash + the other character */
5584 length += 2;
5585 }
5586 }
5587 }
5588 return length;
5589}
5590
Fredrik Lundh06d12682001-01-24 07:59:11 +00005591static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005592
Alexander Belopolsky40018472011-02-26 01:02:56 +00005593PyObject *
5594PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005595 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005596 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005597{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005598 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005599 Py_ssize_t startinpos;
5600 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005601 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005602 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005603 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005604 char* message;
5605 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005606 PyObject *errorHandler = NULL;
5607 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005608 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005609 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005610
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005611 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005612
5613 /* After length_of_escaped_ascii_string() there are two alternatives,
5614 either the string is pure ASCII with named escapes like \n, etc.
5615 and we determined it's exact size (common case)
5616 or it contains \x, \u, ... escape sequences. then we create a
5617 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005618 if (len >= 0) {
5619 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005620 if (!v)
5621 goto onError;
5622 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005623 }
5624 else {
5625 /* Escaped strings will always be longer than the resulting
5626 Unicode string, so we start with size here and then reduce the
5627 length after conversion to the true value.
5628 (but if the error callback returns a long replacement string
5629 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005630 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005631 if (!v)
5632 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005633 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005634 }
5635
Guido van Rossumd57fd912000-03-10 22:53:23 +00005636 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005637 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005638 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005639 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005640
Guido van Rossumd57fd912000-03-10 22:53:23 +00005641 while (s < end) {
5642 unsigned char c;
Victor Stinner24729f32011-11-10 20:31:37 +01005643 Py_UCS4 x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005644 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005645
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005646 /* The only case in which i == ascii_length is a backslash
5647 followed by a newline. */
5648 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005649
Guido van Rossumd57fd912000-03-10 22:53:23 +00005650 /* Non-escape characters are interpreted as Unicode ordinals */
5651 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005652 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5653 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005654 continue;
5655 }
5656
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005657 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005658 /* \ - Escapes */
5659 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005660 c = *s++;
5661 if (s > end)
5662 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005663
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005664 /* The only case in which i == ascii_length is a backslash
5665 followed by a newline. */
5666 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005667
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005668 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005669
Benjamin Peterson29060642009-01-31 22:14:21 +00005670 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005671#define WRITECHAR(ch) \
5672 do { \
5673 if (unicode_putchar(&v, &i, ch) < 0) \
5674 goto onError; \
5675 }while(0)
5676
Guido van Rossumd57fd912000-03-10 22:53:23 +00005677 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005678 case '\\': WRITECHAR('\\'); break;
5679 case '\'': WRITECHAR('\''); break;
5680 case '\"': WRITECHAR('\"'); break;
5681 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005682 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005683 case 'f': WRITECHAR('\014'); break;
5684 case 't': WRITECHAR('\t'); break;
5685 case 'n': WRITECHAR('\n'); break;
5686 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005687 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005688 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005689 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005690 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005691
Benjamin Peterson29060642009-01-31 22:14:21 +00005692 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005693 case '0': case '1': case '2': case '3':
5694 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005695 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005696 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005697 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005698 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005699 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005700 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005702 break;
5703
Benjamin Peterson29060642009-01-31 22:14:21 +00005704 /* hex escapes */
5705 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005706 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005707 digits = 2;
5708 message = "truncated \\xXX escape";
5709 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005710
Benjamin Peterson29060642009-01-31 22:14:21 +00005711 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005712 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005713 digits = 4;
5714 message = "truncated \\uXXXX escape";
5715 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005716
Benjamin Peterson29060642009-01-31 22:14:21 +00005717 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005718 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005719 digits = 8;
5720 message = "truncated \\UXXXXXXXX escape";
5721 hexescape:
5722 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005723 if (s+digits>end) {
5724 endinpos = size;
5725 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005726 errors, &errorHandler,
5727 "unicodeescape", "end of string in escape sequence",
5728 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005729 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005730 goto onError;
5731 goto nextByte;
5732 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005733 for (j = 0; j < digits; ++j) {
5734 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005735 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005736 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005737 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005738 errors, &errorHandler,
5739 "unicodeescape", message,
5740 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005741 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005742 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005743 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005744 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005745 }
5746 chr = (chr<<4) & ~0xF;
5747 if (c >= '0' && c <= '9')
5748 chr += c - '0';
5749 else if (c >= 'a' && c <= 'f')
5750 chr += 10 + c - 'a';
5751 else
5752 chr += 10 + c - 'A';
5753 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005754 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005755 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 /* _decoding_error will have already written into the
5757 target buffer. */
5758 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005759 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005760 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005761 if (chr <= 0x10ffff) {
5762 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005763 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005764 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005765 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005766 errors, &errorHandler,
5767 "unicodeescape", "illegal Unicode character",
5768 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005769 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005770 goto onError;
5771 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005772 break;
5773
Benjamin Peterson29060642009-01-31 22:14:21 +00005774 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005775 case 'N':
5776 message = "malformed \\N character escape";
5777 if (ucnhash_CAPI == NULL) {
5778 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005779 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5780 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005781 if (ucnhash_CAPI == NULL)
5782 goto ucnhashError;
5783 }
5784 if (*s == '{') {
5785 const char *start = s+1;
5786 /* look for the closing brace */
5787 while (*s != '}' && s < end)
5788 s++;
5789 if (s > start && s < end && *s == '}') {
5790 /* found a name. look it up in the unicode database */
5791 message = "unknown Unicode character name";
5792 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005793 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005794 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005795 goto store;
5796 }
5797 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005798 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005799 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005800 errors, &errorHandler,
5801 "unicodeescape", message,
5802 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005803 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005804 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005805 break;
5806
5807 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005808 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005809 message = "\\ at end of string";
5810 s--;
5811 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005813 errors, &errorHandler,
5814 "unicodeescape", message,
5815 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005816 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005817 goto onError;
5818 }
5819 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005820 WRITECHAR('\\');
5821 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005822 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005823 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005824 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005825 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005826 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005827 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005828#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005829
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005830 if (PyUnicode_Resize(&v, i) < 0)
5831 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005832 Py_XDECREF(errorHandler);
5833 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005834#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005835 if (_PyUnicode_READY_REPLACE(&v)) {
5836 Py_DECREF(v);
5837 return NULL;
5838 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005839#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005840 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005841 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005842
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005844 PyErr_SetString(
5845 PyExc_UnicodeError,
5846 "\\N escapes not supported (can't load unicodedata module)"
5847 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005848 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005849 Py_XDECREF(errorHandler);
5850 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005851 return NULL;
5852
Benjamin Peterson29060642009-01-31 22:14:21 +00005853 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005854 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005855 Py_XDECREF(errorHandler);
5856 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005857 return NULL;
5858}
5859
5860/* Return a Unicode-Escape string version of the Unicode object.
5861
5862 If quotes is true, the string is enclosed in u"" or u'' quotes as
5863 appropriate.
5864
5865*/
5866
Alexander Belopolsky40018472011-02-26 01:02:56 +00005867PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005868PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005869{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005870 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005871 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005873 int kind;
5874 void *data;
5875 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005876
Thomas Wouters89f507f2006-12-13 04:49:30 +00005877 /* Initial allocation is based on the longest-possible unichr
5878 escape.
5879
5880 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5881 unichr, so in this case it's the longest unichr escape. In
5882 narrow (UTF-16) builds this is five chars per source unichr
5883 since there are two unichrs in the surrogate pair, so in narrow
5884 (UTF-16) builds it's not the longest unichr escape.
5885
5886 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5887 so in the narrow (UTF-16) build case it's the longest unichr
5888 escape.
5889 */
5890
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005891 if (!PyUnicode_Check(unicode)) {
5892 PyErr_BadArgument();
5893 return NULL;
5894 }
5895 if (PyUnicode_READY(unicode) < 0)
5896 return NULL;
5897 len = PyUnicode_GET_LENGTH(unicode);
5898 kind = PyUnicode_KIND(unicode);
5899 data = PyUnicode_DATA(unicode);
5900 switch(kind) {
5901 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5902 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5903 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5904 }
5905
5906 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005907 return PyBytes_FromStringAndSize(NULL, 0);
5908
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005909 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005910 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005911
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005912 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005913 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005914 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005915 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005916 if (repr == NULL)
5917 return NULL;
5918
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005919 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005920
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005921 for (i = 0; i < len; i++) {
Victor Stinner3326cb62011-11-10 20:15:25 +01005922 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005923
Walter Dörwald79e913e2007-05-12 11:08:06 +00005924 /* Escape backslashes */
5925 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 *p++ = '\\';
5927 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005928 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005929 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005930
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005931 /* Map 21-bit characters to '\U00xxxxxx' */
5932 else if (ch >= 0x10000) {
5933 *p++ = '\\';
5934 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005935 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5936 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5937 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5938 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5939 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5940 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5941 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5942 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005943 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005944 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005945
Guido van Rossumd57fd912000-03-10 22:53:23 +00005946 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005947 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005948 *p++ = '\\';
5949 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005950 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5951 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5952 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5953 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005954 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005955
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005956 /* Map special whitespace to '\t', \n', '\r' */
5957 else if (ch == '\t') {
5958 *p++ = '\\';
5959 *p++ = 't';
5960 }
5961 else if (ch == '\n') {
5962 *p++ = '\\';
5963 *p++ = 'n';
5964 }
5965 else if (ch == '\r') {
5966 *p++ = '\\';
5967 *p++ = 'r';
5968 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005969
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005970 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005971 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005972 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005973 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005974 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5975 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005976 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005977
Guido van Rossumd57fd912000-03-10 22:53:23 +00005978 /* Copy everything else as-is */
5979 else
5980 *p++ = (char) ch;
5981 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005982
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005983 assert(p - PyBytes_AS_STRING(repr) > 0);
5984 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5985 return NULL;
5986 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005987}
5988
Alexander Belopolsky40018472011-02-26 01:02:56 +00005989PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005990PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
5991 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005992{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005993 PyObject *result;
5994 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5995 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005996 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005997 result = PyUnicode_AsUnicodeEscapeString(tmp);
5998 Py_DECREF(tmp);
5999 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006000}
6001
6002/* --- Raw Unicode Escape Codec ------------------------------------------- */
6003
Alexander Belopolsky40018472011-02-26 01:02:56 +00006004PyObject *
6005PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006006 Py_ssize_t size,
6007 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006009 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006010 Py_ssize_t startinpos;
6011 Py_ssize_t endinpos;
6012 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006013 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006014 const char *end;
6015 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006016 PyObject *errorHandler = NULL;
6017 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006018
Guido van Rossumd57fd912000-03-10 22:53:23 +00006019 /* Escaped strings will always be longer than the resulting
6020 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006021 length after conversion to the true value. (But decoding error
6022 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006023 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006024 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006025 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006026 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006027 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006028 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029 end = s + size;
6030 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006031 unsigned char c;
6032 Py_UCS4 x;
6033 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006034 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035
Benjamin Peterson29060642009-01-31 22:14:21 +00006036 /* Non-escape characters are interpreted as Unicode ordinals */
6037 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006038 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6039 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006040 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006041 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006042 startinpos = s-starts;
6043
6044 /* \u-escapes are only interpreted iff the number of leading
6045 backslashes if odd */
6046 bs = s;
6047 for (;s < end;) {
6048 if (*s != '\\')
6049 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006050 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6051 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006052 }
6053 if (((s - bs) & 1) == 0 ||
6054 s >= end ||
6055 (*s != 'u' && *s != 'U')) {
6056 continue;
6057 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006058 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006059 count = *s=='u' ? 4 : 8;
6060 s++;
6061
6062 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006063 for (x = 0, i = 0; i < count; ++i, ++s) {
6064 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006065 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006066 endinpos = s-starts;
6067 if (unicode_decode_call_errorhandler(
6068 errors, &errorHandler,
6069 "rawunicodeescape", "truncated \\uXXXX",
6070 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006071 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006072 goto onError;
6073 goto nextByte;
6074 }
6075 x = (x<<4) & ~0xF;
6076 if (c >= '0' && c <= '9')
6077 x += c - '0';
6078 else if (c >= 'a' && c <= 'f')
6079 x += 10 + c - 'a';
6080 else
6081 x += 10 + c - 'A';
6082 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006083 if (x <= 0x10ffff) {
6084 if (unicode_putchar(&v, &outpos, x) < 0)
6085 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006086 } else {
6087 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006088 if (unicode_decode_call_errorhandler(
6089 errors, &errorHandler,
6090 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006091 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006092 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006094 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006095 nextByte:
6096 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006098 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006099 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006100 Py_XDECREF(errorHandler);
6101 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006102 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006103 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006104
Benjamin Peterson29060642009-01-31 22:14:21 +00006105 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006106 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006107 Py_XDECREF(errorHandler);
6108 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006109 return NULL;
6110}
6111
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006112
Alexander Belopolsky40018472011-02-26 01:02:56 +00006113PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006114PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006115{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006116 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006117 char *p;
6118 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006119 Py_ssize_t expandsize, pos;
6120 int kind;
6121 void *data;
6122 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006123
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006124 if (!PyUnicode_Check(unicode)) {
6125 PyErr_BadArgument();
6126 return NULL;
6127 }
6128 if (PyUnicode_READY(unicode) < 0)
6129 return NULL;
6130 kind = PyUnicode_KIND(unicode);
6131 data = PyUnicode_DATA(unicode);
6132 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006133
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006134 switch(kind) {
6135 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6136 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6137 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6138 }
Victor Stinner0e368262011-11-10 20:12:49 +01006139
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006140 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006141 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006142
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006143 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144 if (repr == NULL)
6145 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006146 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006147 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006148
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006149 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006150 for (pos = 0; pos < len; pos++) {
6151 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006152 /* Map 32-bit characters to '\Uxxxxxxxx' */
6153 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006154 *p++ = '\\';
6155 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006156 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6157 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6158 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6159 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6160 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6161 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6162 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6163 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006164 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006165 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006166 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006167 *p++ = '\\';
6168 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006169 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6170 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6171 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6172 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006173 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006174 /* Copy everything else as-is */
6175 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006176 *p++ = (char) ch;
6177 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006178
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006179 assert(p > q);
6180 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006181 return NULL;
6182 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183}
6184
Alexander Belopolsky40018472011-02-26 01:02:56 +00006185PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006186PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6187 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006189 PyObject *result;
6190 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6191 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006192 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006193 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6194 Py_DECREF(tmp);
6195 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006196}
6197
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006198/* --- Unicode Internal Codec ------------------------------------------- */
6199
Alexander Belopolsky40018472011-02-26 01:02:56 +00006200PyObject *
6201_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006202 Py_ssize_t size,
6203 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006204{
6205 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006206 Py_ssize_t startinpos;
6207 Py_ssize_t endinpos;
6208 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006209 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006210 const char *end;
6211 const char *reason;
6212 PyObject *errorHandler = NULL;
6213 PyObject *exc = NULL;
6214
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006215 if (PyErr_WarnEx(PyExc_DeprecationWarning,
Ezio Melotti11060a42011-11-16 09:39:10 +02006216 "unicode_internal codec has been deprecated",
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006217 1))
6218 return NULL;
6219
Thomas Wouters89f507f2006-12-13 04:49:30 +00006220 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006221 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006222 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006223 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006224 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006225 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006226 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006227 end = s + size;
6228
6229 while (s < end) {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006230 Py_UNICODE uch;
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006231 Py_UCS4 ch;
6232 /* We copy the raw representation one byte at a time because the
6233 pointer may be unaligned (see test_codeccallbacks). */
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006234 ((char *) &uch)[0] = s[0];
6235 ((char *) &uch)[1] = s[1];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006236#ifdef Py_UNICODE_WIDE
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006237 ((char *) &uch)[2] = s[2];
6238 ((char *) &uch)[3] = s[3];
Antoine Pitrou44c6aff2011-11-11 02:59:42 +01006239#endif
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006240 ch = uch;
6241
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006242 /* We have to sanity check the raw data, otherwise doom looms for
6243 some malformed UCS-4 data. */
6244 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006245#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006246 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006247#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006248 end-s < Py_UNICODE_SIZE
6249 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006250 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006251 startinpos = s - starts;
6252 if (end-s < Py_UNICODE_SIZE) {
6253 endinpos = end-starts;
6254 reason = "truncated input";
6255 }
6256 else {
6257 endinpos = s - starts + Py_UNICODE_SIZE;
6258 reason = "illegal code point (> 0x10FFFF)";
6259 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006260 if (unicode_decode_call_errorhandler(
6261 errors, &errorHandler,
6262 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006263 &starts, &end, &startinpos, &endinpos, &exc, &s,
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006264 &v, &outpos))
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006265 goto onError;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006266 continue;
6267 }
6268
6269 s += Py_UNICODE_SIZE;
6270#ifndef Py_UNICODE_WIDE
6271 if (ch >= 0xD800 && ch <= 0xDBFF && s < end)
6272 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006273 Py_UNICODE uch2;
6274 ((char *) &uch2)[0] = s[0];
6275 ((char *) &uch2)[1] = s[1];
6276 if (uch2 >= 0xDC00 && uch2 <= 0xDFFF)
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006277 {
Antoine Pitrou0290c7a2011-11-11 13:29:12 +01006278 ch = (((uch & 0x3FF)<<10) | (uch2 & 0x3FF)) + 0x10000;
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006279 s += Py_UNICODE_SIZE;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006280 }
6281 }
Victor Stinner9f4b1e92011-11-10 20:56:30 +01006282#endif
6283
6284 if (unicode_putchar(&v, &outpos, ch) < 0)
6285 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006286 }
6287
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006288 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006289 goto onError;
6290 Py_XDECREF(errorHandler);
6291 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006292 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006293 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006294
Benjamin Peterson29060642009-01-31 22:14:21 +00006295 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006296 Py_XDECREF(v);
6297 Py_XDECREF(errorHandler);
6298 Py_XDECREF(exc);
6299 return NULL;
6300}
6301
Guido van Rossumd57fd912000-03-10 22:53:23 +00006302/* --- Latin-1 Codec ------------------------------------------------------ */
6303
Alexander Belopolsky40018472011-02-26 01:02:56 +00006304PyObject *
6305PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006306 Py_ssize_t size,
6307 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006308{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006309 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006310 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006311}
6312
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006313/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006314static void
6315make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006316 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006317 PyObject *unicode,
6318 Py_ssize_t startpos, Py_ssize_t endpos,
6319 const char *reason)
6320{
6321 if (*exceptionObject == NULL) {
6322 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006323 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006324 encoding, unicode, startpos, endpos, reason);
6325 }
6326 else {
6327 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6328 goto onError;
6329 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6330 goto onError;
6331 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6332 goto onError;
6333 return;
6334 onError:
6335 Py_DECREF(*exceptionObject);
6336 *exceptionObject = NULL;
6337 }
6338}
6339
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006340/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006341static void
6342raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006343 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006344 PyObject *unicode,
6345 Py_ssize_t startpos, Py_ssize_t endpos,
6346 const char *reason)
6347{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006348 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006349 encoding, unicode, startpos, endpos, reason);
6350 if (*exceptionObject != NULL)
6351 PyCodec_StrictErrors(*exceptionObject);
6352}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006353
6354/* error handling callback helper:
6355 build arguments, call the callback and check the arguments,
6356 put the result into newpos and return the replacement string, which
6357 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006358static PyObject *
6359unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006360 PyObject **errorHandler,
6361 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006362 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006363 Py_ssize_t startpos, Py_ssize_t endpos,
6364 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006365{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006366 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006367 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006368 PyObject *restuple;
6369 PyObject *resunicode;
6370
6371 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006372 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006374 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006375 }
6376
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006377 if (PyUnicode_READY(unicode) < 0)
6378 return NULL;
6379 len = PyUnicode_GET_LENGTH(unicode);
6380
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006381 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006382 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006383 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006384 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006385
6386 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006387 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006388 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006389 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006390 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006391 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006392 Py_DECREF(restuple);
6393 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006395 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006396 &resunicode, newpos)) {
6397 Py_DECREF(restuple);
6398 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006399 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006400 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6401 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6402 Py_DECREF(restuple);
6403 return NULL;
6404 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006405 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006406 *newpos = len + *newpos;
6407 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006408 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6409 Py_DECREF(restuple);
6410 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006411 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006412 Py_INCREF(resunicode);
6413 Py_DECREF(restuple);
6414 return resunicode;
6415}
6416
Alexander Belopolsky40018472011-02-26 01:02:56 +00006417static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006418unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006419 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006420 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006421{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006422 /* input state */
6423 Py_ssize_t pos=0, size;
6424 int kind;
6425 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 /* output object */
6427 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006428 /* pointer into the output */
6429 char *str;
6430 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006431 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006432 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6433 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006434 PyObject *errorHandler = NULL;
6435 PyObject *exc = NULL;
6436 /* the following variable is used for caching string comparisons
6437 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6438 int known_errorHandler = -1;
6439
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006440 if (PyUnicode_READY(unicode) < 0)
6441 return NULL;
6442 size = PyUnicode_GET_LENGTH(unicode);
6443 kind = PyUnicode_KIND(unicode);
6444 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 /* allocate enough for a simple encoding without
6446 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006447 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006448 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006449 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006450 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006451 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006452 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006453 ressize = size;
6454
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006455 while (pos < size) {
6456 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006457
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 /* can we encode this? */
6459 if (c<limit) {
6460 /* no overflow check, because we know that the space is enough */
6461 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006462 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006463 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 Py_ssize_t requiredsize;
6466 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006467 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006468 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006469 Py_ssize_t collstart = pos;
6470 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006473 ++collend;
6474 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6475 if (known_errorHandler==-1) {
6476 if ((errors==NULL) || (!strcmp(errors, "strict")))
6477 known_errorHandler = 1;
6478 else if (!strcmp(errors, "replace"))
6479 known_errorHandler = 2;
6480 else if (!strcmp(errors, "ignore"))
6481 known_errorHandler = 3;
6482 else if (!strcmp(errors, "xmlcharrefreplace"))
6483 known_errorHandler = 4;
6484 else
6485 known_errorHandler = 0;
6486 }
6487 switch (known_errorHandler) {
6488 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006489 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006490 goto onError;
6491 case 2: /* replace */
6492 while (collstart++<collend)
6493 *str++ = '?'; /* fall through */
6494 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006495 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006496 break;
6497 case 4: /* xmlcharrefreplace */
6498 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006499 /* determine replacement size */
6500 for (i = collstart, repsize = 0; i < collend; ++i) {
6501 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6502 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006504 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006505 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006510#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 else
6512 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006513#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006516 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006517 repsize += 2+6+1;
6518 else
6519 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006520#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006521 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006522 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006523 if (requiredsize > ressize) {
6524 if (requiredsize<2*ressize)
6525 requiredsize = 2*ressize;
6526 if (_PyBytes_Resize(&res, requiredsize))
6527 goto onError;
6528 str = PyBytes_AS_STRING(res) + respos;
6529 ressize = requiredsize;
6530 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 /* generate replacement */
6532 for (i = collstart; i < collend; ++i) {
6533 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006534 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006536 break;
6537 default:
6538 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006539 encoding, reason, unicode, &exc,
6540 collstart, collend, &newpos);
6541 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6542 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006543 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006544 if (PyBytes_Check(repunicode)) {
6545 /* Directly copy bytes result to output. */
6546 repsize = PyBytes_Size(repunicode);
6547 if (repsize > 1) {
6548 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006549 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006550 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6551 Py_DECREF(repunicode);
6552 goto onError;
6553 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006554 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006555 ressize += repsize-1;
6556 }
6557 memcpy(str, PyBytes_AsString(repunicode), repsize);
6558 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006559 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006560 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006561 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006562 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006563 /* need more space? (at least enough for what we
6564 have+the replacement+the rest of the string, so
6565 we won't have to check space for encodable characters) */
6566 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006567 repsize = PyUnicode_GET_LENGTH(repunicode);
6568 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006569 if (requiredsize > ressize) {
6570 if (requiredsize<2*ressize)
6571 requiredsize = 2*ressize;
6572 if (_PyBytes_Resize(&res, requiredsize)) {
6573 Py_DECREF(repunicode);
6574 goto onError;
6575 }
6576 str = PyBytes_AS_STRING(res) + respos;
6577 ressize = requiredsize;
6578 }
6579 /* check if there is anything unencodable in the replacement
6580 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006581 for (i = 0; repsize-->0; ++i, ++str) {
6582 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006583 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006584 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006585 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006586 Py_DECREF(repunicode);
6587 goto onError;
6588 }
6589 *str = (char)c;
6590 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006591 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006592 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006593 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006594 }
6595 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006596 /* Resize if we allocated to much */
6597 size = str - PyBytes_AS_STRING(res);
6598 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006599 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006600 if (_PyBytes_Resize(&res, size) < 0)
6601 goto onError;
6602 }
6603
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006604 Py_XDECREF(errorHandler);
6605 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006606 return res;
6607
6608 onError:
6609 Py_XDECREF(res);
6610 Py_XDECREF(errorHandler);
6611 Py_XDECREF(exc);
6612 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006613}
6614
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006615/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006616PyObject *
6617PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006618 Py_ssize_t size,
6619 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006621 PyObject *result;
6622 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6623 if (unicode == NULL)
6624 return NULL;
6625 result = unicode_encode_ucs1(unicode, errors, 256);
6626 Py_DECREF(unicode);
6627 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628}
6629
Alexander Belopolsky40018472011-02-26 01:02:56 +00006630PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006631_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006632{
6633 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006634 PyErr_BadArgument();
6635 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006636 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006637 if (PyUnicode_READY(unicode) == -1)
6638 return NULL;
6639 /* Fast path: if it is a one-byte string, construct
6640 bytes object directly. */
6641 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6642 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6643 PyUnicode_GET_LENGTH(unicode));
6644 /* Non-Latin-1 characters present. Defer to above function to
6645 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006646 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006647}
6648
6649PyObject*
6650PyUnicode_AsLatin1String(PyObject *unicode)
6651{
6652 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653}
6654
6655/* --- 7-bit ASCII Codec -------------------------------------------------- */
6656
Alexander Belopolsky40018472011-02-26 01:02:56 +00006657PyObject *
6658PyUnicode_DecodeASCII(const char *s,
6659 Py_ssize_t size,
6660 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006661{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006662 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006663 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006664 int kind;
6665 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006666 Py_ssize_t startinpos;
6667 Py_ssize_t endinpos;
6668 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006669 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006670 int has_error;
6671 const unsigned char *p = (const unsigned char *)s;
6672 const unsigned char *end = p + size;
6673 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006674 PyObject *errorHandler = NULL;
6675 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006676
Guido van Rossumd57fd912000-03-10 22:53:23 +00006677 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006678 if (size == 1 && (unsigned char)s[0] < 128)
6679 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006680
Victor Stinner702c7342011-10-05 13:50:52 +02006681 has_error = 0;
6682 while (p < end && !has_error) {
6683 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6684 an explanation. */
6685 if (!((size_t) p & LONG_PTR_MASK)) {
6686 /* Help register allocation */
6687 register const unsigned char *_p = p;
6688 while (_p < aligned_end) {
6689 unsigned long value = *(unsigned long *) _p;
6690 if (value & ASCII_CHAR_MASK) {
6691 has_error = 1;
6692 break;
6693 }
6694 _p += SIZEOF_LONG;
6695 }
6696 if (_p == end)
6697 break;
6698 if (has_error)
6699 break;
6700 p = _p;
6701 }
6702 if (*p & 0x80) {
6703 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006704 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006705 }
6706 else {
6707 ++p;
6708 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006709 }
Victor Stinner702c7342011-10-05 13:50:52 +02006710 if (!has_error)
6711 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006712
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006713 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006714 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006716 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006717 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006718 kind = PyUnicode_KIND(v);
6719 data = PyUnicode_DATA(v);
6720 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006721 e = s + size;
6722 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 register unsigned char c = (unsigned char)*s;
6724 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006725 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006726 ++s;
6727 }
6728 else {
6729 startinpos = s-starts;
6730 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 if (unicode_decode_call_errorhandler(
6732 errors, &errorHandler,
6733 "ascii", "ordinal not in range(128)",
6734 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006735 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006736 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006737 kind = PyUnicode_KIND(v);
6738 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006739 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006740 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006741 if (PyUnicode_Resize(&v, outpos) < 0)
6742 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006743 Py_XDECREF(errorHandler);
6744 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006745 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006746 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006747
Benjamin Peterson29060642009-01-31 22:14:21 +00006748 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006749 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006750 Py_XDECREF(errorHandler);
6751 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752 return NULL;
6753}
6754
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006755/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006756PyObject *
6757PyUnicode_EncodeASCII(const Py_UNICODE *p,
6758 Py_ssize_t size,
6759 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006761 PyObject *result;
6762 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6763 if (unicode == NULL)
6764 return NULL;
6765 result = unicode_encode_ucs1(unicode, errors, 128);
6766 Py_DECREF(unicode);
6767 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768}
6769
Alexander Belopolsky40018472011-02-26 01:02:56 +00006770PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006771_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006772{
6773 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006774 PyErr_BadArgument();
6775 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006776 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777 if (PyUnicode_READY(unicode) == -1)
6778 return NULL;
6779 /* Fast path: if it is an ASCII-only string, construct bytes object
6780 directly. Else defer to above function to raise the exception. */
6781 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6782 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6783 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006784 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006785}
6786
6787PyObject *
6788PyUnicode_AsASCIIString(PyObject *unicode)
6789{
6790 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006791}
6792
Victor Stinner99b95382011-07-04 14:23:54 +02006793#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006794
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006795/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006796
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006797#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006798#define NEED_RETRY
6799#endif
6800
Victor Stinner3a50e702011-10-18 21:21:00 +02006801#ifndef WC_ERR_INVALID_CHARS
6802# define WC_ERR_INVALID_CHARS 0x0080
6803#endif
6804
6805static char*
6806code_page_name(UINT code_page, PyObject **obj)
6807{
6808 *obj = NULL;
6809 if (code_page == CP_ACP)
6810 return "mbcs";
6811 if (code_page == CP_UTF7)
6812 return "CP_UTF7";
6813 if (code_page == CP_UTF8)
6814 return "CP_UTF8";
6815
6816 *obj = PyBytes_FromFormat("cp%u", code_page);
6817 if (*obj == NULL)
6818 return NULL;
6819 return PyBytes_AS_STRING(*obj);
6820}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006821
Alexander Belopolsky40018472011-02-26 01:02:56 +00006822static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006823is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006824{
6825 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006826 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006827
Victor Stinner3a50e702011-10-18 21:21:00 +02006828 if (!IsDBCSLeadByteEx(code_page, *curr))
6829 return 0;
6830
6831 prev = CharPrevExA(code_page, s, curr, 0);
6832 if (prev == curr)
6833 return 1;
6834 /* FIXME: This code is limited to "true" double-byte encodings,
6835 as it assumes an incomplete character consists of a single
6836 byte. */
6837 if (curr - prev == 2)
6838 return 1;
6839 if (!IsDBCSLeadByteEx(code_page, *prev))
6840 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006841 return 0;
6842}
6843
Victor Stinner3a50e702011-10-18 21:21:00 +02006844static DWORD
6845decode_code_page_flags(UINT code_page)
6846{
6847 if (code_page == CP_UTF7) {
6848 /* The CP_UTF7 decoder only supports flags=0 */
6849 return 0;
6850 }
6851 else
6852 return MB_ERR_INVALID_CHARS;
6853}
6854
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006855/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006856 * Decode a byte string from a Windows code page into unicode object in strict
6857 * mode.
6858 *
6859 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6860 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006861 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006862static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006863decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006864 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 const char *in,
6866 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006867{
Victor Stinner3a50e702011-10-18 21:21:00 +02006868 const DWORD flags = decode_code_page_flags(code_page);
Victor Stinner24729f32011-11-10 20:31:37 +01006869 wchar_t *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02006870 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006871
6872 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006873 assert(insize > 0);
6874 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6875 if (outsize <= 0)
6876 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006877
6878 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006879 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006880 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 if (*v == NULL)
6882 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006883 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006884 }
6885 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006886 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006887 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006888 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006889 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006890 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006891 }
6892
6893 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006894 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6895 if (outsize <= 0)
6896 goto error;
6897 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006898
Victor Stinner3a50e702011-10-18 21:21:00 +02006899error:
6900 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6901 return -2;
6902 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006903 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006904}
6905
Victor Stinner3a50e702011-10-18 21:21:00 +02006906/*
6907 * Decode a byte string from a code page into unicode object with an error
6908 * handler.
6909 *
6910 * Returns consumed size if succeed, or raise a WindowsError or
6911 * UnicodeDecodeError exception and returns -1 on error.
6912 */
6913static int
6914decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006915 PyObject **v,
6916 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006917 const char *errors)
6918{
6919 const char *startin = in;
6920 const char *endin = in + size;
6921 const DWORD flags = decode_code_page_flags(code_page);
6922 /* Ideally, we should get reason from FormatMessage. This is the Windows
6923 2000 English version of the message. */
6924 const char *reason = "No mapping for the Unicode character exists "
6925 "in the target code page.";
6926 /* each step cannot decode more than 1 character, but a character can be
6927 represented as a surrogate pair */
6928 wchar_t buffer[2], *startout, *out;
6929 int insize, outsize;
6930 PyObject *errorHandler = NULL;
6931 PyObject *exc = NULL;
6932 PyObject *encoding_obj = NULL;
6933 char *encoding;
6934 DWORD err;
6935 int ret = -1;
6936
6937 assert(size > 0);
6938
6939 encoding = code_page_name(code_page, &encoding_obj);
6940 if (encoding == NULL)
6941 return -1;
6942
6943 if (errors == NULL || strcmp(errors, "strict") == 0) {
6944 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6945 UnicodeDecodeError. */
6946 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6947 if (exc != NULL) {
6948 PyCodec_StrictErrors(exc);
6949 Py_CLEAR(exc);
6950 }
6951 goto error;
6952 }
6953
6954 if (*v == NULL) {
6955 /* Create unicode object */
6956 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6957 PyErr_NoMemory();
6958 goto error;
6959 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006960 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006961 if (*v == NULL)
6962 goto error;
6963 startout = PyUnicode_AS_UNICODE(*v);
6964 }
6965 else {
6966 /* Extend unicode object */
6967 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6968 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6969 PyErr_NoMemory();
6970 goto error;
6971 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006972 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006973 goto error;
6974 startout = PyUnicode_AS_UNICODE(*v) + n;
6975 }
6976
6977 /* Decode the byte string character per character */
6978 out = startout;
6979 while (in < endin)
6980 {
6981 /* Decode a character */
6982 insize = 1;
6983 do
6984 {
6985 outsize = MultiByteToWideChar(code_page, flags,
6986 in, insize,
6987 buffer, Py_ARRAY_LENGTH(buffer));
6988 if (outsize > 0)
6989 break;
6990 err = GetLastError();
6991 if (err != ERROR_NO_UNICODE_TRANSLATION
6992 && err != ERROR_INSUFFICIENT_BUFFER)
6993 {
6994 PyErr_SetFromWindowsErr(0);
6995 goto error;
6996 }
6997 insize++;
6998 }
6999 /* 4=maximum length of a UTF-8 sequence */
7000 while (insize <= 4 && (in + insize) <= endin);
7001
7002 if (outsize <= 0) {
7003 Py_ssize_t startinpos, endinpos, outpos;
7004
7005 startinpos = in - startin;
7006 endinpos = startinpos + 1;
7007 outpos = out - PyUnicode_AS_UNICODE(*v);
7008 if (unicode_decode_call_errorhandler(
7009 errors, &errorHandler,
7010 encoding, reason,
7011 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007012 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007013 {
7014 goto error;
7015 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007016 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 }
7018 else {
7019 in += insize;
7020 memcpy(out, buffer, outsize * sizeof(wchar_t));
7021 out += outsize;
7022 }
7023 }
7024
7025 /* write a NUL character at the end */
7026 *out = 0;
7027
7028 /* Extend unicode object */
7029 outsize = out - startout;
7030 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007031 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007032 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007033 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007034
7035error:
7036 Py_XDECREF(encoding_obj);
7037 Py_XDECREF(errorHandler);
7038 Py_XDECREF(exc);
7039 return ret;
7040}
7041
Victor Stinner3a50e702011-10-18 21:21:00 +02007042static PyObject *
7043decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007044 const char *s, Py_ssize_t size,
7045 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007046{
Victor Stinner76a31a62011-11-04 00:05:13 +01007047 PyObject *v = NULL;
7048 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049
Victor Stinner3a50e702011-10-18 21:21:00 +02007050 if (code_page < 0) {
7051 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7052 return NULL;
7053 }
7054
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007055 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007056 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007057
Victor Stinner76a31a62011-11-04 00:05:13 +01007058 do
7059 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007060#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007061 if (size > INT_MAX) {
7062 chunk_size = INT_MAX;
7063 final = 0;
7064 done = 0;
7065 }
7066 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007067#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007068 {
7069 chunk_size = (int)size;
7070 final = (consumed == NULL);
7071 done = 1;
7072 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007073
Victor Stinner76a31a62011-11-04 00:05:13 +01007074 /* Skip trailing lead-byte unless 'final' is set */
7075 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7076 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007077
Victor Stinner76a31a62011-11-04 00:05:13 +01007078 if (chunk_size == 0 && done) {
7079 if (v != NULL)
7080 break;
7081 Py_INCREF(unicode_empty);
7082 return unicode_empty;
7083 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007084
Victor Stinner76a31a62011-11-04 00:05:13 +01007085
7086 converted = decode_code_page_strict(code_page, &v,
7087 s, chunk_size);
7088 if (converted == -2)
7089 converted = decode_code_page_errors(code_page, &v,
7090 s, chunk_size,
7091 errors);
7092 assert(converted != 0);
7093
7094 if (converted < 0) {
7095 Py_XDECREF(v);
7096 return NULL;
7097 }
7098
7099 if (consumed)
7100 *consumed += converted;
7101
7102 s += converted;
7103 size -= converted;
7104 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007105
Victor Stinner17efeed2011-10-04 20:05:46 +02007106#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007107 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007108 Py_DECREF(v);
7109 return NULL;
7110 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007111#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007112 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007113 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007114}
7115
Alexander Belopolsky40018472011-02-26 01:02:56 +00007116PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007117PyUnicode_DecodeCodePageStateful(int code_page,
7118 const char *s,
7119 Py_ssize_t size,
7120 const char *errors,
7121 Py_ssize_t *consumed)
7122{
7123 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7124}
7125
7126PyObject *
7127PyUnicode_DecodeMBCSStateful(const char *s,
7128 Py_ssize_t size,
7129 const char *errors,
7130 Py_ssize_t *consumed)
7131{
7132 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7133}
7134
7135PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007136PyUnicode_DecodeMBCS(const char *s,
7137 Py_ssize_t size,
7138 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007139{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007140 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7141}
7142
Victor Stinner3a50e702011-10-18 21:21:00 +02007143static DWORD
7144encode_code_page_flags(UINT code_page, const char *errors)
7145{
7146 if (code_page == CP_UTF8) {
7147 if (winver.dwMajorVersion >= 6)
7148 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7149 and later */
7150 return WC_ERR_INVALID_CHARS;
7151 else
7152 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7153 return 0;
7154 }
7155 else if (code_page == CP_UTF7) {
7156 /* CP_UTF7 only supports flags=0 */
7157 return 0;
7158 }
7159 else {
7160 if (errors != NULL && strcmp(errors, "replace") == 0)
7161 return 0;
7162 else
7163 return WC_NO_BEST_FIT_CHARS;
7164 }
7165}
7166
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007167/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007168 * Encode a Unicode string to a Windows code page into a byte string in strict
7169 * mode.
7170 *
7171 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7172 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007173 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007174static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007175encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007176 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007178{
Victor Stinner554f3f02010-06-16 23:33:54 +00007179 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007180 BOOL *pusedDefaultChar = &usedDefaultChar;
7181 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007182 PyObject *exc = NULL;
Victor Stinner24729f32011-11-10 20:31:37 +01007183 wchar_t *p;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007184 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 const DWORD flags = encode_code_page_flags(code_page, NULL);
7186 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007187 /* Create a substring so that we can get the UTF-16 representation
7188 of just the slice under consideration. */
7189 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007190
Martin v. Löwis3d325192011-11-04 18:23:06 +01007191 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007192
Victor Stinner3a50e702011-10-18 21:21:00 +02007193 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007194 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007195 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007196 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007197
Victor Stinner2fc507f2011-11-04 20:06:39 +01007198 substring = PyUnicode_Substring(unicode, offset, offset+len);
7199 if (substring == NULL)
7200 return -1;
7201 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7202 if (p == NULL) {
7203 Py_DECREF(substring);
7204 return -1;
7205 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007206
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007207 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007208 outsize = WideCharToMultiByte(code_page, flags,
7209 p, size,
7210 NULL, 0,
7211 NULL, pusedDefaultChar);
7212 if (outsize <= 0)
7213 goto error;
7214 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007215 if (pusedDefaultChar && *pusedDefaultChar) {
7216 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007218 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007219
Victor Stinner3a50e702011-10-18 21:21:00 +02007220 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007221 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007222 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007223 if (*outbytes == NULL) {
7224 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007225 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007226 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007227 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007228 }
7229 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007230 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 const Py_ssize_t n = PyBytes_Size(*outbytes);
7232 if (outsize > PY_SSIZE_T_MAX - n) {
7233 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007234 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007235 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007236 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007237 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7238 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007239 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007240 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007241 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007242 }
7243
7244 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007245 outsize = WideCharToMultiByte(code_page, flags,
7246 p, size,
7247 out, outsize,
7248 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007249 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 if (outsize <= 0)
7251 goto error;
7252 if (pusedDefaultChar && *pusedDefaultChar)
7253 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007254 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007257 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007258 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7259 return -2;
7260 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007261 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007262}
7263
Victor Stinner3a50e702011-10-18 21:21:00 +02007264/*
7265 * Encode a Unicode string to a Windows code page into a byte string using a
7266 * error handler.
7267 *
7268 * Returns consumed characters if succeed, or raise a WindowsError and returns
7269 * -1 on other error.
7270 */
7271static int
7272encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007273 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007274 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007275{
Victor Stinner3a50e702011-10-18 21:21:00 +02007276 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007277 Py_ssize_t pos = unicode_offset;
7278 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007279 /* Ideally, we should get reason from FormatMessage. This is the Windows
7280 2000 English version of the message. */
7281 const char *reason = "invalid character";
7282 /* 4=maximum length of a UTF-8 sequence */
7283 char buffer[4];
7284 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7285 Py_ssize_t outsize;
7286 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007287 PyObject *errorHandler = NULL;
7288 PyObject *exc = NULL;
7289 PyObject *encoding_obj = NULL;
7290 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007291 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007292 PyObject *rep;
7293 int ret = -1;
7294
7295 assert(insize > 0);
7296
7297 encoding = code_page_name(code_page, &encoding_obj);
7298 if (encoding == NULL)
7299 return -1;
7300
7301 if (errors == NULL || strcmp(errors, "strict") == 0) {
7302 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7303 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007304 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007305 if (exc != NULL) {
7306 PyCodec_StrictErrors(exc);
7307 Py_DECREF(exc);
7308 }
7309 Py_XDECREF(encoding_obj);
7310 return -1;
7311 }
7312
7313 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7314 pusedDefaultChar = &usedDefaultChar;
7315 else
7316 pusedDefaultChar = NULL;
7317
7318 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7319 PyErr_NoMemory();
7320 goto error;
7321 }
7322 outsize = insize * Py_ARRAY_LENGTH(buffer);
7323
7324 if (*outbytes == NULL) {
7325 /* Create string object */
7326 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7327 if (*outbytes == NULL)
7328 goto error;
7329 out = PyBytes_AS_STRING(*outbytes);
7330 }
7331 else {
7332 /* Extend string object */
7333 Py_ssize_t n = PyBytes_Size(*outbytes);
7334 if (n > PY_SSIZE_T_MAX - outsize) {
7335 PyErr_NoMemory();
7336 goto error;
7337 }
7338 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7339 goto error;
7340 out = PyBytes_AS_STRING(*outbytes) + n;
7341 }
7342
7343 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007344 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007346 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7347 wchar_t chars[2];
7348 int charsize;
7349 if (ch < 0x10000) {
7350 chars[0] = (wchar_t)ch;
7351 charsize = 1;
7352 }
7353 else {
7354 ch -= 0x10000;
7355 chars[0] = 0xd800 + (ch >> 10);
7356 chars[1] = 0xdc00 + (ch & 0x3ff);
7357 charsize = 2;
7358 }
7359
Victor Stinner3a50e702011-10-18 21:21:00 +02007360 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007361 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007362 buffer, Py_ARRAY_LENGTH(buffer),
7363 NULL, pusedDefaultChar);
7364 if (outsize > 0) {
7365 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7366 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007367 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007368 memcpy(out, buffer, outsize);
7369 out += outsize;
7370 continue;
7371 }
7372 }
7373 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7374 PyErr_SetFromWindowsErr(0);
7375 goto error;
7376 }
7377
Victor Stinner3a50e702011-10-18 21:21:00 +02007378 rep = unicode_encode_call_errorhandler(
7379 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007380 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007381 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007382 if (rep == NULL)
7383 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007384 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007385
7386 if (PyBytes_Check(rep)) {
7387 outsize = PyBytes_GET_SIZE(rep);
7388 if (outsize != 1) {
7389 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7390 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7391 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7392 Py_DECREF(rep);
7393 goto error;
7394 }
7395 out = PyBytes_AS_STRING(*outbytes) + offset;
7396 }
7397 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7398 out += outsize;
7399 }
7400 else {
7401 Py_ssize_t i;
7402 enum PyUnicode_Kind kind;
7403 void *data;
7404
7405 if (PyUnicode_READY(rep) < 0) {
7406 Py_DECREF(rep);
7407 goto error;
7408 }
7409
7410 outsize = PyUnicode_GET_LENGTH(rep);
7411 if (outsize != 1) {
7412 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7413 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7414 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7415 Py_DECREF(rep);
7416 goto error;
7417 }
7418 out = PyBytes_AS_STRING(*outbytes) + offset;
7419 }
7420 kind = PyUnicode_KIND(rep);
7421 data = PyUnicode_DATA(rep);
7422 for (i=0; i < outsize; i++) {
7423 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7424 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007425 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007426 encoding, unicode,
7427 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007428 "unable to encode error handler result to ASCII");
7429 Py_DECREF(rep);
7430 goto error;
7431 }
7432 *out = (unsigned char)ch;
7433 out++;
7434 }
7435 }
7436 Py_DECREF(rep);
7437 }
7438 /* write a NUL byte */
7439 *out = 0;
7440 outsize = out - PyBytes_AS_STRING(*outbytes);
7441 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7442 if (_PyBytes_Resize(outbytes, outsize) < 0)
7443 goto error;
7444 ret = 0;
7445
7446error:
7447 Py_XDECREF(encoding_obj);
7448 Py_XDECREF(errorHandler);
7449 Py_XDECREF(exc);
7450 return ret;
7451}
7452
Victor Stinner3a50e702011-10-18 21:21:00 +02007453static PyObject *
7454encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007455 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007456 const char *errors)
7457{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007458 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007460 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007461 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007462
Victor Stinner2fc507f2011-11-04 20:06:39 +01007463 if (PyUnicode_READY(unicode) < 0)
7464 return NULL;
7465 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007466
Victor Stinner3a50e702011-10-18 21:21:00 +02007467 if (code_page < 0) {
7468 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7469 return NULL;
7470 }
7471
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007473 return PyBytes_FromStringAndSize(NULL, 0);
7474
Victor Stinner7581cef2011-11-03 22:32:33 +01007475 offset = 0;
7476 do
7477 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007478#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007479 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007480 chunks. */
7481 if (len > INT_MAX/2) {
7482 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007483 done = 0;
7484 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007485 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007486#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007487 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007488 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007489 done = 1;
7490 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007491
Victor Stinner76a31a62011-11-04 00:05:13 +01007492 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007493 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007494 errors);
7495 if (ret == -2)
7496 ret = encode_code_page_errors(code_page, &outbytes,
7497 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007498 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007499 if (ret < 0) {
7500 Py_XDECREF(outbytes);
7501 return NULL;
7502 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007503
Victor Stinner7581cef2011-11-03 22:32:33 +01007504 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007505 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007506 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007507
Victor Stinner3a50e702011-10-18 21:21:00 +02007508 return outbytes;
7509}
7510
7511PyObject *
7512PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7513 Py_ssize_t size,
7514 const char *errors)
7515{
Victor Stinner7581cef2011-11-03 22:32:33 +01007516 PyObject *unicode, *res;
7517 unicode = PyUnicode_FromUnicode(p, size);
7518 if (unicode == NULL)
7519 return NULL;
7520 res = encode_code_page(CP_ACP, unicode, errors);
7521 Py_DECREF(unicode);
7522 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007523}
7524
7525PyObject *
7526PyUnicode_EncodeCodePage(int code_page,
7527 PyObject *unicode,
7528 const char *errors)
7529{
Victor Stinner7581cef2011-11-03 22:32:33 +01007530 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007531}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007532
Alexander Belopolsky40018472011-02-26 01:02:56 +00007533PyObject *
7534PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007535{
7536 if (!PyUnicode_Check(unicode)) {
7537 PyErr_BadArgument();
7538 return NULL;
7539 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007540 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007541}
7542
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007543#undef NEED_RETRY
7544
Victor Stinner99b95382011-07-04 14:23:54 +02007545#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007546
Guido van Rossumd57fd912000-03-10 22:53:23 +00007547/* --- Character Mapping Codec -------------------------------------------- */
7548
Alexander Belopolsky40018472011-02-26 01:02:56 +00007549PyObject *
7550PyUnicode_DecodeCharmap(const char *s,
7551 Py_ssize_t size,
7552 PyObject *mapping,
7553 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007554{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007555 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007556 Py_ssize_t startinpos;
7557 Py_ssize_t endinpos;
7558 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007559 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007560 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007561 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007562 PyObject *errorHandler = NULL;
7563 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00007564
Guido van Rossumd57fd912000-03-10 22:53:23 +00007565 /* Default to Latin-1 */
7566 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007567 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007568
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007569 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007570 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007571 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007572 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007573 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007574 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007575 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007576 if (PyUnicode_CheckExact(mapping)) {
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007577 Py_ssize_t maplen;
7578 enum PyUnicode_Kind kind;
7579 void *data;
7580 Py_UCS4 x;
7581
7582 if (PyUnicode_READY(mapping) < 0)
7583 return NULL;
7584
7585 maplen = PyUnicode_GET_LENGTH(mapping);
7586 data = PyUnicode_DATA(mapping);
7587 kind = PyUnicode_KIND(mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007588 while (s < e) {
7589 unsigned char ch = *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007590
Benjamin Peterson29060642009-01-31 22:14:21 +00007591 if (ch < maplen)
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007592 x = PyUnicode_READ(kind, data, ch);
7593 else
7594 x = 0xfffe; /* invalid value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007595
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007596 if (x == 0xfffe)
7597 {
Benjamin Peterson29060642009-01-31 22:14:21 +00007598 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007599 startinpos = s-starts;
7600 endinpos = startinpos+1;
7601 if (unicode_decode_call_errorhandler(
7602 errors, &errorHandler,
7603 "charmap", "character maps to <undefined>",
7604 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007605 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007606 goto onError;
7607 }
7608 continue;
7609 }
Victor Stinnerebf3ba82011-11-10 20:30:22 +01007610
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007611 if (unicode_putchar(&v, &outpos, x) < 0)
7612 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007613 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007614 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007615 }
7616 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007617 while (s < e) {
7618 unsigned char ch = *s;
7619 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007620
Benjamin Peterson29060642009-01-31 22:14:21 +00007621 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7622 w = PyLong_FromLong((long)ch);
7623 if (w == NULL)
7624 goto onError;
7625 x = PyObject_GetItem(mapping, w);
7626 Py_DECREF(w);
7627 if (x == NULL) {
7628 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7629 /* No mapping found means: mapping is undefined. */
7630 PyErr_Clear();
7631 x = Py_None;
7632 Py_INCREF(x);
7633 } else
7634 goto onError;
7635 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007636
Benjamin Peterson29060642009-01-31 22:14:21 +00007637 /* Apply mapping */
7638 if (PyLong_Check(x)) {
7639 long value = PyLong_AS_LONG(x);
7640 if (value < 0 || value > 65535) {
7641 PyErr_SetString(PyExc_TypeError,
7642 "character mapping must be in range(65536)");
7643 Py_DECREF(x);
7644 goto onError;
7645 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007646 if (unicode_putchar(&v, &outpos, value) < 0)
7647 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007648 }
7649 else if (x == Py_None) {
7650 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007651 startinpos = s-starts;
7652 endinpos = startinpos+1;
7653 if (unicode_decode_call_errorhandler(
7654 errors, &errorHandler,
7655 "charmap", "character maps to <undefined>",
7656 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007657 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007658 Py_DECREF(x);
7659 goto onError;
7660 }
7661 Py_DECREF(x);
7662 continue;
7663 }
7664 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007665 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007666
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007667 if (PyUnicode_READY(x) < 0)
7668 goto onError;
7669 targetsize = PyUnicode_GET_LENGTH(x);
7670
7671 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007672 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007673 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007674 PyUnicode_READ_CHAR(x, 0)) < 0)
7675 goto onError;
7676 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007677 else if (targetsize > 1) {
7678 /* 1-n mapping */
7679 if (targetsize > extrachars) {
7680 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007681 Py_ssize_t needed = (targetsize - extrachars) + \
7682 (targetsize << 2);
7683 extrachars += needed;
7684 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007685 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007686 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007687 Py_DECREF(x);
7688 goto onError;
7689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007690 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007691 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7692 goto onError;
7693 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7694 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007695 extrachars -= targetsize;
7696 }
7697 /* 1-0 mapping: skip the character */
7698 }
7699 else {
7700 /* wrong return value */
7701 PyErr_SetString(PyExc_TypeError,
7702 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007703 Py_DECREF(x);
7704 goto onError;
7705 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007706 Py_DECREF(x);
7707 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007708 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007709 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007710 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007711 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007712 Py_XDECREF(errorHandler);
7713 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007714 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007715 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007716
Benjamin Peterson29060642009-01-31 22:14:21 +00007717 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007718 Py_XDECREF(errorHandler);
7719 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007720 Py_XDECREF(v);
7721 return NULL;
7722}
7723
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007724/* Charmap encoding: the lookup table */
7725
Alexander Belopolsky40018472011-02-26 01:02:56 +00007726struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007727 PyObject_HEAD
7728 unsigned char level1[32];
7729 int count2, count3;
7730 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007731};
7732
7733static PyObject*
7734encoding_map_size(PyObject *obj, PyObject* args)
7735{
7736 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007737 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007738 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007739}
7740
7741static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007742 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007743 PyDoc_STR("Return the size (in bytes) of this object") },
7744 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007745};
7746
7747static void
7748encoding_map_dealloc(PyObject* o)
7749{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007750 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007751}
7752
7753static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007754 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007755 "EncodingMap", /*tp_name*/
7756 sizeof(struct encoding_map), /*tp_basicsize*/
7757 0, /*tp_itemsize*/
7758 /* methods */
7759 encoding_map_dealloc, /*tp_dealloc*/
7760 0, /*tp_print*/
7761 0, /*tp_getattr*/
7762 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007763 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007764 0, /*tp_repr*/
7765 0, /*tp_as_number*/
7766 0, /*tp_as_sequence*/
7767 0, /*tp_as_mapping*/
7768 0, /*tp_hash*/
7769 0, /*tp_call*/
7770 0, /*tp_str*/
7771 0, /*tp_getattro*/
7772 0, /*tp_setattro*/
7773 0, /*tp_as_buffer*/
7774 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7775 0, /*tp_doc*/
7776 0, /*tp_traverse*/
7777 0, /*tp_clear*/
7778 0, /*tp_richcompare*/
7779 0, /*tp_weaklistoffset*/
7780 0, /*tp_iter*/
7781 0, /*tp_iternext*/
7782 encoding_map_methods, /*tp_methods*/
7783 0, /*tp_members*/
7784 0, /*tp_getset*/
7785 0, /*tp_base*/
7786 0, /*tp_dict*/
7787 0, /*tp_descr_get*/
7788 0, /*tp_descr_set*/
7789 0, /*tp_dictoffset*/
7790 0, /*tp_init*/
7791 0, /*tp_alloc*/
7792 0, /*tp_new*/
7793 0, /*tp_free*/
7794 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007795};
7796
7797PyObject*
7798PyUnicode_BuildEncodingMap(PyObject* string)
7799{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007800 PyObject *result;
7801 struct encoding_map *mresult;
7802 int i;
7803 int need_dict = 0;
7804 unsigned char level1[32];
7805 unsigned char level2[512];
7806 unsigned char *mlevel1, *mlevel2, *mlevel3;
7807 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007808 int kind;
7809 void *data;
7810 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007812 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007813 PyErr_BadArgument();
7814 return NULL;
7815 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007816 kind = PyUnicode_KIND(string);
7817 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007818 memset(level1, 0xFF, sizeof level1);
7819 memset(level2, 0xFF, sizeof level2);
7820
7821 /* If there isn't a one-to-one mapping of NULL to \0,
7822 or if there are non-BMP characters, we need to use
7823 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007824 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007825 need_dict = 1;
7826 for (i = 1; i < 256; i++) {
7827 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007828 ch = PyUnicode_READ(kind, data, i);
7829 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007830 need_dict = 1;
7831 break;
7832 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007833 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007834 /* unmapped character */
7835 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007836 l1 = ch >> 11;
7837 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007838 if (level1[l1] == 0xFF)
7839 level1[l1] = count2++;
7840 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007841 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007842 }
7843
7844 if (count2 >= 0xFF || count3 >= 0xFF)
7845 need_dict = 1;
7846
7847 if (need_dict) {
7848 PyObject *result = PyDict_New();
7849 PyObject *key, *value;
7850 if (!result)
7851 return NULL;
7852 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007853 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007854 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007855 if (!key || !value)
7856 goto failed1;
7857 if (PyDict_SetItem(result, key, value) == -1)
7858 goto failed1;
7859 Py_DECREF(key);
7860 Py_DECREF(value);
7861 }
7862 return result;
7863 failed1:
7864 Py_XDECREF(key);
7865 Py_XDECREF(value);
7866 Py_DECREF(result);
7867 return NULL;
7868 }
7869
7870 /* Create a three-level trie */
7871 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7872 16*count2 + 128*count3 - 1);
7873 if (!result)
7874 return PyErr_NoMemory();
7875 PyObject_Init(result, &EncodingMapType);
7876 mresult = (struct encoding_map*)result;
7877 mresult->count2 = count2;
7878 mresult->count3 = count3;
7879 mlevel1 = mresult->level1;
7880 mlevel2 = mresult->level23;
7881 mlevel3 = mresult->level23 + 16*count2;
7882 memcpy(mlevel1, level1, 32);
7883 memset(mlevel2, 0xFF, 16*count2);
7884 memset(mlevel3, 0, 128*count3);
7885 count3 = 0;
7886 for (i = 1; i < 256; i++) {
7887 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007888 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007889 /* unmapped character */
7890 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007891 o1 = PyUnicode_READ(kind, data, i)>>11;
7892 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007893 i2 = 16*mlevel1[o1] + o2;
7894 if (mlevel2[i2] == 0xFF)
7895 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007896 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 i3 = 128*mlevel2[i2] + o3;
7898 mlevel3[i3] = i;
7899 }
7900 return result;
7901}
7902
7903static int
Victor Stinner22168992011-11-20 17:09:18 +01007904encoding_map_lookup(Py_UCS4 c, PyObject *mapping)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007905{
7906 struct encoding_map *map = (struct encoding_map*)mapping;
7907 int l1 = c>>11;
7908 int l2 = (c>>7) & 0xF;
7909 int l3 = c & 0x7F;
7910 int i;
7911
Victor Stinner22168992011-11-20 17:09:18 +01007912 if (c > 0xFFFF)
Benjamin Peterson29060642009-01-31 22:14:21 +00007913 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007914 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 *
Victor Stinner22168992011-11-20 17:09:18 +01007938charmapencode_lookup(Py_UCS4 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
Victor Stinner22168992011-11-20 17:09:18 +01008003charmapencode_output(Py_UCS4 c, PyObject *mapping,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008004 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;
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008070 enum PyUnicode_Kind kind;
8071 void *data;
8072 Py_ssize_t index;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008073 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008074 Py_ssize_t collstartpos = *inpos;
8075 Py_ssize_t collendpos = *inpos+1;
8076 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008077 char *encoding = "charmap";
8078 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008079 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008080 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008081 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008082
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008083 if (PyUnicode_READY(unicode) < 0)
8084 return -1;
8085 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008086 /* find all unencodable characters */
8087 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008088 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008089 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008090 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008091 val = encoding_map_lookup(ch, mapping);
8092 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008093 break;
8094 ++collendpos;
8095 continue;
8096 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008097
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008098 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8099 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008100 if (rep==NULL)
8101 return -1;
8102 else if (rep!=Py_None) {
8103 Py_DECREF(rep);
8104 break;
8105 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008106 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008107 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008108 }
8109 /* cache callback name lookup
8110 * (if not done yet, i.e. it's the first error) */
8111 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 if ((errors==NULL) || (!strcmp(errors, "strict")))
8113 *known_errorHandler = 1;
8114 else if (!strcmp(errors, "replace"))
8115 *known_errorHandler = 2;
8116 else if (!strcmp(errors, "ignore"))
8117 *known_errorHandler = 3;
8118 else if (!strcmp(errors, "xmlcharrefreplace"))
8119 *known_errorHandler = 4;
8120 else
8121 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008122 }
8123 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008124 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008125 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008126 return -1;
8127 case 2: /* replace */
8128 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008129 x = charmapencode_output('?', mapping, res, respos);
8130 if (x==enc_EXCEPTION) {
8131 return -1;
8132 }
8133 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008134 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008135 return -1;
8136 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008137 }
8138 /* fall through */
8139 case 3: /* ignore */
8140 *inpos = collendpos;
8141 break;
8142 case 4: /* xmlcharrefreplace */
8143 /* generate replacement (temporarily (mis)uses p) */
8144 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 char buffer[2+29+1+1];
8146 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008147 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 for (cp = buffer; *cp; ++cp) {
8149 x = charmapencode_output(*cp, mapping, res, respos);
8150 if (x==enc_EXCEPTION)
8151 return -1;
8152 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008153 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008154 return -1;
8155 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008156 }
8157 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008158 *inpos = collendpos;
8159 break;
8160 default:
8161 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008162 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008163 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008164 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008165 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008166 if (PyBytes_Check(repunicode)) {
8167 /* Directly copy bytes result to output. */
8168 Py_ssize_t outsize = PyBytes_Size(*res);
8169 Py_ssize_t requiredsize;
8170 repsize = PyBytes_Size(repunicode);
8171 requiredsize = *respos + repsize;
8172 if (requiredsize > outsize)
8173 /* Make room for all additional bytes. */
8174 if (charmapencode_resize(res, respos, requiredsize)) {
8175 Py_DECREF(repunicode);
8176 return -1;
8177 }
8178 memcpy(PyBytes_AsString(*res) + *respos,
8179 PyBytes_AsString(repunicode), repsize);
8180 *respos += repsize;
8181 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008182 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008183 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008184 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008185 /* generate replacement */
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008186 if (PyUnicode_READY(repunicode) < 0) {
8187 Py_DECREF(repunicode);
8188 return -1;
8189 }
Victor Stinner9e30aa52011-11-21 02:49:52 +01008190 repsize = PyUnicode_GET_LENGTH(repunicode);
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008191 data = PyUnicode_DATA(repunicode);
8192 kind = PyUnicode_KIND(repunicode);
8193 for (index = 0; index < repsize; index++) {
8194 Py_UCS4 repch = PyUnicode_READ(kind, data, index);
8195 x = charmapencode_output(repch, mapping, res, respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008196 if (x==enc_EXCEPTION) {
Victor Stinnerae4f7c82011-11-20 18:28:55 +01008197 Py_DECREF(repunicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 return -1;
8199 }
8200 else if (x==enc_FAILED) {
8201 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008202 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008203 return -1;
8204 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008205 }
8206 *inpos = newpos;
8207 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008208 }
8209 return 0;
8210}
8211
Alexander Belopolsky40018472011-02-26 01:02:56 +00008212PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008213_PyUnicode_EncodeCharmap(PyObject *unicode,
8214 PyObject *mapping,
8215 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008216{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008217 /* output object */
8218 PyObject *res = NULL;
8219 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008220 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008221 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008223 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008224 PyObject *errorHandler = NULL;
8225 PyObject *exc = NULL;
8226 /* the following variable is used for caching string comparisons
8227 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8228 * 3=ignore, 4=xmlcharrefreplace */
8229 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008230
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008231 if (PyUnicode_READY(unicode) < 0)
8232 return NULL;
8233 size = PyUnicode_GET_LENGTH(unicode);
8234
Guido van Rossumd57fd912000-03-10 22:53:23 +00008235 /* Default to Latin-1 */
8236 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008237 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008238
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008239 /* allocate enough for a simple encoding without
8240 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008241 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008242 if (res == NULL)
8243 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008244 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008245 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008246
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008247 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008248 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008249 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008250 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008251 if (x==enc_EXCEPTION) /* error */
8252 goto onError;
8253 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008254 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008255 &exc,
8256 &known_errorHandler, &errorHandler, errors,
8257 &res, &respos)) {
8258 goto onError;
8259 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008260 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008261 else
8262 /* done with this character => adjust input position */
8263 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008265
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008266 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008267 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008268 if (_PyBytes_Resize(&res, respos) < 0)
8269 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008270
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008271 Py_XDECREF(exc);
8272 Py_XDECREF(errorHandler);
8273 return res;
8274
Benjamin Peterson29060642009-01-31 22:14:21 +00008275 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008276 Py_XDECREF(res);
8277 Py_XDECREF(exc);
8278 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008279 return NULL;
8280}
8281
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008282/* Deprecated */
8283PyObject *
8284PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8285 Py_ssize_t size,
8286 PyObject *mapping,
8287 const char *errors)
8288{
8289 PyObject *result;
8290 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8291 if (unicode == NULL)
8292 return NULL;
8293 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8294 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008295 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008296}
8297
Alexander Belopolsky40018472011-02-26 01:02:56 +00008298PyObject *
8299PyUnicode_AsCharmapString(PyObject *unicode,
8300 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008301{
8302 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008303 PyErr_BadArgument();
8304 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008305 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008306 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008307}
8308
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008310static void
8311make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008312 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008313 Py_ssize_t startpos, Py_ssize_t endpos,
8314 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008315{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008317 *exceptionObject = _PyUnicodeTranslateError_Create(
8318 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008319 }
8320 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008321 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8322 goto onError;
8323 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8324 goto onError;
8325 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8326 goto onError;
8327 return;
8328 onError:
8329 Py_DECREF(*exceptionObject);
8330 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008331 }
8332}
8333
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008334/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008335static void
8336raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008337 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008338 Py_ssize_t startpos, Py_ssize_t endpos,
8339 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008340{
8341 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008342 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008343 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008345}
8346
8347/* error handling callback helper:
8348 build arguments, call the callback and check the arguments,
8349 put the result into newpos and return the replacement string, which
8350 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008351static PyObject *
8352unicode_translate_call_errorhandler(const char *errors,
8353 PyObject **errorHandler,
8354 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008355 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008356 Py_ssize_t startpos, Py_ssize_t endpos,
8357 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008359 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008361 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008362 PyObject *restuple;
8363 PyObject *resunicode;
8364
8365 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008366 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008367 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008368 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008369 }
8370
8371 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008372 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008373 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008374 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008375
8376 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008377 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008379 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008380 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008381 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008382 Py_DECREF(restuple);
8383 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384 }
8385 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008386 &resunicode, &i_newpos)) {
8387 Py_DECREF(restuple);
8388 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008389 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008390 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008391 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008392 else
8393 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008394 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008395 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8396 Py_DECREF(restuple);
8397 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008398 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008399 Py_INCREF(resunicode);
8400 Py_DECREF(restuple);
8401 return resunicode;
8402}
8403
8404/* Lookup the character ch in the mapping and put the result in result,
8405 which must be decrefed by the caller.
8406 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008407static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008408charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409{
Christian Heimes217cfd12007-12-02 14:31:20 +00008410 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008411 PyObject *x;
8412
8413 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008414 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008415 x = PyObject_GetItem(mapping, w);
8416 Py_DECREF(w);
8417 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008418 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8419 /* No mapping found means: use 1:1 mapping. */
8420 PyErr_Clear();
8421 *result = NULL;
8422 return 0;
8423 } else
8424 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008425 }
8426 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008427 *result = x;
8428 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008429 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008430 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008431 long value = PyLong_AS_LONG(x);
8432 long max = PyUnicode_GetMax();
8433 if (value < 0 || value > max) {
8434 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008435 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 Py_DECREF(x);
8437 return -1;
8438 }
8439 *result = x;
8440 return 0;
8441 }
8442 else if (PyUnicode_Check(x)) {
8443 *result = x;
8444 return 0;
8445 }
8446 else {
8447 /* wrong return value */
8448 PyErr_SetString(PyExc_TypeError,
8449 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008450 Py_DECREF(x);
8451 return -1;
8452 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008453}
8454/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 if not reallocate and adjust various state variables.
8456 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008457static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008458charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008459 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008460{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008462 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 /* exponentially overallocate to minimize reallocations */
8464 if (requiredsize < 2 * oldsize)
8465 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008466 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8467 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008469 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 }
8471 return 0;
8472}
8473/* lookup the character, put the result in the output string and adjust
8474 various state variables. Return a new reference to the object that
8475 was put in the output buffer in *result, or Py_None, if the mapping was
8476 undefined (in which case no character was written).
8477 The called must decref result.
8478 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008479static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8481 PyObject *mapping, Py_UCS4 **output,
8482 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008483 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008484{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008485 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8486 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008487 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008491 }
8492 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008493 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008494 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008496 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008497 }
8498 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008499 Py_ssize_t repsize;
8500 if (PyUnicode_READY(*res) == -1)
8501 return -1;
8502 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008503 if (repsize==1) {
8504 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008505 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008506 }
8507 else if (repsize!=0) {
8508 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008509 Py_ssize_t requiredsize = *opos +
8510 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008511 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008512 Py_ssize_t i;
8513 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008514 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 for(i = 0; i < repsize; i++)
8516 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008517 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008518 }
8519 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008521 return 0;
8522}
8523
Alexander Belopolsky40018472011-02-26 01:02:56 +00008524PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008525_PyUnicode_TranslateCharmap(PyObject *input,
8526 PyObject *mapping,
8527 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008528{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008529 /* input object */
8530 char *idata;
8531 Py_ssize_t size, i;
8532 int kind;
8533 /* output buffer */
8534 Py_UCS4 *output = NULL;
8535 Py_ssize_t osize;
8536 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008537 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539 char *reason = "character maps to <undefined>";
8540 PyObject *errorHandler = NULL;
8541 PyObject *exc = NULL;
8542 /* the following variable is used for caching string comparisons
8543 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8544 * 3=ignore, 4=xmlcharrefreplace */
8545 int known_errorHandler = -1;
8546
Guido van Rossumd57fd912000-03-10 22:53:23 +00008547 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008548 PyErr_BadArgument();
8549 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008550 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008551
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 if (PyUnicode_READY(input) == -1)
8553 return NULL;
8554 idata = (char*)PyUnicode_DATA(input);
8555 kind = PyUnicode_KIND(input);
8556 size = PyUnicode_GET_LENGTH(input);
8557 i = 0;
8558
8559 if (size == 0) {
8560 Py_INCREF(input);
8561 return input;
8562 }
8563
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008564 /* allocate enough for a simple 1:1 translation without
8565 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 osize = size;
8567 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8568 opos = 0;
8569 if (output == NULL) {
8570 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008571 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008572 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008573
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008575 /* try to encode it */
8576 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008577 if (charmaptranslate_output(input, i, mapping,
8578 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 Py_XDECREF(x);
8580 goto onError;
8581 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008582 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008583 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008584 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008585 else { /* untranslatable character */
8586 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8587 Py_ssize_t repsize;
8588 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008589 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008590 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008591 Py_ssize_t collstart = i;
8592 Py_ssize_t collend = i+1;
8593 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008594
Benjamin Peterson29060642009-01-31 22:14:21 +00008595 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 while (collend < size) {
8597 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 goto onError;
8599 Py_XDECREF(x);
8600 if (x!=Py_None)
8601 break;
8602 ++collend;
8603 }
8604 /* cache callback name lookup
8605 * (if not done yet, i.e. it's the first error) */
8606 if (known_errorHandler==-1) {
8607 if ((errors==NULL) || (!strcmp(errors, "strict")))
8608 known_errorHandler = 1;
8609 else if (!strcmp(errors, "replace"))
8610 known_errorHandler = 2;
8611 else if (!strcmp(errors, "ignore"))
8612 known_errorHandler = 3;
8613 else if (!strcmp(errors, "xmlcharrefreplace"))
8614 known_errorHandler = 4;
8615 else
8616 known_errorHandler = 0;
8617 }
8618 switch (known_errorHandler) {
8619 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008620 raise_translate_exception(&exc, input, collstart,
8621 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008622 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008623 case 2: /* replace */
8624 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008625 for (coll = collstart; coll<collend; coll++)
8626 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008627 /* fall through */
8628 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 break;
8631 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008632 /* generate replacement (temporarily (mis)uses i) */
8633 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008634 char buffer[2+29+1+1];
8635 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008636 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8637 if (charmaptranslate_makespace(&output, &osize,
8638 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008639 goto onError;
8640 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008641 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008642 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008643 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008644 break;
8645 default:
8646 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008647 reason, input, &exc,
8648 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008649 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008650 goto onError;
8651 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 repsize = PyUnicode_GET_LENGTH(repunicode);
8653 if (charmaptranslate_makespace(&output, &osize,
8654 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008655 Py_DECREF(repunicode);
8656 goto onError;
8657 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008658 for (uni2 = 0; repsize-->0; ++uni2)
8659 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8660 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008661 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008662 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008663 }
8664 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008665 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8666 if (!res)
8667 goto onError;
8668 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008669 Py_XDECREF(exc);
8670 Py_XDECREF(errorHandler);
8671 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008672
Benjamin Peterson29060642009-01-31 22:14:21 +00008673 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008674 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008675 Py_XDECREF(exc);
8676 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008677 return NULL;
8678}
8679
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008680/* Deprecated. Use PyUnicode_Translate instead. */
8681PyObject *
8682PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8683 Py_ssize_t size,
8684 PyObject *mapping,
8685 const char *errors)
8686{
8687 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8688 if (!unicode)
8689 return NULL;
8690 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8691}
8692
Alexander Belopolsky40018472011-02-26 01:02:56 +00008693PyObject *
8694PyUnicode_Translate(PyObject *str,
8695 PyObject *mapping,
8696 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008697{
8698 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008699
Guido van Rossumd57fd912000-03-10 22:53:23 +00008700 str = PyUnicode_FromObject(str);
8701 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008702 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008703 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008704 Py_DECREF(str);
8705 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008706
Benjamin Peterson29060642009-01-31 22:14:21 +00008707 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008708 Py_XDECREF(str);
8709 return NULL;
8710}
Tim Petersced69f82003-09-16 20:30:58 +00008711
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008712static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008713fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008714{
8715 /* No need to call PyUnicode_READY(self) because this function is only
8716 called as a callback from fixup() which does it already. */
8717 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8718 const int kind = PyUnicode_KIND(self);
8719 void *data = PyUnicode_DATA(self);
8720 Py_UCS4 maxchar = 0, ch, fixed;
8721 Py_ssize_t i;
8722
8723 for (i = 0; i < len; ++i) {
8724 ch = PyUnicode_READ(kind, data, i);
8725 fixed = 0;
8726 if (ch > 127) {
8727 if (Py_UNICODE_ISSPACE(ch))
8728 fixed = ' ';
8729 else {
8730 const int decimal = Py_UNICODE_TODECIMAL(ch);
8731 if (decimal >= 0)
8732 fixed = '0' + decimal;
8733 }
8734 if (fixed != 0) {
8735 if (fixed > maxchar)
8736 maxchar = fixed;
8737 PyUnicode_WRITE(kind, data, i, fixed);
8738 }
8739 else if (ch > maxchar)
8740 maxchar = ch;
8741 }
8742 else if (ch > maxchar)
8743 maxchar = ch;
8744 }
8745
8746 return maxchar;
8747}
8748
8749PyObject *
8750_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8751{
8752 if (!PyUnicode_Check(unicode)) {
8753 PyErr_BadInternalCall();
8754 return NULL;
8755 }
8756 if (PyUnicode_READY(unicode) == -1)
8757 return NULL;
8758 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8759 /* If the string is already ASCII, just return the same string */
8760 Py_INCREF(unicode);
8761 return unicode;
8762 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008763 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008764}
8765
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008766PyObject *
8767PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8768 Py_ssize_t length)
8769{
8770 PyObject *result;
8771 Py_UNICODE *p; /* write pointer into result */
8772 Py_ssize_t i;
8773 /* Copy to a new string */
8774 result = (PyObject *)_PyUnicode_New(length);
8775 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8776 if (result == NULL)
8777 return result;
8778 p = PyUnicode_AS_UNICODE(result);
8779 /* Iterate over code points */
8780 for (i = 0; i < length; i++) {
8781 Py_UNICODE ch =s[i];
8782 if (ch > 127) {
8783 int decimal = Py_UNICODE_TODECIMAL(ch);
8784 if (decimal >= 0)
8785 p[i] = '0' + decimal;
8786 }
8787 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008788#ifndef DONT_MAKE_RESULT_READY
8789 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008790 Py_DECREF(result);
8791 return NULL;
8792 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008793#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008794 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008795 return result;
8796}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008797/* --- Decimal Encoder ---------------------------------------------------- */
8798
Alexander Belopolsky40018472011-02-26 01:02:56 +00008799int
8800PyUnicode_EncodeDecimal(Py_UNICODE *s,
8801 Py_ssize_t length,
8802 char *output,
8803 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008804{
8805 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008806 PyObject *errorHandler = NULL;
8807 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008808 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008809 const char *encoding = "decimal";
8810 const char *reason = "invalid decimal Unicode string";
8811 /* the following variable is used for caching string comparisons
8812 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8813 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008814
8815 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008816 PyErr_BadArgument();
8817 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008818 }
8819
8820 p = s;
8821 end = s + length;
8822 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008823 register Py_UNICODE ch = *p;
8824 int decimal;
8825 PyObject *repunicode;
8826 Py_ssize_t repsize;
8827 Py_ssize_t newpos;
8828 Py_UNICODE *uni2;
8829 Py_UNICODE *collstart;
8830 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008831
Benjamin Peterson29060642009-01-31 22:14:21 +00008832 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008833 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008834 ++p;
8835 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008836 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008837 decimal = Py_UNICODE_TODECIMAL(ch);
8838 if (decimal >= 0) {
8839 *output++ = '0' + decimal;
8840 ++p;
8841 continue;
8842 }
8843 if (0 < ch && ch < 256) {
8844 *output++ = (char)ch;
8845 ++p;
8846 continue;
8847 }
8848 /* All other characters are considered unencodable */
8849 collstart = p;
8850 collend = p+1;
8851 while (collend < end) {
8852 if ((0 < *collend && *collend < 256) ||
8853 !Py_UNICODE_ISSPACE(*collend) ||
8854 Py_UNICODE_TODECIMAL(*collend))
8855 break;
8856 }
8857 /* cache callback name lookup
8858 * (if not done yet, i.e. it's the first error) */
8859 if (known_errorHandler==-1) {
8860 if ((errors==NULL) || (!strcmp(errors, "strict")))
8861 known_errorHandler = 1;
8862 else if (!strcmp(errors, "replace"))
8863 known_errorHandler = 2;
8864 else if (!strcmp(errors, "ignore"))
8865 known_errorHandler = 3;
8866 else if (!strcmp(errors, "xmlcharrefreplace"))
8867 known_errorHandler = 4;
8868 else
8869 known_errorHandler = 0;
8870 }
8871 switch (known_errorHandler) {
8872 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008873 unicode = PyUnicode_FromUnicode(s, length);
8874 if (unicode == NULL)
8875 goto onError;
8876 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8877 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008878 goto onError;
8879 case 2: /* replace */
8880 for (p = collstart; p < collend; ++p)
8881 *output++ = '?';
8882 /* fall through */
8883 case 3: /* ignore */
8884 p = collend;
8885 break;
8886 case 4: /* xmlcharrefreplace */
8887 /* generate replacement (temporarily (mis)uses p) */
8888 for (p = collstart; p < collend; ++p)
8889 output += sprintf(output, "&#%d;", (int)*p);
8890 p = collend;
8891 break;
8892 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008893 unicode = PyUnicode_FromUnicode(s, length);
8894 if (unicode == NULL)
8895 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008896 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008897 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008898 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008899 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008900 if (repunicode == NULL)
8901 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008902 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008903 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008904 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8905 Py_DECREF(repunicode);
8906 goto onError;
8907 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008908 /* generate replacement */
8909 repsize = PyUnicode_GET_SIZE(repunicode);
8910 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8911 Py_UNICODE ch = *uni2;
8912 if (Py_UNICODE_ISSPACE(ch))
8913 *output++ = ' ';
8914 else {
8915 decimal = Py_UNICODE_TODECIMAL(ch);
8916 if (decimal >= 0)
8917 *output++ = '0' + decimal;
8918 else if (0 < ch && ch < 256)
8919 *output++ = (char)ch;
8920 else {
8921 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008922 unicode = PyUnicode_FromUnicode(s, length);
8923 if (unicode == NULL)
8924 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008925 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008926 unicode, collstart-s, collend-s, reason);
8927 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008928 goto onError;
8929 }
8930 }
8931 }
8932 p = s + newpos;
8933 Py_DECREF(repunicode);
8934 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008935 }
8936 /* 0-terminate the output string */
8937 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008938 Py_XDECREF(exc);
8939 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008940 return 0;
8941
Benjamin Peterson29060642009-01-31 22:14:21 +00008942 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008943 Py_XDECREF(exc);
8944 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008945 return -1;
8946}
8947
Guido van Rossumd57fd912000-03-10 22:53:23 +00008948/* --- Helpers ------------------------------------------------------------ */
8949
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008950static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008951any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008952 Py_ssize_t start,
8953 Py_ssize_t end)
8954{
8955 int kind1, kind2, kind;
8956 void *buf1, *buf2;
8957 Py_ssize_t len1, len2, result;
8958
8959 kind1 = PyUnicode_KIND(s1);
8960 kind2 = PyUnicode_KIND(s2);
8961 kind = kind1 > kind2 ? kind1 : kind2;
8962 buf1 = PyUnicode_DATA(s1);
8963 buf2 = PyUnicode_DATA(s2);
8964 if (kind1 != kind)
8965 buf1 = _PyUnicode_AsKind(s1, kind);
8966 if (!buf1)
8967 return -2;
8968 if (kind2 != kind)
8969 buf2 = _PyUnicode_AsKind(s2, kind);
8970 if (!buf2) {
8971 if (kind1 != kind) PyMem_Free(buf1);
8972 return -2;
8973 }
8974 len1 = PyUnicode_GET_LENGTH(s1);
8975 len2 = PyUnicode_GET_LENGTH(s2);
8976
Victor Stinner794d5672011-10-10 03:21:36 +02008977 if (direction > 0) {
8978 switch(kind) {
8979 case PyUnicode_1BYTE_KIND:
8980 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8981 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8982 else
8983 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8984 break;
8985 case PyUnicode_2BYTE_KIND:
8986 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8987 break;
8988 case PyUnicode_4BYTE_KIND:
8989 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8990 break;
8991 default:
8992 assert(0); result = -2;
8993 }
8994 }
8995 else {
8996 switch(kind) {
8997 case PyUnicode_1BYTE_KIND:
8998 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8999 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
9000 else
9001 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9002 break;
9003 case PyUnicode_2BYTE_KIND:
9004 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9005 break;
9006 case PyUnicode_4BYTE_KIND:
9007 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
9008 break;
9009 default:
9010 assert(0); result = -2;
9011 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009012 }
9013
9014 if (kind1 != kind)
9015 PyMem_Free(buf1);
9016 if (kind2 != kind)
9017 PyMem_Free(buf2);
9018
9019 return result;
9020}
9021
9022Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009023_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009024 Py_ssize_t n_buffer,
9025 void *digits, Py_ssize_t n_digits,
9026 Py_ssize_t min_width,
9027 const char *grouping,
9028 const char *thousands_sep)
9029{
9030 switch(kind) {
9031 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009032 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9033 return _PyUnicode_ascii_InsertThousandsGrouping(
9034 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9035 min_width, grouping, thousands_sep);
9036 else
9037 return _PyUnicode_ucs1_InsertThousandsGrouping(
9038 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9039 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 case PyUnicode_2BYTE_KIND:
9041 return _PyUnicode_ucs2_InsertThousandsGrouping(
9042 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9043 min_width, grouping, thousands_sep);
9044 case PyUnicode_4BYTE_KIND:
9045 return _PyUnicode_ucs4_InsertThousandsGrouping(
9046 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9047 min_width, grouping, thousands_sep);
9048 }
9049 assert(0);
9050 return -1;
9051}
9052
9053
Thomas Wouters477c8d52006-05-27 19:21:47 +00009054/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009055#define ADJUST_INDICES(start, end, len) \
9056 if (end > len) \
9057 end = len; \
9058 else if (end < 0) { \
9059 end += len; \
9060 if (end < 0) \
9061 end = 0; \
9062 } \
9063 if (start < 0) { \
9064 start += len; \
9065 if (start < 0) \
9066 start = 0; \
9067 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009068
Alexander Belopolsky40018472011-02-26 01:02:56 +00009069Py_ssize_t
9070PyUnicode_Count(PyObject *str,
9071 PyObject *substr,
9072 Py_ssize_t start,
9073 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009074{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009075 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009076 PyObject* str_obj;
9077 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009078 int kind1, kind2, kind;
9079 void *buf1 = NULL, *buf2 = NULL;
9080 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009081
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009082 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009083 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009084 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009085 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009086 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009087 Py_DECREF(str_obj);
9088 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009089 }
Tim Petersced69f82003-09-16 20:30:58 +00009090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009091 kind1 = PyUnicode_KIND(str_obj);
9092 kind2 = PyUnicode_KIND(sub_obj);
9093 kind = kind1 > kind2 ? kind1 : kind2;
9094 buf1 = PyUnicode_DATA(str_obj);
9095 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009096 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009097 if (!buf1)
9098 goto onError;
9099 buf2 = PyUnicode_DATA(sub_obj);
9100 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009101 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009102 if (!buf2)
9103 goto onError;
9104 len1 = PyUnicode_GET_LENGTH(str_obj);
9105 len2 = PyUnicode_GET_LENGTH(sub_obj);
9106
9107 ADJUST_INDICES(start, end, len1);
9108 switch(kind) {
9109 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009110 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9111 result = asciilib_count(
9112 ((Py_UCS1*)buf1) + start, end - start,
9113 buf2, len2, PY_SSIZE_T_MAX
9114 );
9115 else
9116 result = ucs1lib_count(
9117 ((Py_UCS1*)buf1) + start, end - start,
9118 buf2, len2, PY_SSIZE_T_MAX
9119 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009120 break;
9121 case PyUnicode_2BYTE_KIND:
9122 result = ucs2lib_count(
9123 ((Py_UCS2*)buf1) + start, end - start,
9124 buf2, len2, PY_SSIZE_T_MAX
9125 );
9126 break;
9127 case PyUnicode_4BYTE_KIND:
9128 result = ucs4lib_count(
9129 ((Py_UCS4*)buf1) + start, end - start,
9130 buf2, len2, PY_SSIZE_T_MAX
9131 );
9132 break;
9133 default:
9134 assert(0); result = 0;
9135 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009136
9137 Py_DECREF(sub_obj);
9138 Py_DECREF(str_obj);
9139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140 if (kind1 != kind)
9141 PyMem_Free(buf1);
9142 if (kind2 != kind)
9143 PyMem_Free(buf2);
9144
Guido van Rossumd57fd912000-03-10 22:53:23 +00009145 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 onError:
9147 Py_DECREF(sub_obj);
9148 Py_DECREF(str_obj);
9149 if (kind1 != kind && buf1)
9150 PyMem_Free(buf1);
9151 if (kind2 != kind && buf2)
9152 PyMem_Free(buf2);
9153 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009154}
9155
Alexander Belopolsky40018472011-02-26 01:02:56 +00009156Py_ssize_t
9157PyUnicode_Find(PyObject *str,
9158 PyObject *sub,
9159 Py_ssize_t start,
9160 Py_ssize_t end,
9161 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009162{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009163 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009164
Guido van Rossumd57fd912000-03-10 22:53:23 +00009165 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009167 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009168 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009169 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009170 Py_DECREF(str);
9171 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009172 }
Tim Petersced69f82003-09-16 20:30:58 +00009173
Victor Stinner794d5672011-10-10 03:21:36 +02009174 result = any_find_slice(direction,
9175 str, sub, start, end
9176 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009177
Guido van Rossumd57fd912000-03-10 22:53:23 +00009178 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009179 Py_DECREF(sub);
9180
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181 return result;
9182}
9183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009184Py_ssize_t
9185PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9186 Py_ssize_t start, Py_ssize_t end,
9187 int direction)
9188{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009189 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009190 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009191 if (PyUnicode_READY(str) == -1)
9192 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009193 if (start < 0 || end < 0) {
9194 PyErr_SetString(PyExc_IndexError, "string index out of range");
9195 return -2;
9196 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009197 if (end > PyUnicode_GET_LENGTH(str))
9198 end = PyUnicode_GET_LENGTH(str);
9199 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009200 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9201 kind, end-start, ch, direction);
9202 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009204 else
9205 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206}
9207
Alexander Belopolsky40018472011-02-26 01:02:56 +00009208static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009209tailmatch(PyObject *self,
9210 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009211 Py_ssize_t start,
9212 Py_ssize_t end,
9213 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009214{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009215 int kind_self;
9216 int kind_sub;
9217 void *data_self;
9218 void *data_sub;
9219 Py_ssize_t offset;
9220 Py_ssize_t i;
9221 Py_ssize_t end_sub;
9222
9223 if (PyUnicode_READY(self) == -1 ||
9224 PyUnicode_READY(substring) == -1)
9225 return 0;
9226
9227 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009228 return 1;
9229
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009230 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9231 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009232 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009233 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009235 kind_self = PyUnicode_KIND(self);
9236 data_self = PyUnicode_DATA(self);
9237 kind_sub = PyUnicode_KIND(substring);
9238 data_sub = PyUnicode_DATA(substring);
9239 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9240
9241 if (direction > 0)
9242 offset = end;
9243 else
9244 offset = start;
9245
9246 if (PyUnicode_READ(kind_self, data_self, offset) ==
9247 PyUnicode_READ(kind_sub, data_sub, 0) &&
9248 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9249 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9250 /* If both are of the same kind, memcmp is sufficient */
9251 if (kind_self == kind_sub) {
9252 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009253 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009254 data_sub,
9255 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009256 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009257 }
9258 /* otherwise we have to compare each character by first accesing it */
9259 else {
9260 /* We do not need to compare 0 and len(substring)-1 because
9261 the if statement above ensured already that they are equal
9262 when we end up here. */
9263 // TODO: honor direction and do a forward or backwards search
9264 for (i = 1; i < end_sub; ++i) {
9265 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9266 PyUnicode_READ(kind_sub, data_sub, i))
9267 return 0;
9268 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009269 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009270 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 }
9272
9273 return 0;
9274}
9275
Alexander Belopolsky40018472011-02-26 01:02:56 +00009276Py_ssize_t
9277PyUnicode_Tailmatch(PyObject *str,
9278 PyObject *substr,
9279 Py_ssize_t start,
9280 Py_ssize_t end,
9281 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009283 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009284
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285 str = PyUnicode_FromObject(str);
9286 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009287 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009288 substr = PyUnicode_FromObject(substr);
9289 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009290 Py_DECREF(str);
9291 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009292 }
Tim Petersced69f82003-09-16 20:30:58 +00009293
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009294 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009295 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009296 Py_DECREF(str);
9297 Py_DECREF(substr);
9298 return result;
9299}
9300
Guido van Rossumd57fd912000-03-10 22:53:23 +00009301/* Apply fixfct filter to the Unicode object self and return a
9302 reference to the modified object */
9303
Alexander Belopolsky40018472011-02-26 01:02:56 +00009304static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009305fixup(PyObject *self,
9306 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009307{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009308 PyObject *u;
9309 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009310
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009311 if (PyUnicode_READY(self) == -1)
9312 return NULL;
9313 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9314 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9315 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009316 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009317 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009318
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009319 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009320 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009321
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009322 /* fix functions return the new maximum character in a string,
9323 if the kind of the resulting unicode object does not change,
9324 everything is fine. Otherwise we need to change the string kind
9325 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009326 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 if (maxchar_new == 0)
9328 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9329 else if (maxchar_new <= 127)
9330 maxchar_new = 127;
9331 else if (maxchar_new <= 255)
9332 maxchar_new = 255;
9333 else if (maxchar_new <= 65535)
9334 maxchar_new = 65535;
9335 else
9336 maxchar_new = 1114111; /* 0x10ffff */
9337
9338 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009339 /* fixfct should return TRUE if it modified the buffer. If
9340 FALSE, return a reference to the original buffer instead
9341 (to save space, not time) */
9342 Py_INCREF(self);
9343 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009344 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009345 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 else if (maxchar_new == maxchar_old) {
9347 return u;
9348 }
9349 else {
9350 /* In case the maximum character changed, we need to
9351 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009352 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 if (v == NULL) {
9354 Py_DECREF(u);
9355 return NULL;
9356 }
9357 if (maxchar_new > maxchar_old) {
9358 /* If the maxchar increased so that the kind changed, not all
9359 characters are representable anymore and we need to fix the
9360 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009361 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009362 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009363 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9364 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009365 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009366 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009367 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009368
9369 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009370 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371 return v;
9372 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373}
9374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009376fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009378 /* No need to call PyUnicode_READY(self) because this function is only
9379 called as a callback from fixup() which does it already. */
9380 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9381 const int kind = PyUnicode_KIND(self);
9382 void *data = PyUnicode_DATA(self);
9383 int touched = 0;
9384 Py_UCS4 maxchar = 0;
9385 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009386
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009387 for (i = 0; i < len; ++i) {
9388 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9389 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9390 if (up != ch) {
9391 if (up > maxchar)
9392 maxchar = up;
9393 PyUnicode_WRITE(kind, data, i, up);
9394 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009395 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396 else if (ch > maxchar)
9397 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009398 }
9399
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009400 if (touched)
9401 return maxchar;
9402 else
9403 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009404}
9405
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009406static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009407fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009408{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009409 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9410 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9411 const int kind = PyUnicode_KIND(self);
9412 void *data = PyUnicode_DATA(self);
9413 int touched = 0;
9414 Py_UCS4 maxchar = 0;
9415 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009417 for(i = 0; i < len; ++i) {
9418 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9419 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9420 if (lo != ch) {
9421 if (lo > maxchar)
9422 maxchar = lo;
9423 PyUnicode_WRITE(kind, data, i, lo);
9424 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009426 else if (ch > maxchar)
9427 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009428 }
9429
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009430 if (touched)
9431 return maxchar;
9432 else
9433 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009434}
9435
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009436static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009437fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009438{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009439 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9440 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9441 const int kind = PyUnicode_KIND(self);
9442 void *data = PyUnicode_DATA(self);
9443 int touched = 0;
9444 Py_UCS4 maxchar = 0;
9445 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447 for(i = 0; i < len; ++i) {
9448 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9449 Py_UCS4 nu = 0;
9450
9451 if (Py_UNICODE_ISUPPER(ch))
9452 nu = Py_UNICODE_TOLOWER(ch);
9453 else if (Py_UNICODE_ISLOWER(ch))
9454 nu = Py_UNICODE_TOUPPER(ch);
9455
9456 if (nu != 0) {
9457 if (nu > maxchar)
9458 maxchar = nu;
9459 PyUnicode_WRITE(kind, data, i, nu);
9460 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009461 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462 else if (ch > maxchar)
9463 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464 }
9465
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009466 if (touched)
9467 return maxchar;
9468 else
9469 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009470}
9471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009472static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009473fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009475 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9476 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9477 const int kind = PyUnicode_KIND(self);
9478 void *data = PyUnicode_DATA(self);
9479 int touched = 0;
9480 Py_UCS4 maxchar = 0;
9481 Py_ssize_t i = 0;
9482 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009483
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009484 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009485 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009486
9487 ch = PyUnicode_READ(kind, data, i);
9488 if (!Py_UNICODE_ISUPPER(ch)) {
9489 maxchar = Py_UNICODE_TOUPPER(ch);
9490 PyUnicode_WRITE(kind, data, i, maxchar);
9491 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009492 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009493 ++i;
9494 for(; i < len; ++i) {
9495 ch = PyUnicode_READ(kind, data, i);
9496 if (!Py_UNICODE_ISLOWER(ch)) {
9497 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9498 if (lo > maxchar)
9499 maxchar = lo;
9500 PyUnicode_WRITE(kind, data, i, lo);
9501 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009502 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009503 else if (ch > maxchar)
9504 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009505 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009506
9507 if (touched)
9508 return maxchar;
9509 else
9510 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009511}
9512
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009513static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009514fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009515{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9517 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9518 const int kind = PyUnicode_KIND(self);
9519 void *data = PyUnicode_DATA(self);
9520 Py_UCS4 maxchar = 0;
9521 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009522 int previous_is_cased;
9523
9524 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009525 if (len == 1) {
9526 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9527 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9528 if (ti != ch) {
9529 PyUnicode_WRITE(kind, data, i, ti);
9530 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009531 }
9532 else
9533 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009534 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009535 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009536 for(; i < len; ++i) {
9537 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9538 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009539
Benjamin Peterson29060642009-01-31 22:14:21 +00009540 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009541 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009542 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009543 nu = Py_UNICODE_TOTITLE(ch);
9544
9545 if (nu > maxchar)
9546 maxchar = nu;
9547 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009548
Benjamin Peterson29060642009-01-31 22:14:21 +00009549 if (Py_UNICODE_ISLOWER(ch) ||
9550 Py_UNICODE_ISUPPER(ch) ||
9551 Py_UNICODE_ISTITLE(ch))
9552 previous_is_cased = 1;
9553 else
9554 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009555 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009556 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009557}
9558
Tim Peters8ce9f162004-08-27 01:49:32 +00009559PyObject *
9560PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009561{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009562 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009563 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009564 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009565 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009566 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9567 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009568 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009569 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009570 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009571 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009572 int use_memcpy;
9573 unsigned char *res_data = NULL, *sep_data = NULL;
9574 PyObject *last_obj;
9575 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009576
Tim Peters05eba1f2004-08-27 21:32:02 +00009577 fseq = PySequence_Fast(seq, "");
9578 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009579 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009580 }
9581
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009582 /* NOTE: the following code can't call back into Python code,
9583 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009584 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009585
Tim Peters05eba1f2004-08-27 21:32:02 +00009586 seqlen = PySequence_Fast_GET_SIZE(fseq);
9587 /* If empty sequence, return u"". */
9588 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009589 Py_DECREF(fseq);
9590 Py_INCREF(unicode_empty);
9591 res = unicode_empty;
9592 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009593 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009594
Tim Peters05eba1f2004-08-27 21:32:02 +00009595 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009596 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009597 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009598 if (seqlen == 1) {
9599 if (PyUnicode_CheckExact(items[0])) {
9600 res = items[0];
9601 Py_INCREF(res);
9602 Py_DECREF(fseq);
9603 return res;
9604 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009605 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009606 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009607 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009608 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009609 /* Set up sep and seplen */
9610 if (separator == NULL) {
9611 /* fall back to a blank space separator */
9612 sep = PyUnicode_FromOrdinal(' ');
9613 if (!sep)
9614 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009615 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009616 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009617 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009618 else {
9619 if (!PyUnicode_Check(separator)) {
9620 PyErr_Format(PyExc_TypeError,
9621 "separator: expected str instance,"
9622 " %.80s found",
9623 Py_TYPE(separator)->tp_name);
9624 goto onError;
9625 }
9626 if (PyUnicode_READY(separator))
9627 goto onError;
9628 sep = separator;
9629 seplen = PyUnicode_GET_LENGTH(separator);
9630 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9631 /* inc refcount to keep this code path symmetric with the
9632 above case of a blank separator */
9633 Py_INCREF(sep);
9634 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009635 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009636 }
9637
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009638 /* There are at least two things to join, or else we have a subclass
9639 * of str in the sequence.
9640 * Do a pre-pass to figure out the total amount of space we'll
9641 * need (sz), and see whether all argument are strings.
9642 */
9643 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009644#ifdef Py_DEBUG
9645 use_memcpy = 0;
9646#else
9647 use_memcpy = 1;
9648#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009649 for (i = 0; i < seqlen; i++) {
9650 const Py_ssize_t old_sz = sz;
9651 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009652 if (!PyUnicode_Check(item)) {
9653 PyErr_Format(PyExc_TypeError,
9654 "sequence item %zd: expected str instance,"
9655 " %.80s found",
9656 i, Py_TYPE(item)->tp_name);
9657 goto onError;
9658 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009659 if (PyUnicode_READY(item) == -1)
9660 goto onError;
9661 sz += PyUnicode_GET_LENGTH(item);
9662 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009663 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009664 if (i != 0)
9665 sz += seplen;
9666 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9667 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009668 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009669 goto onError;
9670 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009671 if (use_memcpy && last_obj != NULL) {
9672 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9673 use_memcpy = 0;
9674 }
9675 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009676 }
Tim Petersced69f82003-09-16 20:30:58 +00009677
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009678 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009679 if (res == NULL)
9680 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009681
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009682 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009683#ifdef Py_DEBUG
9684 use_memcpy = 0;
9685#else
9686 if (use_memcpy) {
9687 res_data = PyUnicode_1BYTE_DATA(res);
9688 kind = PyUnicode_KIND(res);
9689 if (seplen != 0)
9690 sep_data = PyUnicode_1BYTE_DATA(sep);
9691 }
9692#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009693 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009694 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009695 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009696 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009697 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009698 if (use_memcpy) {
9699 Py_MEMCPY(res_data,
9700 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009701 kind * seplen);
9702 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009703 }
9704 else {
9705 copy_characters(res, res_offset, sep, 0, seplen);
9706 res_offset += seplen;
9707 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009708 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009709 itemlen = PyUnicode_GET_LENGTH(item);
9710 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009711 if (use_memcpy) {
9712 Py_MEMCPY(res_data,
9713 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009714 kind * itemlen);
9715 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009716 }
9717 else {
9718 copy_characters(res, res_offset, item, 0, itemlen);
9719 res_offset += itemlen;
9720 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009721 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009722 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009723 if (use_memcpy)
9724 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009725 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009726 else
9727 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009728
Tim Peters05eba1f2004-08-27 21:32:02 +00009729 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009730 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009731 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009732 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009733
Benjamin Peterson29060642009-01-31 22:14:21 +00009734 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009735 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009736 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009737 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009738 return NULL;
9739}
9740
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009741#define FILL(kind, data, value, start, length) \
9742 do { \
9743 Py_ssize_t i_ = 0; \
9744 assert(kind != PyUnicode_WCHAR_KIND); \
9745 switch ((kind)) { \
9746 case PyUnicode_1BYTE_KIND: { \
9747 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9748 memset(to_, (unsigned char)value, length); \
9749 break; \
9750 } \
9751 case PyUnicode_2BYTE_KIND: { \
9752 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9753 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9754 break; \
9755 } \
9756 default: { \
9757 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9758 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9759 break; \
9760 } \
9761 } \
9762 } while (0)
9763
Victor Stinner9310abb2011-10-05 00:59:23 +02009764static PyObject *
9765pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009766 Py_ssize_t left,
9767 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009768 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009769{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009770 PyObject *u;
9771 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009772 int kind;
9773 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009774
9775 if (left < 0)
9776 left = 0;
9777 if (right < 0)
9778 right = 0;
9779
Tim Peters7a29bd52001-09-12 03:03:31 +00009780 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009781 Py_INCREF(self);
9782 return self;
9783 }
9784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009785 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9786 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009787 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9788 return NULL;
9789 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9791 if (fill > maxchar)
9792 maxchar = fill;
9793 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009794 if (!u)
9795 return NULL;
9796
9797 kind = PyUnicode_KIND(u);
9798 data = PyUnicode_DATA(u);
9799 if (left)
9800 FILL(kind, data, fill, 0, left);
9801 if (right)
9802 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009803 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009804 assert(_PyUnicode_CheckConsistency(u, 1));
9805 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808
Alexander Belopolsky40018472011-02-26 01:02:56 +00009809PyObject *
9810PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009811{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009812 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009813
9814 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009815 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009816 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009817
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009818 switch(PyUnicode_KIND(string)) {
9819 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009820 if (PyUnicode_IS_ASCII(string))
9821 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009822 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009823 PyUnicode_GET_LENGTH(string), keepends);
9824 else
9825 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009826 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009827 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 break;
9829 case PyUnicode_2BYTE_KIND:
9830 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009831 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009832 PyUnicode_GET_LENGTH(string), keepends);
9833 break;
9834 case PyUnicode_4BYTE_KIND:
9835 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009836 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009837 PyUnicode_GET_LENGTH(string), keepends);
9838 break;
9839 default:
9840 assert(0);
9841 list = 0;
9842 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009843 Py_DECREF(string);
9844 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009845}
9846
Alexander Belopolsky40018472011-02-26 01:02:56 +00009847static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009848split(PyObject *self,
9849 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009850 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009851{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009852 int kind1, kind2, kind;
9853 void *buf1, *buf2;
9854 Py_ssize_t len1, len2;
9855 PyObject* out;
9856
Guido van Rossumd57fd912000-03-10 22:53:23 +00009857 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009858 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009859
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009860 if (PyUnicode_READY(self) == -1)
9861 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009862
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009863 if (substring == NULL)
9864 switch(PyUnicode_KIND(self)) {
9865 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009866 if (PyUnicode_IS_ASCII(self))
9867 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009868 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009869 PyUnicode_GET_LENGTH(self), maxcount
9870 );
9871 else
9872 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009873 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009874 PyUnicode_GET_LENGTH(self), maxcount
9875 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 case PyUnicode_2BYTE_KIND:
9877 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009878 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009879 PyUnicode_GET_LENGTH(self), maxcount
9880 );
9881 case PyUnicode_4BYTE_KIND:
9882 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009883 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009884 PyUnicode_GET_LENGTH(self), maxcount
9885 );
9886 default:
9887 assert(0);
9888 return NULL;
9889 }
9890
9891 if (PyUnicode_READY(substring) == -1)
9892 return NULL;
9893
9894 kind1 = PyUnicode_KIND(self);
9895 kind2 = PyUnicode_KIND(substring);
9896 kind = kind1 > kind2 ? kind1 : kind2;
9897 buf1 = PyUnicode_DATA(self);
9898 buf2 = PyUnicode_DATA(substring);
9899 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009900 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009901 if (!buf1)
9902 return NULL;
9903 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009904 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009905 if (!buf2) {
9906 if (kind1 != kind) PyMem_Free(buf1);
9907 return NULL;
9908 }
9909 len1 = PyUnicode_GET_LENGTH(self);
9910 len2 = PyUnicode_GET_LENGTH(substring);
9911
9912 switch(kind) {
9913 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009914 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9915 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009916 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009917 else
9918 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009919 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 break;
9921 case PyUnicode_2BYTE_KIND:
9922 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009923 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009924 break;
9925 case PyUnicode_4BYTE_KIND:
9926 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009927 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009928 break;
9929 default:
9930 out = NULL;
9931 }
9932 if (kind1 != kind)
9933 PyMem_Free(buf1);
9934 if (kind2 != kind)
9935 PyMem_Free(buf2);
9936 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009937}
9938
Alexander Belopolsky40018472011-02-26 01:02:56 +00009939static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009940rsplit(PyObject *self,
9941 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009942 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009943{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009944 int kind1, kind2, kind;
9945 void *buf1, *buf2;
9946 Py_ssize_t len1, len2;
9947 PyObject* out;
9948
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009949 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009950 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009951
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009952 if (PyUnicode_READY(self) == -1)
9953 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009954
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009955 if (substring == NULL)
9956 switch(PyUnicode_KIND(self)) {
9957 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009958 if (PyUnicode_IS_ASCII(self))
9959 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009961 PyUnicode_GET_LENGTH(self), maxcount
9962 );
9963 else
9964 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009965 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009966 PyUnicode_GET_LENGTH(self), maxcount
9967 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 case PyUnicode_2BYTE_KIND:
9969 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009970 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009971 PyUnicode_GET_LENGTH(self), maxcount
9972 );
9973 case PyUnicode_4BYTE_KIND:
9974 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009975 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009976 PyUnicode_GET_LENGTH(self), maxcount
9977 );
9978 default:
9979 assert(0);
9980 return NULL;
9981 }
9982
9983 if (PyUnicode_READY(substring) == -1)
9984 return NULL;
9985
9986 kind1 = PyUnicode_KIND(self);
9987 kind2 = PyUnicode_KIND(substring);
9988 kind = kind1 > kind2 ? kind1 : kind2;
9989 buf1 = PyUnicode_DATA(self);
9990 buf2 = PyUnicode_DATA(substring);
9991 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009992 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009993 if (!buf1)
9994 return NULL;
9995 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009996 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009997 if (!buf2) {
9998 if (kind1 != kind) PyMem_Free(buf1);
9999 return NULL;
10000 }
10001 len1 = PyUnicode_GET_LENGTH(self);
10002 len2 = PyUnicode_GET_LENGTH(substring);
10003
10004 switch(kind) {
10005 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010006 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
10007 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010008 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +020010009 else
10010 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010011 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010012 break;
10013 case PyUnicode_2BYTE_KIND:
10014 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010015 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016 break;
10017 case PyUnicode_4BYTE_KIND:
10018 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +010010019 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010020 break;
10021 default:
10022 out = NULL;
10023 }
10024 if (kind1 != kind)
10025 PyMem_Free(buf1);
10026 if (kind2 != kind)
10027 PyMem_Free(buf2);
10028 return out;
10029}
10030
10031static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010032anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10033 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010034{
10035 switch(kind) {
10036 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010037 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10038 return asciilib_find(buf1, len1, buf2, len2, offset);
10039 else
10040 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010041 case PyUnicode_2BYTE_KIND:
10042 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10043 case PyUnicode_4BYTE_KIND:
10044 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10045 }
10046 assert(0);
10047 return -1;
10048}
10049
10050static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010051anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10052 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010053{
10054 switch(kind) {
10055 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010056 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10057 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10058 else
10059 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010060 case PyUnicode_2BYTE_KIND:
10061 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10062 case PyUnicode_4BYTE_KIND:
10063 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10064 }
10065 assert(0);
10066 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010067}
10068
Alexander Belopolsky40018472011-02-26 01:02:56 +000010069static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070replace(PyObject *self, PyObject *str1,
10071 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010072{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010073 PyObject *u;
10074 char *sbuf = PyUnicode_DATA(self);
10075 char *buf1 = PyUnicode_DATA(str1);
10076 char *buf2 = PyUnicode_DATA(str2);
10077 int srelease = 0, release1 = 0, release2 = 0;
10078 int skind = PyUnicode_KIND(self);
10079 int kind1 = PyUnicode_KIND(str1);
10080 int kind2 = PyUnicode_KIND(str2);
10081 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10082 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10083 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010084 int mayshrink;
10085 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010086
10087 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010088 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010090 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010091
Victor Stinner59de0ee2011-10-07 10:01:28 +020010092 if (str1 == str2)
10093 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 if (skind < kind1)
10095 /* substring too wide to be present */
10096 goto nothing;
10097
Victor Stinner49a0a212011-10-12 23:46:10 +020010098 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10099 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10100 /* Replacing str1 with str2 may cause a maxchar reduction in the
10101 result string. */
10102 mayshrink = (maxchar_str2 < maxchar);
10103 maxchar = Py_MAX(maxchar, maxchar_str2);
10104
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010105 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010106 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010107 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010108 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010109 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010111 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010112 Py_UCS4 u1, u2;
10113 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010114 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010115 if (findchar(sbuf, PyUnicode_KIND(self),
10116 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010117 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010118 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010120 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010122 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010123 rkind = PyUnicode_KIND(u);
10124 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10125 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010126 if (--maxcount < 0)
10127 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010128 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010129 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010130 }
10131 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 int rkind = skind;
10133 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010134
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010135 if (kind1 < rkind) {
10136 /* widen substring */
10137 buf1 = _PyUnicode_AsKind(str1, rkind);
10138 if (!buf1) goto error;
10139 release1 = 1;
10140 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010141 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010142 if (i < 0)
10143 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 if (rkind > kind2) {
10145 /* widen replacement */
10146 buf2 = _PyUnicode_AsKind(str2, rkind);
10147 if (!buf2) goto error;
10148 release2 = 1;
10149 }
10150 else if (rkind < kind2) {
10151 /* widen self and buf1 */
10152 rkind = kind2;
10153 if (release1) PyMem_Free(buf1);
10154 sbuf = _PyUnicode_AsKind(self, rkind);
10155 if (!sbuf) goto error;
10156 srelease = 1;
10157 buf1 = _PyUnicode_AsKind(str1, rkind);
10158 if (!buf1) goto error;
10159 release1 = 1;
10160 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010161 u = PyUnicode_New(slen, maxchar);
10162 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010164 assert(PyUnicode_KIND(u) == rkind);
10165 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010166
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010167 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010168 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010169 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010171 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010172 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010173
10174 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010175 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010176 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010177 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010178 if (i == -1)
10179 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010180 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010181 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010182 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010184 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010185 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010186 }
10187 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010188 Py_ssize_t n, i, j, ires;
10189 Py_ssize_t product, new_size;
10190 int rkind = skind;
10191 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010192
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010193 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010194 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010195 buf1 = _PyUnicode_AsKind(str1, rkind);
10196 if (!buf1) goto error;
10197 release1 = 1;
10198 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010199 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010200 if (n == 0)
10201 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010202 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010203 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010204 buf2 = _PyUnicode_AsKind(str2, rkind);
10205 if (!buf2) goto error;
10206 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010207 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010209 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010210 rkind = kind2;
10211 sbuf = _PyUnicode_AsKind(self, rkind);
10212 if (!sbuf) goto error;
10213 srelease = 1;
10214 if (release1) PyMem_Free(buf1);
10215 buf1 = _PyUnicode_AsKind(str1, rkind);
10216 if (!buf1) goto error;
10217 release1 = 1;
10218 }
10219 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10220 PyUnicode_GET_LENGTH(str1))); */
10221 product = n * (len2-len1);
10222 if ((product / (len2-len1)) != n) {
10223 PyErr_SetString(PyExc_OverflowError,
10224 "replace string is too long");
10225 goto error;
10226 }
10227 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010228 if (new_size == 0) {
10229 Py_INCREF(unicode_empty);
10230 u = unicode_empty;
10231 goto done;
10232 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010233 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10234 PyErr_SetString(PyExc_OverflowError,
10235 "replace string is too long");
10236 goto error;
10237 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010238 u = PyUnicode_New(new_size, maxchar);
10239 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010240 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010241 assert(PyUnicode_KIND(u) == rkind);
10242 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 ires = i = 0;
10244 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010245 while (n-- > 0) {
10246 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010247 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010248 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010249 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010250 if (j == -1)
10251 break;
10252 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010253 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010254 memcpy(res + rkind * ires,
10255 sbuf + rkind * i,
10256 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010257 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010258 }
10259 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010260 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010261 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010263 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010264 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010265 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010266 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010267 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010268 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010269 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010270 memcpy(res + rkind * ires,
10271 sbuf + rkind * i,
10272 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010273 }
10274 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010275 /* interleave */
10276 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010277 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010278 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010279 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010280 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010281 if (--n <= 0)
10282 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010283 memcpy(res + rkind * ires,
10284 sbuf + rkind * i,
10285 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010286 ires++;
10287 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010288 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010289 memcpy(res + rkind * ires,
10290 sbuf + rkind * i,
10291 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010292 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010293 }
10294
10295 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010296 unicode_adjust_maxchar(&u);
10297 if (u == NULL)
10298 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010300
10301 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010302 if (srelease)
10303 PyMem_FREE(sbuf);
10304 if (release1)
10305 PyMem_FREE(buf1);
10306 if (release2)
10307 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010308 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010309 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010310
Benjamin Peterson29060642009-01-31 22:14:21 +000010311 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010312 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010313 if (srelease)
10314 PyMem_FREE(sbuf);
10315 if (release1)
10316 PyMem_FREE(buf1);
10317 if (release2)
10318 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010319 if (PyUnicode_CheckExact(self)) {
10320 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010321 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010322 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010323 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010324 error:
10325 if (srelease && sbuf)
10326 PyMem_FREE(sbuf);
10327 if (release1 && buf1)
10328 PyMem_FREE(buf1);
10329 if (release2 && buf2)
10330 PyMem_FREE(buf2);
10331 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010332}
10333
10334/* --- Unicode Object Methods --------------------------------------------- */
10335
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010336PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010337 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010338\n\
10339Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010340characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341
10342static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010343unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010344{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010345 return fixup(self, fixtitle);
10346}
10347
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010348PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010349 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010350\n\
10351Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010352have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010353
10354static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010355unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010356{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010357 return fixup(self, fixcapitalize);
10358}
10359
10360#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010361PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010362 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010363\n\
10364Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010365normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010366
10367static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010368unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010369{
10370 PyObject *list;
10371 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010372 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010373
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374 /* Split into words */
10375 list = split(self, NULL, -1);
10376 if (!list)
10377 return NULL;
10378
10379 /* Capitalize each word */
10380 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010381 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010382 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010383 if (item == NULL)
10384 goto onError;
10385 Py_DECREF(PyList_GET_ITEM(list, i));
10386 PyList_SET_ITEM(list, i, item);
10387 }
10388
10389 /* Join the words to form a new string */
10390 item = PyUnicode_Join(NULL, list);
10391
Benjamin Peterson29060642009-01-31 22:14:21 +000010392 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010393 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010394 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010395}
10396#endif
10397
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010398/* Argument converter. Coerces to a single unicode character */
10399
10400static int
10401convert_uc(PyObject *obj, void *addr)
10402{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010403 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010404 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010405
Benjamin Peterson14339b62009-01-31 16:36:08 +000010406 uniobj = PyUnicode_FromObject(obj);
10407 if (uniobj == NULL) {
10408 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010409 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010410 return 0;
10411 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010413 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010414 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010415 Py_DECREF(uniobj);
10416 return 0;
10417 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010419 Py_DECREF(uniobj);
10420 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010421}
10422
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010423PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010424 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010425\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010426Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010427done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010428
10429static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010430unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010431{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010432 Py_ssize_t marg, left;
10433 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010434 Py_UCS4 fillchar = ' ';
10435
Victor Stinnere9a29352011-10-01 02:14:59 +020010436 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010438
Victor Stinnere9a29352011-10-01 02:14:59 +020010439 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010440 return NULL;
10441
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010442 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010443 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010444 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010445 }
10446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010447 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010448 left = marg / 2 + (marg & width & 1);
10449
Victor Stinner9310abb2011-10-05 00:59:23 +020010450 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010451}
10452
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010453/* This function assumes that str1 and str2 are readied by the caller. */
10454
Marc-André Lemburge5034372000-08-08 08:04:29 +000010455static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010456unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010457{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010458 int kind1, kind2;
10459 void *data1, *data2;
10460 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010462 kind1 = PyUnicode_KIND(str1);
10463 kind2 = PyUnicode_KIND(str2);
10464 data1 = PyUnicode_DATA(str1);
10465 data2 = PyUnicode_DATA(str2);
10466 len1 = PyUnicode_GET_LENGTH(str1);
10467 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010468
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010469 for (i = 0; i < len1 && i < len2; ++i) {
10470 Py_UCS4 c1, c2;
10471 c1 = PyUnicode_READ(kind1, data1, i);
10472 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010473
10474 if (c1 != c2)
10475 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010476 }
10477
10478 return (len1 < len2) ? -1 : (len1 != len2);
10479}
10480
Alexander Belopolsky40018472011-02-26 01:02:56 +000010481int
10482PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010483{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010484 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10485 if (PyUnicode_READY(left) == -1 ||
10486 PyUnicode_READY(right) == -1)
10487 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010488 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010489 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010490 PyErr_Format(PyExc_TypeError,
10491 "Can't compare %.100s and %.100s",
10492 left->ob_type->tp_name,
10493 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010494 return -1;
10495}
10496
Martin v. Löwis5b222132007-06-10 09:51:05 +000010497int
10498PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10499{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010500 Py_ssize_t i;
10501 int kind;
10502 void *data;
10503 Py_UCS4 chr;
10504
Victor Stinner910337b2011-10-03 03:20:16 +020010505 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010506 if (PyUnicode_READY(uni) == -1)
10507 return -1;
10508 kind = PyUnicode_KIND(uni);
10509 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010510 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010511 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10512 if (chr != str[i])
10513 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010514 /* This check keeps Python strings that end in '\0' from comparing equal
10515 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010516 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010517 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010518 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010519 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010520 return 0;
10521}
10522
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010523
Benjamin Peterson29060642009-01-31 22:14:21 +000010524#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010525 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010526
Alexander Belopolsky40018472011-02-26 01:02:56 +000010527PyObject *
10528PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010529{
10530 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010531
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010532 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10533 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010534 if (PyUnicode_READY(left) == -1 ||
10535 PyUnicode_READY(right) == -1)
10536 return NULL;
10537 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10538 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010539 if (op == Py_EQ) {
10540 Py_INCREF(Py_False);
10541 return Py_False;
10542 }
10543 if (op == Py_NE) {
10544 Py_INCREF(Py_True);
10545 return Py_True;
10546 }
10547 }
10548 if (left == right)
10549 result = 0;
10550 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010551 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010552
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010553 /* Convert the return value to a Boolean */
10554 switch (op) {
10555 case Py_EQ:
10556 v = TEST_COND(result == 0);
10557 break;
10558 case Py_NE:
10559 v = TEST_COND(result != 0);
10560 break;
10561 case Py_LE:
10562 v = TEST_COND(result <= 0);
10563 break;
10564 case Py_GE:
10565 v = TEST_COND(result >= 0);
10566 break;
10567 case Py_LT:
10568 v = TEST_COND(result == -1);
10569 break;
10570 case Py_GT:
10571 v = TEST_COND(result == 1);
10572 break;
10573 default:
10574 PyErr_BadArgument();
10575 return NULL;
10576 }
10577 Py_INCREF(v);
10578 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010579 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010580
Brian Curtindfc80e32011-08-10 20:28:54 -050010581 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010582}
10583
Alexander Belopolsky40018472011-02-26 01:02:56 +000010584int
10585PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010586{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010587 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010588 int kind1, kind2, kind;
10589 void *buf1, *buf2;
10590 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010591 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010592
10593 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010594 sub = PyUnicode_FromObject(element);
10595 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010596 PyErr_Format(PyExc_TypeError,
10597 "'in <string>' requires string as left operand, not %s",
10598 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010599 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010600 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010601 if (PyUnicode_READY(sub) == -1)
10602 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010603
Thomas Wouters477c8d52006-05-27 19:21:47 +000010604 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010605 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010606 Py_DECREF(sub);
10607 return -1;
10608 }
10609
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010610 kind1 = PyUnicode_KIND(str);
10611 kind2 = PyUnicode_KIND(sub);
10612 kind = kind1 > kind2 ? kind1 : kind2;
10613 buf1 = PyUnicode_DATA(str);
10614 buf2 = PyUnicode_DATA(sub);
10615 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010616 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010617 if (!buf1) {
10618 Py_DECREF(sub);
10619 return -1;
10620 }
10621 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010622 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010623 if (!buf2) {
10624 Py_DECREF(sub);
10625 if (kind1 != kind) PyMem_Free(buf1);
10626 return -1;
10627 }
10628 len1 = PyUnicode_GET_LENGTH(str);
10629 len2 = PyUnicode_GET_LENGTH(sub);
10630
10631 switch(kind) {
10632 case PyUnicode_1BYTE_KIND:
10633 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10634 break;
10635 case PyUnicode_2BYTE_KIND:
10636 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10637 break;
10638 case PyUnicode_4BYTE_KIND:
10639 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10640 break;
10641 default:
10642 result = -1;
10643 assert(0);
10644 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010645
10646 Py_DECREF(str);
10647 Py_DECREF(sub);
10648
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010649 if (kind1 != kind)
10650 PyMem_Free(buf1);
10651 if (kind2 != kind)
10652 PyMem_Free(buf2);
10653
Guido van Rossum403d68b2000-03-13 15:55:09 +000010654 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010655}
10656
Guido van Rossumd57fd912000-03-10 22:53:23 +000010657/* Concat to string or Unicode object giving a new Unicode object. */
10658
Alexander Belopolsky40018472011-02-26 01:02:56 +000010659PyObject *
10660PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010661{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010662 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010663 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010664
10665 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010666 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010667 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010668 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010669 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010671 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010672
10673 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010674 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010675 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010676 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010677 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010678 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010679 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010680 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010681 }
10682
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010683 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010684 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10685 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010686
Guido van Rossumd57fd912000-03-10 22:53:23 +000010687 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010688 w = PyUnicode_New(
10689 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10690 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010691 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010692 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010693 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10694 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010695 Py_DECREF(u);
10696 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010697 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010698 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010699
Benjamin Peterson29060642009-01-31 22:14:21 +000010700 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010701 Py_XDECREF(u);
10702 Py_XDECREF(v);
10703 return NULL;
10704}
10705
Victor Stinnerb0923652011-10-04 01:17:31 +020010706static void
10707unicode_append_inplace(PyObject **p_left, PyObject *right)
10708{
10709 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010710
10711 assert(PyUnicode_IS_READY(*p_left));
10712 assert(PyUnicode_IS_READY(right));
10713
10714 left_len = PyUnicode_GET_LENGTH(*p_left);
10715 right_len = PyUnicode_GET_LENGTH(right);
10716 if (left_len > PY_SSIZE_T_MAX - right_len) {
10717 PyErr_SetString(PyExc_OverflowError,
10718 "strings are too large to concat");
10719 goto error;
10720 }
10721 new_len = left_len + right_len;
10722
10723 /* Now we own the last reference to 'left', so we can resize it
10724 * in-place.
10725 */
10726 if (unicode_resize(p_left, new_len) != 0) {
10727 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10728 * deallocated so it cannot be put back into
10729 * 'variable'. The MemoryError is raised when there
10730 * is no value in 'variable', which might (very
10731 * remotely) be a cause of incompatibilities.
10732 */
10733 goto error;
10734 }
10735 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010736 copy_characters(*p_left, left_len, right, 0, right_len);
10737 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010738 return;
10739
10740error:
10741 Py_DECREF(*p_left);
10742 *p_left = NULL;
10743}
10744
Walter Dörwald1ab83302007-05-18 17:15:44 +000010745void
Victor Stinner23e56682011-10-03 03:54:37 +020010746PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010747{
Victor Stinner23e56682011-10-03 03:54:37 +020010748 PyObject *left, *res;
10749
10750 if (p_left == NULL) {
10751 if (!PyErr_Occurred())
10752 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010753 return;
10754 }
Victor Stinner23e56682011-10-03 03:54:37 +020010755 left = *p_left;
10756 if (right == NULL || !PyUnicode_Check(left)) {
10757 if (!PyErr_Occurred())
10758 PyErr_BadInternalCall();
10759 goto error;
10760 }
10761
Victor Stinnere1335c72011-10-04 20:53:03 +020010762 if (PyUnicode_READY(left))
10763 goto error;
10764 if (PyUnicode_READY(right))
10765 goto error;
10766
Victor Stinner23e56682011-10-03 03:54:37 +020010767 if (PyUnicode_CheckExact(left) && left != unicode_empty
10768 && PyUnicode_CheckExact(right) && right != unicode_empty
10769 && unicode_resizable(left)
10770 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10771 || _PyUnicode_WSTR(left) != NULL))
10772 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010773 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10774 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010775 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010776 not so different than duplicating the string. */
10777 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010778 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010779 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010780 if (p_left != NULL)
10781 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010782 return;
10783 }
10784 }
10785
10786 res = PyUnicode_Concat(left, right);
10787 if (res == NULL)
10788 goto error;
10789 Py_DECREF(left);
10790 *p_left = res;
10791 return;
10792
10793error:
10794 Py_DECREF(*p_left);
10795 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010796}
10797
10798void
10799PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10800{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010801 PyUnicode_Append(pleft, right);
10802 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010803}
10804
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010805PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010806 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010807\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010808Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010809string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010810interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010811
10812static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010813unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010814{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010815 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010816 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010817 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010818 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010819 int kind1, kind2, kind;
10820 void *buf1, *buf2;
10821 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010822
Jesus Ceaac451502011-04-20 17:09:23 +020010823 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10824 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010825 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010826
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010827 kind1 = PyUnicode_KIND(self);
10828 kind2 = PyUnicode_KIND(substring);
10829 kind = kind1 > kind2 ? kind1 : kind2;
10830 buf1 = PyUnicode_DATA(self);
10831 buf2 = PyUnicode_DATA(substring);
10832 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010833 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010834 if (!buf1) {
10835 Py_DECREF(substring);
10836 return NULL;
10837 }
10838 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010839 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010840 if (!buf2) {
10841 Py_DECREF(substring);
10842 if (kind1 != kind) PyMem_Free(buf1);
10843 return NULL;
10844 }
10845 len1 = PyUnicode_GET_LENGTH(self);
10846 len2 = PyUnicode_GET_LENGTH(substring);
10847
10848 ADJUST_INDICES(start, end, len1);
10849 switch(kind) {
10850 case PyUnicode_1BYTE_KIND:
10851 iresult = ucs1lib_count(
10852 ((Py_UCS1*)buf1) + start, end - start,
10853 buf2, len2, PY_SSIZE_T_MAX
10854 );
10855 break;
10856 case PyUnicode_2BYTE_KIND:
10857 iresult = ucs2lib_count(
10858 ((Py_UCS2*)buf1) + start, end - start,
10859 buf2, len2, PY_SSIZE_T_MAX
10860 );
10861 break;
10862 case PyUnicode_4BYTE_KIND:
10863 iresult = ucs4lib_count(
10864 ((Py_UCS4*)buf1) + start, end - start,
10865 buf2, len2, PY_SSIZE_T_MAX
10866 );
10867 break;
10868 default:
10869 assert(0); iresult = 0;
10870 }
10871
10872 result = PyLong_FromSsize_t(iresult);
10873
10874 if (kind1 != kind)
10875 PyMem_Free(buf1);
10876 if (kind2 != kind)
10877 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878
10879 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010880
Guido van Rossumd57fd912000-03-10 22:53:23 +000010881 return result;
10882}
10883
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010884PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010885 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010886\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010887Encode S using the codec registered for encoding. Default encoding\n\
10888is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010889handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010890a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10891'xmlcharrefreplace' as well as any other name registered with\n\
10892codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010893
10894static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010895unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010896{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010897 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010898 char *encoding = NULL;
10899 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010900
Benjamin Peterson308d6372009-09-18 21:42:35 +000010901 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10902 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010903 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010904 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010905}
10906
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010907PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010908 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010909\n\
10910Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010911If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010912
10913static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010914unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010915{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 Py_ssize_t i, j, line_pos, src_len, incr;
10917 Py_UCS4 ch;
10918 PyObject *u;
10919 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010920 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010921 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010922 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923
10924 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010925 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010926
Antoine Pitrou22425222011-10-04 19:10:51 +020010927 if (PyUnicode_READY(self) == -1)
10928 return NULL;
10929
Thomas Wouters7e474022000-07-16 12:04:32 +000010930 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 src_len = PyUnicode_GET_LENGTH(self);
10932 i = j = line_pos = 0;
10933 kind = PyUnicode_KIND(self);
10934 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010935 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010936 for (; i < src_len; i++) {
10937 ch = PyUnicode_READ(kind, src_data, i);
10938 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010939 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010940 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010941 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010942 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010943 goto overflow;
10944 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010945 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010946 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010947 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010948 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010949 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010950 goto overflow;
10951 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010953 if (ch == '\n' || ch == '\r')
10954 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010955 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010956 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010957 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010958 Py_INCREF(self);
10959 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010960 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010961
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010963 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010964 if (!u)
10965 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010966 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010967
Antoine Pitroue71d5742011-10-04 15:55:09 +020010968 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010969
Antoine Pitroue71d5742011-10-04 15:55:09 +020010970 for (; i < src_len; i++) {
10971 ch = PyUnicode_READ(kind, src_data, i);
10972 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010973 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010974 incr = tabsize - (line_pos % tabsize);
10975 line_pos += incr;
10976 while (incr--) {
10977 PyUnicode_WRITE(kind, dest_data, j, ' ');
10978 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010979 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010980 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010981 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010982 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010983 line_pos++;
10984 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010985 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010986 if (ch == '\n' || ch == '\r')
10987 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010989 }
10990 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010991#ifndef DONT_MAKE_RESULT_READY
10992 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010993 Py_DECREF(u);
10994 return NULL;
10995 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010996#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010997 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010010998 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010999
Antoine Pitroue71d5742011-10-04 15:55:09 +020011000 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000011001 PyErr_SetString(PyExc_OverflowError, "new string is too long");
11002 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003}
11004
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011005PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011006 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007\n\
11008Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080011009such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011010arguments start and end are interpreted as in slice notation.\n\
11011\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011012Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011013
11014static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011015unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011016{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011017 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011018 Py_ssize_t start;
11019 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000011020 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011021
Jesus Ceaac451502011-04-20 17:09:23 +020011022 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
11023 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011024 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011025
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011026 if (PyUnicode_READY(self) == -1)
11027 return NULL;
11028 if (PyUnicode_READY(substring) == -1)
11029 return NULL;
11030
Victor Stinner7931d9a2011-11-04 00:22:48 +010011031 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011032
11033 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011034
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011035 if (result == -2)
11036 return NULL;
11037
Christian Heimes217cfd12007-12-02 14:31:20 +000011038 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011039}
11040
11041static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011042unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011043{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011044 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11045 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011047 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011048}
11049
Guido van Rossumc2504932007-09-18 19:42:40 +000011050/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011051 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011052static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011053unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011054{
Guido van Rossumc2504932007-09-18 19:42:40 +000011055 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011056 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011057
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011058 if (_PyUnicode_HASH(self) != -1)
11059 return _PyUnicode_HASH(self);
11060 if (PyUnicode_READY(self) == -1)
11061 return -1;
11062 len = PyUnicode_GET_LENGTH(self);
11063
11064 /* The hash function as a macro, gets expanded three times below. */
11065#define HASH(P) \
11066 x = (Py_uhash_t)*P << 7; \
11067 while (--len >= 0) \
11068 x = (1000003*x) ^ (Py_uhash_t)*P++;
11069
11070 switch (PyUnicode_KIND(self)) {
11071 case PyUnicode_1BYTE_KIND: {
11072 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11073 HASH(c);
11074 break;
11075 }
11076 case PyUnicode_2BYTE_KIND: {
11077 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11078 HASH(s);
11079 break;
11080 }
11081 default: {
11082 Py_UCS4 *l;
11083 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11084 "Impossible switch case in unicode_hash");
11085 l = PyUnicode_4BYTE_DATA(self);
11086 HASH(l);
11087 break;
11088 }
11089 }
11090 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11091
Guido van Rossumc2504932007-09-18 19:42:40 +000011092 if (x == -1)
11093 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011095 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011096}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011097#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011098
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011099PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011100 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011101\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011102Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103
11104static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011105unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011106{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011107 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011108 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011109 Py_ssize_t start;
11110 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011111
Jesus Ceaac451502011-04-20 17:09:23 +020011112 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11113 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011115
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011116 if (PyUnicode_READY(self) == -1)
11117 return NULL;
11118 if (PyUnicode_READY(substring) == -1)
11119 return NULL;
11120
Victor Stinner7931d9a2011-11-04 00:22:48 +010011121 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122
11123 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011125 if (result == -2)
11126 return NULL;
11127
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128 if (result < 0) {
11129 PyErr_SetString(PyExc_ValueError, "substring not found");
11130 return NULL;
11131 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011132
Christian Heimes217cfd12007-12-02 14:31:20 +000011133 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134}
11135
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011136PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011137 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011139Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011140at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011141
11142static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011143unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011144{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011145 Py_ssize_t i, length;
11146 int kind;
11147 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011148 int cased;
11149
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011150 if (PyUnicode_READY(self) == -1)
11151 return NULL;
11152 length = PyUnicode_GET_LENGTH(self);
11153 kind = PyUnicode_KIND(self);
11154 data = PyUnicode_DATA(self);
11155
Guido van Rossumd57fd912000-03-10 22:53:23 +000011156 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011157 if (length == 1)
11158 return PyBool_FromLong(
11159 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011161 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011162 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011163 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011164
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 for (i = 0; i < length; i++) {
11167 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011168
Benjamin Peterson29060642009-01-31 22:14:21 +000011169 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11170 return PyBool_FromLong(0);
11171 else if (!cased && Py_UNICODE_ISLOWER(ch))
11172 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011173 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011174 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011175}
11176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011177PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011178 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011179\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011180Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011181at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011182
11183static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011184unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011185{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011186 Py_ssize_t i, length;
11187 int kind;
11188 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 int cased;
11190
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011191 if (PyUnicode_READY(self) == -1)
11192 return NULL;
11193 length = PyUnicode_GET_LENGTH(self);
11194 kind = PyUnicode_KIND(self);
11195 data = PyUnicode_DATA(self);
11196
Guido van Rossumd57fd912000-03-10 22:53:23 +000011197 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011198 if (length == 1)
11199 return PyBool_FromLong(
11200 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011201
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011202 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011203 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011204 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011205
Guido van Rossumd57fd912000-03-10 22:53:23 +000011206 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011207 for (i = 0; i < length; i++) {
11208 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011209
Benjamin Peterson29060642009-01-31 22:14:21 +000011210 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11211 return PyBool_FromLong(0);
11212 else if (!cased && Py_UNICODE_ISUPPER(ch))
11213 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011214 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011215 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011216}
11217
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011218PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011219 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011220\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011221Return True if S is a titlecased string and there is at least one\n\
11222character in S, i.e. upper- and titlecase characters may only\n\
11223follow uncased characters and lowercase characters only cased ones.\n\
11224Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225
11226static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011227unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011229 Py_ssize_t i, length;
11230 int kind;
11231 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011232 int cased, previous_is_cased;
11233
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011234 if (PyUnicode_READY(self) == -1)
11235 return NULL;
11236 length = PyUnicode_GET_LENGTH(self);
11237 kind = PyUnicode_KIND(self);
11238 data = PyUnicode_DATA(self);
11239
Guido van Rossumd57fd912000-03-10 22:53:23 +000011240 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011241 if (length == 1) {
11242 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11243 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11244 (Py_UNICODE_ISUPPER(ch) != 0));
11245 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011246
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011247 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011248 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011249 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011250
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251 cased = 0;
11252 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011253 for (i = 0; i < length; i++) {
11254 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011255
Benjamin Peterson29060642009-01-31 22:14:21 +000011256 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11257 if (previous_is_cased)
11258 return PyBool_FromLong(0);
11259 previous_is_cased = 1;
11260 cased = 1;
11261 }
11262 else if (Py_UNICODE_ISLOWER(ch)) {
11263 if (!previous_is_cased)
11264 return PyBool_FromLong(0);
11265 previous_is_cased = 1;
11266 cased = 1;
11267 }
11268 else
11269 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011270 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011271 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272}
11273
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011274PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011276\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011277Return True if all characters in S are whitespace\n\
11278and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011279
11280static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011281unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011282{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011283 Py_ssize_t i, length;
11284 int kind;
11285 void *data;
11286
11287 if (PyUnicode_READY(self) == -1)
11288 return NULL;
11289 length = PyUnicode_GET_LENGTH(self);
11290 kind = PyUnicode_KIND(self);
11291 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011292
Guido van Rossumd57fd912000-03-10 22:53:23 +000011293 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 if (length == 1)
11295 return PyBool_FromLong(
11296 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011297
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011298 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011299 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011300 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011301
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011302 for (i = 0; i < length; i++) {
11303 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011304 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011305 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011306 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011307 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011308}
11309
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011310PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011313Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011314and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011315
11316static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011317unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011319 Py_ssize_t i, length;
11320 int kind;
11321 void *data;
11322
11323 if (PyUnicode_READY(self) == -1)
11324 return NULL;
11325 length = PyUnicode_GET_LENGTH(self);
11326 kind = PyUnicode_KIND(self);
11327 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011329 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011330 if (length == 1)
11331 return PyBool_FromLong(
11332 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011333
11334 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011335 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011336 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011337
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011338 for (i = 0; i < length; i++) {
11339 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011340 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011341 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011342 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011343}
11344
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011345PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011346 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011347\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011348Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011349and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011350
11351static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011352unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011353{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011354 int kind;
11355 void *data;
11356 Py_ssize_t len, i;
11357
11358 if (PyUnicode_READY(self) == -1)
11359 return NULL;
11360
11361 kind = PyUnicode_KIND(self);
11362 data = PyUnicode_DATA(self);
11363 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011364
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011365 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011366 if (len == 1) {
11367 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11368 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11369 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011370
11371 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011372 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011373 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011375 for (i = 0; i < len; i++) {
11376 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011377 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011378 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011379 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011380 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011381}
11382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011383PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011386Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011387False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011388
11389static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011390unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011392 Py_ssize_t i, length;
11393 int kind;
11394 void *data;
11395
11396 if (PyUnicode_READY(self) == -1)
11397 return NULL;
11398 length = PyUnicode_GET_LENGTH(self);
11399 kind = PyUnicode_KIND(self);
11400 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401
Guido van Rossumd57fd912000-03-10 22:53:23 +000011402 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011403 if (length == 1)
11404 return PyBool_FromLong(
11405 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011406
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011407 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011408 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011409 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011411 for (i = 0; i < length; i++) {
11412 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011413 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011414 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011415 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011416}
11417
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011418PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011419 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011420\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011421Return True if all characters in S are digits\n\
11422and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011423
11424static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011425unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011427 Py_ssize_t i, length;
11428 int kind;
11429 void *data;
11430
11431 if (PyUnicode_READY(self) == -1)
11432 return NULL;
11433 length = PyUnicode_GET_LENGTH(self);
11434 kind = PyUnicode_KIND(self);
11435 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 if (length == 1) {
11439 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11440 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11441 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011442
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011443 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011444 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011445 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011447 for (i = 0; i < length; i++) {
11448 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011449 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011450 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011451 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452}
11453
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011454PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011456\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011457Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011458False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011459
11460static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011461unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011463 Py_ssize_t i, length;
11464 int kind;
11465 void *data;
11466
11467 if (PyUnicode_READY(self) == -1)
11468 return NULL;
11469 length = PyUnicode_GET_LENGTH(self);
11470 kind = PyUnicode_KIND(self);
11471 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011472
Guido van Rossumd57fd912000-03-10 22:53:23 +000011473 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011474 if (length == 1)
11475 return PyBool_FromLong(
11476 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011477
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011478 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011479 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011480 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011481
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011482 for (i = 0; i < length; i++) {
11483 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011484 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011485 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011486 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011487}
11488
Martin v. Löwis47383402007-08-15 07:32:56 +000011489int
11490PyUnicode_IsIdentifier(PyObject *self)
11491{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011492 int kind;
11493 void *data;
11494 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011495 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011496
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011497 if (PyUnicode_READY(self) == -1) {
11498 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011499 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011500 }
11501
11502 /* Special case for empty strings */
11503 if (PyUnicode_GET_LENGTH(self) == 0)
11504 return 0;
11505 kind = PyUnicode_KIND(self);
11506 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011507
11508 /* PEP 3131 says that the first character must be in
11509 XID_Start and subsequent characters in XID_Continue,
11510 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011511 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011512 letters, digits, underscore). However, given the current
11513 definition of XID_Start and XID_Continue, it is sufficient
11514 to check just for these, except that _ must be allowed
11515 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011516 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011517 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011518 return 0;
11519
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011520 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011521 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011522 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011523 return 1;
11524}
11525
11526PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011527 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011528\n\
11529Return True if S is a valid identifier according\n\
11530to the language definition.");
11531
11532static PyObject*
11533unicode_isidentifier(PyObject *self)
11534{
11535 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11536}
11537
Georg Brandl559e5d72008-06-11 18:37:52 +000011538PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011539 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011540\n\
11541Return True if all characters in S are considered\n\
11542printable in repr() or S is empty, False otherwise.");
11543
11544static PyObject*
11545unicode_isprintable(PyObject *self)
11546{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011547 Py_ssize_t i, length;
11548 int kind;
11549 void *data;
11550
11551 if (PyUnicode_READY(self) == -1)
11552 return NULL;
11553 length = PyUnicode_GET_LENGTH(self);
11554 kind = PyUnicode_KIND(self);
11555 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011556
11557 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011558 if (length == 1)
11559 return PyBool_FromLong(
11560 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011561
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011562 for (i = 0; i < length; i++) {
11563 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011564 Py_RETURN_FALSE;
11565 }
11566 }
11567 Py_RETURN_TRUE;
11568}
11569
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011570PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011571 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572\n\
11573Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011574iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011575
11576static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011577unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011578{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011579 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011580}
11581
Martin v. Löwis18e16552006-02-15 17:27:45 +000011582static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011583unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011585 if (PyUnicode_READY(self) == -1)
11586 return -1;
11587 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011588}
11589
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011590PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011591 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011592\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011593Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011594done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
11596static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011597unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011599 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011600 Py_UCS4 fillchar = ' ';
11601
11602 if (PyUnicode_READY(self) == -1)
11603 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011604
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011605 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011606 return NULL;
11607
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011608 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011609 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011610 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011611 }
11612
Victor Stinner7931d9a2011-11-04 00:22:48 +010011613 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011614}
11615
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011616PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011617 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011618\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011619Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011620
11621static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011622unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011623{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011624 return fixup(self, fixlower);
11625}
11626
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011627#define LEFTSTRIP 0
11628#define RIGHTSTRIP 1
11629#define BOTHSTRIP 2
11630
11631/* Arrays indexed by above */
11632static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11633
11634#define STRIPNAME(i) (stripformat[i]+3)
11635
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011636/* externally visible for str.strip(unicode) */
11637PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011638_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011639{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011640 void *data;
11641 int kind;
11642 Py_ssize_t i, j, len;
11643 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011644
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011645 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11646 return NULL;
11647
11648 kind = PyUnicode_KIND(self);
11649 data = PyUnicode_DATA(self);
11650 len = PyUnicode_GET_LENGTH(self);
11651 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11652 PyUnicode_DATA(sepobj),
11653 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011654
Benjamin Peterson14339b62009-01-31 16:36:08 +000011655 i = 0;
11656 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011657 while (i < len &&
11658 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011659 i++;
11660 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011661 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011662
Benjamin Peterson14339b62009-01-31 16:36:08 +000011663 j = len;
11664 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011665 do {
11666 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667 } while (j >= i &&
11668 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011669 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011670 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011671
Victor Stinner7931d9a2011-11-04 00:22:48 +010011672 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011673}
11674
11675PyObject*
11676PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11677{
11678 unsigned char *data;
11679 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011680 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011681
Victor Stinnerde636f32011-10-01 03:55:54 +020011682 if (PyUnicode_READY(self) == -1)
11683 return NULL;
11684
11685 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11686
Victor Stinner12bab6d2011-10-01 01:53:49 +020011687 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011688 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011689 if (PyUnicode_CheckExact(self)) {
11690 Py_INCREF(self);
11691 return self;
11692 }
11693 else
11694 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011695 }
11696
Victor Stinner12bab6d2011-10-01 01:53:49 +020011697 length = end - start;
11698 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011699 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011700
Victor Stinnerde636f32011-10-01 03:55:54 +020011701 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011702 PyErr_SetString(PyExc_IndexError, "string index out of range");
11703 return NULL;
11704 }
11705
Victor Stinnerb9275c12011-10-05 14:01:42 +020011706 if (PyUnicode_IS_ASCII(self)) {
11707 kind = PyUnicode_KIND(self);
11708 data = PyUnicode_1BYTE_DATA(self);
11709 return unicode_fromascii(data + start, length);
11710 }
11711 else {
11712 kind = PyUnicode_KIND(self);
11713 data = PyUnicode_1BYTE_DATA(self);
11714 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011715 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011716 length);
11717 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011718}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011719
11720static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011721do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011722{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011723 int kind;
11724 void *data;
11725 Py_ssize_t len, i, j;
11726
11727 if (PyUnicode_READY(self) == -1)
11728 return NULL;
11729
11730 kind = PyUnicode_KIND(self);
11731 data = PyUnicode_DATA(self);
11732 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011733
Benjamin Peterson14339b62009-01-31 16:36:08 +000011734 i = 0;
11735 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011736 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011737 i++;
11738 }
11739 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011740
Benjamin Peterson14339b62009-01-31 16:36:08 +000011741 j = len;
11742 if (striptype != LEFTSTRIP) {
11743 do {
11744 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011745 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011746 j++;
11747 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011748
Victor Stinner7931d9a2011-11-04 00:22:48 +010011749 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011750}
11751
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011752
11753static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011754do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011756 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011757
Benjamin Peterson14339b62009-01-31 16:36:08 +000011758 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11759 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760
Benjamin Peterson14339b62009-01-31 16:36:08 +000011761 if (sep != NULL && sep != Py_None) {
11762 if (PyUnicode_Check(sep))
11763 return _PyUnicode_XStrip(self, striptype, sep);
11764 else {
11765 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011766 "%s arg must be None or str",
11767 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011768 return NULL;
11769 }
11770 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771
Benjamin Peterson14339b62009-01-31 16:36:08 +000011772 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011773}
11774
11775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011776PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011777 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011778\n\
11779Return a copy of the string S with leading and trailing\n\
11780whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011781If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011782
11783static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011784unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011785{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011786 if (PyTuple_GET_SIZE(args) == 0)
11787 return do_strip(self, BOTHSTRIP); /* Common case */
11788 else
11789 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011790}
11791
11792
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011793PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011794 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011795\n\
11796Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011797If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011798
11799static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011800unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011801{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011802 if (PyTuple_GET_SIZE(args) == 0)
11803 return do_strip(self, LEFTSTRIP); /* Common case */
11804 else
11805 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011806}
11807
11808
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011809PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011810 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011811\n\
11812Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011813If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011814
11815static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011816unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011817{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011818 if (PyTuple_GET_SIZE(args) == 0)
11819 return do_strip(self, RIGHTSTRIP); /* Common case */
11820 else
11821 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011822}
11823
11824
Guido van Rossumd57fd912000-03-10 22:53:23 +000011825static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011826unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011827{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011828 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011829 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011830
Georg Brandl222de0f2009-04-12 12:01:50 +000011831 if (len < 1) {
11832 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011833 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011834 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011835
Tim Peters7a29bd52001-09-12 03:03:31 +000011836 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011837 /* no repeat, return original string */
11838 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011839 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840 }
Tim Peters8f422462000-09-09 06:13:41 +000011841
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 if (PyUnicode_READY(str) == -1)
11843 return NULL;
11844
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011845 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011846 PyErr_SetString(PyExc_OverflowError,
11847 "repeated string is too long");
11848 return NULL;
11849 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011850 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011851
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011852 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 if (!u)
11854 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011855 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011856
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011857 if (PyUnicode_GET_LENGTH(str) == 1) {
11858 const int kind = PyUnicode_KIND(str);
11859 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11860 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011861 if (kind == PyUnicode_1BYTE_KIND)
11862 memset(to, (unsigned char)fill_char, len);
11863 else {
11864 for (n = 0; n < len; ++n)
11865 PyUnicode_WRITE(kind, to, n, fill_char);
11866 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011867 }
11868 else {
11869 /* number of characters copied this far */
11870 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011871 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011872 char *to = (char *) PyUnicode_DATA(u);
11873 Py_MEMCPY(to, PyUnicode_DATA(str),
11874 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011875 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011876 n = (done <= nchars-done) ? done : nchars-done;
11877 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011878 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011879 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880 }
11881
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011882 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011883 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011884}
11885
Alexander Belopolsky40018472011-02-26 01:02:56 +000011886PyObject *
11887PyUnicode_Replace(PyObject *obj,
11888 PyObject *subobj,
11889 PyObject *replobj,
11890 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011891{
11892 PyObject *self;
11893 PyObject *str1;
11894 PyObject *str2;
11895 PyObject *result;
11896
11897 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011898 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011899 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011900 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011901 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011902 Py_DECREF(self);
11903 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904 }
11905 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011906 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011907 Py_DECREF(self);
11908 Py_DECREF(str1);
11909 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011910 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011911 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011912 Py_DECREF(self);
11913 Py_DECREF(str1);
11914 Py_DECREF(str2);
11915 return result;
11916}
11917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011918PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011919 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920\n\
11921Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011922old replaced by new. If the optional argument count is\n\
11923given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011924
11925static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011926unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011927{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011928 PyObject *str1;
11929 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011930 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011931 PyObject *result;
11932
Martin v. Löwis18e16552006-02-15 17:27:45 +000011933 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011934 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011935 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011936 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011937 str1 = PyUnicode_FromObject(str1);
11938 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11939 return NULL;
11940 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011941 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011942 Py_DECREF(str1);
11943 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011944 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011945
11946 result = replace(self, str1, str2, maxcount);
11947
11948 Py_DECREF(str1);
11949 Py_DECREF(str2);
11950 return result;
11951}
11952
Alexander Belopolsky40018472011-02-26 01:02:56 +000011953static PyObject *
11954unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011955{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011956 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011957 Py_ssize_t isize;
11958 Py_ssize_t osize, squote, dquote, i, o;
11959 Py_UCS4 max, quote;
11960 int ikind, okind;
11961 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011962
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011963 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011964 return NULL;
11965
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011966 isize = PyUnicode_GET_LENGTH(unicode);
11967 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011969 /* Compute length of output, quote characters, and
11970 maximum character */
11971 osize = 2; /* quotes */
11972 max = 127;
11973 squote = dquote = 0;
11974 ikind = PyUnicode_KIND(unicode);
11975 for (i = 0; i < isize; i++) {
11976 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11977 switch (ch) {
11978 case '\'': squote++; osize++; break;
11979 case '"': dquote++; osize++; break;
11980 case '\\': case '\t': case '\r': case '\n':
11981 osize += 2; break;
11982 default:
11983 /* Fast-path ASCII */
11984 if (ch < ' ' || ch == 0x7f)
11985 osize += 4; /* \xHH */
11986 else if (ch < 0x7f)
11987 osize++;
11988 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11989 osize++;
11990 max = ch > max ? ch : max;
11991 }
11992 else if (ch < 0x100)
11993 osize += 4; /* \xHH */
11994 else if (ch < 0x10000)
11995 osize += 6; /* \uHHHH */
11996 else
11997 osize += 10; /* \uHHHHHHHH */
11998 }
11999 }
12000
12001 quote = '\'';
12002 if (squote) {
12003 if (dquote)
12004 /* Both squote and dquote present. Use squote,
12005 and escape them */
12006 osize += squote;
12007 else
12008 quote = '"';
12009 }
12010
12011 repr = PyUnicode_New(osize, max);
12012 if (repr == NULL)
12013 return NULL;
12014 okind = PyUnicode_KIND(repr);
12015 odata = PyUnicode_DATA(repr);
12016
12017 PyUnicode_WRITE(okind, odata, 0, quote);
12018 PyUnicode_WRITE(okind, odata, osize-1, quote);
12019
12020 for (i = 0, o = 1; i < isize; i++) {
12021 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012022
12023 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012024 if ((ch == quote) || (ch == '\\')) {
12025 PyUnicode_WRITE(okind, odata, o++, '\\');
12026 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012027 continue;
12028 }
12029
Benjamin Peterson29060642009-01-31 22:14:21 +000012030 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012031 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012032 PyUnicode_WRITE(okind, odata, o++, '\\');
12033 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012034 }
12035 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012036 PyUnicode_WRITE(okind, odata, o++, '\\');
12037 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012038 }
12039 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012040 PyUnicode_WRITE(okind, odata, o++, '\\');
12041 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012042 }
12043
12044 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012045 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 PyUnicode_WRITE(okind, odata, o++, '\\');
12047 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012048 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12049 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012050 }
12051
Georg Brandl559e5d72008-06-11 18:37:52 +000012052 /* Copy ASCII characters as-is */
12053 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012054 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012055 }
12056
Benjamin Peterson29060642009-01-31 22:14:21 +000012057 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012058 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012059 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012060 (categories Z* and C* except ASCII space)
12061 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012062 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012063 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012064 if (ch <= 0xff) {
12065 PyUnicode_WRITE(okind, odata, o++, '\\');
12066 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012067 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12068 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012069 }
12070 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012071 else if (ch >= 0x10000) {
12072 PyUnicode_WRITE(okind, odata, o++, '\\');
12073 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012074 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12075 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12076 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12077 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12078 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12079 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12080 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12081 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012082 }
12083 /* Map 16-bit characters to '\uxxxx' */
12084 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012085 PyUnicode_WRITE(okind, odata, o++, '\\');
12086 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012087 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12088 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12089 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12090 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012091 }
12092 }
12093 /* Copy characters as-is */
12094 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012096 }
12097 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012098 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012099 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012100 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012101 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012102}
12103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012104PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012105 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106\n\
12107Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012108such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012109arguments start and end are interpreted as in slice notation.\n\
12110\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012111Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012112
12113static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012114unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012115{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012116 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012117 Py_ssize_t start;
12118 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012119 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012120
Jesus Ceaac451502011-04-20 17:09:23 +020012121 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12122 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012123 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012125 if (PyUnicode_READY(self) == -1)
12126 return NULL;
12127 if (PyUnicode_READY(substring) == -1)
12128 return NULL;
12129
Victor Stinner7931d9a2011-11-04 00:22:48 +010012130 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
12132 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012133
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012134 if (result == -2)
12135 return NULL;
12136
Christian Heimes217cfd12007-12-02 14:31:20 +000012137 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138}
12139
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012140PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012141 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012143Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144
12145static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012146unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012148 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012149 Py_ssize_t start;
12150 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012151 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012152
Jesus Ceaac451502011-04-20 17:09:23 +020012153 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12154 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012155 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012156
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012157 if (PyUnicode_READY(self) == -1)
12158 return NULL;
12159 if (PyUnicode_READY(substring) == -1)
12160 return NULL;
12161
Victor Stinner7931d9a2011-11-04 00:22:48 +010012162 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012163
12164 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012166 if (result == -2)
12167 return NULL;
12168
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169 if (result < 0) {
12170 PyErr_SetString(PyExc_ValueError, "substring not found");
12171 return NULL;
12172 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012173
Christian Heimes217cfd12007-12-02 14:31:20 +000012174 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012175}
12176
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012177PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012178 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012179\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012180Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012181done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012182
12183static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012184unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012185{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012186 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012187 Py_UCS4 fillchar = ' ';
12188
Victor Stinnere9a29352011-10-01 02:14:59 +020012189 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012190 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012191
Victor Stinnere9a29352011-10-01 02:14:59 +020012192 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012193 return NULL;
12194
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012195 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012196 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012197 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012198 }
12199
Victor Stinner7931d9a2011-11-04 00:22:48 +010012200 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012201}
12202
Alexander Belopolsky40018472011-02-26 01:02:56 +000012203PyObject *
12204PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012205{
12206 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012207
Guido van Rossumd57fd912000-03-10 22:53:23 +000012208 s = PyUnicode_FromObject(s);
12209 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012210 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012211 if (sep != NULL) {
12212 sep = PyUnicode_FromObject(sep);
12213 if (sep == NULL) {
12214 Py_DECREF(s);
12215 return NULL;
12216 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 }
12218
Victor Stinner9310abb2011-10-05 00:59:23 +020012219 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012220
12221 Py_DECREF(s);
12222 Py_XDECREF(sep);
12223 return result;
12224}
12225
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012226PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012227 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012228\n\
12229Return a list of the words in S, using sep as the\n\
12230delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012231splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012232whitespace string is a separator and empty strings are\n\
12233removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012234
12235static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012236unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012237{
12238 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012239 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012240
Martin v. Löwis18e16552006-02-15 17:27:45 +000012241 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012242 return NULL;
12243
12244 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012245 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012246 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012247 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012248 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012249 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012250}
12251
Thomas Wouters477c8d52006-05-27 19:21:47 +000012252PyObject *
12253PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12254{
12255 PyObject* str_obj;
12256 PyObject* sep_obj;
12257 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012258 int kind1, kind2, kind;
12259 void *buf1 = NULL, *buf2 = NULL;
12260 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012261
12262 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012263 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012264 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012265 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012266 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012267 Py_DECREF(str_obj);
12268 return NULL;
12269 }
12270
Victor Stinner14f8f022011-10-05 20:58:25 +020012271 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012272 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012273 kind = Py_MAX(kind1, kind2);
12274 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012275 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012276 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012277 if (!buf1)
12278 goto onError;
12279 buf2 = PyUnicode_DATA(sep_obj);
12280 if (kind2 != kind)
12281 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12282 if (!buf2)
12283 goto onError;
12284 len1 = PyUnicode_GET_LENGTH(str_obj);
12285 len2 = PyUnicode_GET_LENGTH(sep_obj);
12286
Victor Stinner14f8f022011-10-05 20:58:25 +020012287 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012289 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12290 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12291 else
12292 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012293 break;
12294 case PyUnicode_2BYTE_KIND:
12295 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12296 break;
12297 case PyUnicode_4BYTE_KIND:
12298 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12299 break;
12300 default:
12301 assert(0);
12302 out = 0;
12303 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012304
12305 Py_DECREF(sep_obj);
12306 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012307 if (kind1 != kind)
12308 PyMem_Free(buf1);
12309 if (kind2 != kind)
12310 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012311
12312 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012313 onError:
12314 Py_DECREF(sep_obj);
12315 Py_DECREF(str_obj);
12316 if (kind1 != kind && buf1)
12317 PyMem_Free(buf1);
12318 if (kind2 != kind && buf2)
12319 PyMem_Free(buf2);
12320 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012321}
12322
12323
12324PyObject *
12325PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12326{
12327 PyObject* str_obj;
12328 PyObject* sep_obj;
12329 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012330 int kind1, kind2, kind;
12331 void *buf1 = NULL, *buf2 = NULL;
12332 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012333
12334 str_obj = PyUnicode_FromObject(str_in);
12335 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012336 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012337 sep_obj = PyUnicode_FromObject(sep_in);
12338 if (!sep_obj) {
12339 Py_DECREF(str_obj);
12340 return NULL;
12341 }
12342
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012343 kind1 = PyUnicode_KIND(str_in);
12344 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012345 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012346 buf1 = PyUnicode_DATA(str_in);
12347 if (kind1 != kind)
12348 buf1 = _PyUnicode_AsKind(str_in, kind);
12349 if (!buf1)
12350 goto onError;
12351 buf2 = PyUnicode_DATA(sep_obj);
12352 if (kind2 != kind)
12353 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12354 if (!buf2)
12355 goto onError;
12356 len1 = PyUnicode_GET_LENGTH(str_obj);
12357 len2 = PyUnicode_GET_LENGTH(sep_obj);
12358
12359 switch(PyUnicode_KIND(str_in)) {
12360 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012361 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12362 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12363 else
12364 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012365 break;
12366 case PyUnicode_2BYTE_KIND:
12367 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12368 break;
12369 case PyUnicode_4BYTE_KIND:
12370 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12371 break;
12372 default:
12373 assert(0);
12374 out = 0;
12375 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376
12377 Py_DECREF(sep_obj);
12378 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012379 if (kind1 != kind)
12380 PyMem_Free(buf1);
12381 if (kind2 != kind)
12382 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012383
12384 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012385 onError:
12386 Py_DECREF(sep_obj);
12387 Py_DECREF(str_obj);
12388 if (kind1 != kind && buf1)
12389 PyMem_Free(buf1);
12390 if (kind2 != kind && buf2)
12391 PyMem_Free(buf2);
12392 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012393}
12394
12395PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012396 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012397\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012398Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012399the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012400found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012401
12402static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012403unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012404{
Victor Stinner9310abb2011-10-05 00:59:23 +020012405 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012406}
12407
12408PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012409 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012410\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012411Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012412the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012413separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012414
12415static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012416unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012417{
Victor Stinner9310abb2011-10-05 00:59:23 +020012418 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012419}
12420
Alexander Belopolsky40018472011-02-26 01:02:56 +000012421PyObject *
12422PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012423{
12424 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012425
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012426 s = PyUnicode_FromObject(s);
12427 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012428 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012429 if (sep != NULL) {
12430 sep = PyUnicode_FromObject(sep);
12431 if (sep == NULL) {
12432 Py_DECREF(s);
12433 return NULL;
12434 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012435 }
12436
Victor Stinner9310abb2011-10-05 00:59:23 +020012437 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012438
12439 Py_DECREF(s);
12440 Py_XDECREF(sep);
12441 return result;
12442}
12443
12444PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012445 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012446\n\
12447Return a list of the words in S, using sep as the\n\
12448delimiter string, starting at the end of the string and\n\
12449working to the front. If maxsplit is given, at most maxsplit\n\
12450splits are done. If sep is not specified, any whitespace string\n\
12451is a separator.");
12452
12453static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012454unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012455{
12456 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012457 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012458
Martin v. Löwis18e16552006-02-15 17:27:45 +000012459 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012460 return NULL;
12461
12462 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012464 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012465 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012466 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012467 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012468}
12469
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012470PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012471 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012472\n\
12473Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012474Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012475is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012476
12477static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012478unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012479{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012480 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012481 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012482
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012483 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12484 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485 return NULL;
12486
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012487 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012488}
12489
12490static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012491PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012492{
Walter Dörwald346737f2007-05-31 10:44:43 +000012493 if (PyUnicode_CheckExact(self)) {
12494 Py_INCREF(self);
12495 return self;
12496 } else
12497 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012498 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012499}
12500
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012501PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012502 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012503\n\
12504Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012505and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012506
12507static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012508unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012509{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012510 return fixup(self, fixswapcase);
12511}
12512
Georg Brandlceee0772007-11-27 23:48:05 +000012513PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012514 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012515\n\
12516Return a translation table usable for str.translate().\n\
12517If there is only one argument, it must be a dictionary mapping Unicode\n\
12518ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012519Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012520If there are two arguments, they must be strings of equal length, and\n\
12521in the resulting dictionary, each character in x will be mapped to the\n\
12522character at the same position in y. If there is a third argument, it\n\
12523must be a string, whose characters will be mapped to None in the result.");
12524
12525static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012526unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012527{
12528 PyObject *x, *y = NULL, *z = NULL;
12529 PyObject *new = NULL, *key, *value;
12530 Py_ssize_t i = 0;
12531 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012532
Georg Brandlceee0772007-11-27 23:48:05 +000012533 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12534 return NULL;
12535 new = PyDict_New();
12536 if (!new)
12537 return NULL;
12538 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012539 int x_kind, y_kind, z_kind;
12540 void *x_data, *y_data, *z_data;
12541
Georg Brandlceee0772007-11-27 23:48:05 +000012542 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012543 if (!PyUnicode_Check(x)) {
12544 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12545 "be a string if there is a second argument");
12546 goto err;
12547 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012548 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012549 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12550 "arguments must have equal length");
12551 goto err;
12552 }
12553 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012554 x_kind = PyUnicode_KIND(x);
12555 y_kind = PyUnicode_KIND(y);
12556 x_data = PyUnicode_DATA(x);
12557 y_data = PyUnicode_DATA(y);
12558 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12559 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12560 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012561 if (!key || !value)
12562 goto err;
12563 res = PyDict_SetItem(new, key, value);
12564 Py_DECREF(key);
12565 Py_DECREF(value);
12566 if (res < 0)
12567 goto err;
12568 }
12569 /* create entries for deleting chars in z */
12570 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012571 z_kind = PyUnicode_KIND(z);
12572 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012573 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012574 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012575 if (!key)
12576 goto err;
12577 res = PyDict_SetItem(new, key, Py_None);
12578 Py_DECREF(key);
12579 if (res < 0)
12580 goto err;
12581 }
12582 }
12583 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012584 int kind;
12585 void *data;
12586
Georg Brandlceee0772007-11-27 23:48:05 +000012587 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012588 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012589 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12590 "to maketrans it must be a dict");
12591 goto err;
12592 }
12593 /* copy entries into the new dict, converting string keys to int keys */
12594 while (PyDict_Next(x, &i, &key, &value)) {
12595 if (PyUnicode_Check(key)) {
12596 /* convert string keys to integer keys */
12597 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012598 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012599 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12600 "table must be of length 1");
12601 goto err;
12602 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012603 kind = PyUnicode_KIND(key);
12604 data = PyUnicode_DATA(key);
12605 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012606 if (!newkey)
12607 goto err;
12608 res = PyDict_SetItem(new, newkey, value);
12609 Py_DECREF(newkey);
12610 if (res < 0)
12611 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012612 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012613 /* just keep integer keys */
12614 if (PyDict_SetItem(new, key, value) < 0)
12615 goto err;
12616 } else {
12617 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12618 "be strings or integers");
12619 goto err;
12620 }
12621 }
12622 }
12623 return new;
12624 err:
12625 Py_DECREF(new);
12626 return NULL;
12627}
12628
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012629PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012630 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012631\n\
12632Return a copy of the string S, where all characters have been mapped\n\
12633through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012634Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012635Unmapped characters are left untouched. Characters mapped to None\n\
12636are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012637
12638static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012639unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012640{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012641 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012642}
12643
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012644PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012645 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012646\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012647Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012648
12649static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012650unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012651{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012652 return fixup(self, fixupper);
12653}
12654
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012655PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012656 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012657\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012658Pad a numeric string S with zeros on the left, to fill a field\n\
12659of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012660
12661static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012662unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012663{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012664 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012665 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012666 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012667 int kind;
12668 void *data;
12669 Py_UCS4 chr;
12670
12671 if (PyUnicode_READY(self) == -1)
12672 return NULL;
12673
Martin v. Löwis18e16552006-02-15 17:27:45 +000012674 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675 return NULL;
12676
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012677 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012678 if (PyUnicode_CheckExact(self)) {
12679 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012680 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012681 }
12682 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012683 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012684 }
12685
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012687
12688 u = pad(self, fill, 0, '0');
12689
Walter Dörwald068325e2002-04-15 13:36:47 +000012690 if (u == NULL)
12691 return NULL;
12692
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012693 kind = PyUnicode_KIND(u);
12694 data = PyUnicode_DATA(u);
12695 chr = PyUnicode_READ(kind, data, fill);
12696
12697 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012698 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012699 PyUnicode_WRITE(kind, data, 0, chr);
12700 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701 }
12702
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012703 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012704 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012705}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012706
12707#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012708static PyObject *
12709unicode__decimal2ascii(PyObject *self)
12710{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012711 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012712}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012713#endif
12714
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012715PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012716 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012717\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012718Return True if S starts with the specified prefix, False otherwise.\n\
12719With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012720With optional end, stop comparing S at that position.\n\
12721prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012722
12723static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012724unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012725 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012726{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012727 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012728 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012729 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012730 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012731 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012732
Jesus Ceaac451502011-04-20 17:09:23 +020012733 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012734 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012735 if (PyTuple_Check(subobj)) {
12736 Py_ssize_t i;
12737 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012738 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012739 if (substring == NULL)
12740 return NULL;
12741 result = tailmatch(self, substring, start, end, -1);
12742 Py_DECREF(substring);
12743 if (result) {
12744 Py_RETURN_TRUE;
12745 }
12746 }
12747 /* nothing matched */
12748 Py_RETURN_FALSE;
12749 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012750 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012751 if (substring == NULL) {
12752 if (PyErr_ExceptionMatches(PyExc_TypeError))
12753 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12754 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012755 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012756 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012757 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012758 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012759 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012760}
12761
12762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012763PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012765\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012766Return True if S ends with the specified suffix, False otherwise.\n\
12767With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012768With optional end, stop comparing S at that position.\n\
12769suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012770
12771static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012772unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012773 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012774{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012775 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012776 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012777 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012778 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012779 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012780
Jesus Ceaac451502011-04-20 17:09:23 +020012781 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012782 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012783 if (PyTuple_Check(subobj)) {
12784 Py_ssize_t i;
12785 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012786 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012787 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012788 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012789 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012790 result = tailmatch(self, substring, start, end, +1);
12791 Py_DECREF(substring);
12792 if (result) {
12793 Py_RETURN_TRUE;
12794 }
12795 }
12796 Py_RETURN_FALSE;
12797 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012798 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012799 if (substring == NULL) {
12800 if (PyErr_ExceptionMatches(PyExc_TypeError))
12801 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12802 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012803 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012804 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012805 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012806 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012807 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012808}
12809
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012811
12812PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012813 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012814\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012815Return a formatted version of S, using substitutions from args and kwargs.\n\
12816The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012817
Eric Smith27bbca62010-11-04 17:06:58 +000012818PyDoc_STRVAR(format_map__doc__,
12819 "S.format_map(mapping) -> str\n\
12820\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012821Return a formatted version of S, using substitutions from mapping.\n\
12822The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012823
Eric Smith4a7d76d2008-05-30 18:10:19 +000012824static PyObject *
12825unicode__format__(PyObject* self, PyObject* args)
12826{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012827 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012828
12829 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12830 return NULL;
12831
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012832 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012833 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012834 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012835}
12836
Eric Smith8c663262007-08-25 02:26:07 +000012837PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012838 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012839\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012840Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012841
12842static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012843unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012844{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012845 Py_ssize_t size;
12846
12847 /* If it's a compact object, account for base structure +
12848 character data. */
12849 if (PyUnicode_IS_COMPACT_ASCII(v))
12850 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12851 else if (PyUnicode_IS_COMPACT(v))
12852 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012853 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 else {
12855 /* If it is a two-block object, account for base object, and
12856 for character block if present. */
12857 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012858 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012859 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012860 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012861 }
12862 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012863 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012864 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012865 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012866 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012867 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012868
12869 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012870}
12871
12872PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012873 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012874
12875static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012876unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012877{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012878 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012879 if (!copy)
12880 return NULL;
12881 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012882}
12883
Guido van Rossumd57fd912000-03-10 22:53:23 +000012884static PyMethodDef unicode_methods[] = {
12885
12886 /* Order is according to common usage: often used methods should
12887 appear first, since lookup is done sequentially. */
12888
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012889 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012890 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12891 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012892 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012893 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12894 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12895 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12896 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12897 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12898 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12899 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012900 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012901 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12902 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12903 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012904 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012905 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12906 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12907 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012908 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012909 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012910 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012911 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012912 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12913 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12914 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12915 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12916 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12917 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12918 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12919 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12920 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12921 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12922 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12923 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12924 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12925 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012926 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012927 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012928 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012929 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012930 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012931 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012932 {"maketrans", (PyCFunction) unicode_maketrans,
12933 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012934 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012935#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012936 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012937#endif
12938
12939#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012940 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012941 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012942#endif
12943
Benjamin Peterson14339b62009-01-31 16:36:08 +000012944 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012945 {NULL, NULL}
12946};
12947
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012948static PyObject *
12949unicode_mod(PyObject *v, PyObject *w)
12950{
Brian Curtindfc80e32011-08-10 20:28:54 -050012951 if (!PyUnicode_Check(v))
12952 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012953 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012954}
12955
12956static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012957 0, /*nb_add*/
12958 0, /*nb_subtract*/
12959 0, /*nb_multiply*/
12960 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012961};
12962
Guido van Rossumd57fd912000-03-10 22:53:23 +000012963static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012964 (lenfunc) unicode_length, /* sq_length */
12965 PyUnicode_Concat, /* sq_concat */
12966 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12967 (ssizeargfunc) unicode_getitem, /* sq_item */
12968 0, /* sq_slice */
12969 0, /* sq_ass_item */
12970 0, /* sq_ass_slice */
12971 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012972};
12973
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012974static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012975unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012976{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012977 if (PyUnicode_READY(self) == -1)
12978 return NULL;
12979
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012980 if (PyIndex_Check(item)) {
12981 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012982 if (i == -1 && PyErr_Occurred())
12983 return NULL;
12984 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012985 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012986 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012987 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012988 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012989 PyObject *result;
12990 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012991 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012992 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012993
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012994 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012995 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012996 return NULL;
12997 }
12998
12999 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013000 return PyUnicode_New(0, 0);
13001 } else if (start == 0 && step == 1 &&
13002 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000013003 PyUnicode_CheckExact(self)) {
13004 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013005 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000013006 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013007 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013008 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013009 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013010 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013011 src_kind = PyUnicode_KIND(self);
13012 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020013013 if (!PyUnicode_IS_ASCII(self)) {
13014 kind_limit = kind_maxchar_limit(src_kind);
13015 max_char = 0;
13016 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
13017 ch = PyUnicode_READ(src_kind, src_data, cur);
13018 if (ch > max_char) {
13019 max_char = ch;
13020 if (max_char >= kind_limit)
13021 break;
13022 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020013023 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013024 }
Victor Stinner55c99112011-10-13 01:17:06 +020013025 else
13026 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013027 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013028 if (result == NULL)
13029 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013030 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013031 dest_data = PyUnicode_DATA(result);
13032
13033 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013034 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13035 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013036 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013037 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013038 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013039 } else {
13040 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13041 return NULL;
13042 }
13043}
13044
13045static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013046 (lenfunc)unicode_length, /* mp_length */
13047 (binaryfunc)unicode_subscript, /* mp_subscript */
13048 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013049};
13050
Guido van Rossumd57fd912000-03-10 22:53:23 +000013051
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052/* Helpers for PyUnicode_Format() */
13053
13054static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013055getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013056{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013057 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013059 (*p_argidx)++;
13060 if (arglen < 0)
13061 return args;
13062 else
13063 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013064 }
13065 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013066 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013067 return NULL;
13068}
13069
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013070/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013071
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013072static PyObject *
13073formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013074{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013075 char *p;
13076 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013077 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013078
Guido van Rossumd57fd912000-03-10 22:53:23 +000013079 x = PyFloat_AsDouble(v);
13080 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013081 return NULL;
13082
Guido van Rossumd57fd912000-03-10 22:53:23 +000013083 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013084 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013085
Eric Smith0923d1d2009-04-16 20:16:10 +000013086 p = PyOS_double_to_string(x, type, prec,
13087 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013088 if (p == NULL)
13089 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013090 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013091 PyMem_Free(p);
13092 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013093}
13094
Tim Peters38fd5b62000-09-21 05:43:11 +000013095static PyObject*
13096formatlong(PyObject *val, int flags, int prec, int type)
13097{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013098 char *buf;
13099 int len;
13100 PyObject *str; /* temporary string object. */
13101 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013102
Benjamin Peterson14339b62009-01-31 16:36:08 +000013103 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13104 if (!str)
13105 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013106 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013107 Py_DECREF(str);
13108 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013109}
13110
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013111static Py_UCS4
13112formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013113{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013114 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013115 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013116 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013117 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013118 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013119 goto onError;
13120 }
13121 else {
13122 /* Integer input truncated to a character */
13123 long x;
13124 x = PyLong_AsLong(v);
13125 if (x == -1 && PyErr_Occurred())
13126 goto onError;
13127
13128 if (x < 0 || x > 0x10ffff) {
13129 PyErr_SetString(PyExc_OverflowError,
13130 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013131 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013132 }
13133
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013134 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013135 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013136
Benjamin Peterson29060642009-01-31 22:14:21 +000013137 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013138 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013139 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013140 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013141}
13142
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013143static int
13144repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13145{
13146 int r;
13147 assert(count > 0);
13148 assert(PyUnicode_Check(obj));
13149 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013150 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013151 if (repeated == NULL)
13152 return -1;
13153 r = _PyAccu_Accumulate(acc, repeated);
13154 Py_DECREF(repeated);
13155 return r;
13156 }
13157 else {
13158 do {
13159 if (_PyAccu_Accumulate(acc, obj))
13160 return -1;
13161 } while (--count);
13162 return 0;
13163 }
13164}
13165
Alexander Belopolsky40018472011-02-26 01:02:56 +000013166PyObject *
13167PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013169 void *fmt;
13170 int fmtkind;
13171 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013172 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013173 int r;
13174 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013175 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013176 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013177 PyObject *temp = NULL;
13178 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013179 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013180 _PyAccu acc;
13181 static PyObject *plus, *minus, *blank, *zero, *percent;
13182
13183 if (!plus && !(plus = get_latin1_char('+')))
13184 return NULL;
13185 if (!minus && !(minus = get_latin1_char('-')))
13186 return NULL;
13187 if (!blank && !(blank = get_latin1_char(' ')))
13188 return NULL;
13189 if (!zero && !(zero = get_latin1_char('0')))
13190 return NULL;
13191 if (!percent && !(percent = get_latin1_char('%')))
13192 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013193
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013195 PyErr_BadInternalCall();
13196 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013197 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013198 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013199 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013200 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013201 if (_PyAccu_Init(&acc))
13202 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013203 fmt = PyUnicode_DATA(uformat);
13204 fmtkind = PyUnicode_KIND(uformat);
13205 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13206 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013207
Guido van Rossumd57fd912000-03-10 22:53:23 +000013208 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013209 arglen = PyTuple_Size(args);
13210 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013211 }
13212 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 arglen = -1;
13214 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013215 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013216 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013217 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013218 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013219
13220 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013221 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013222 PyObject *nonfmt;
13223 Py_ssize_t nonfmtpos;
13224 nonfmtpos = fmtpos++;
13225 while (fmtcnt >= 0 &&
13226 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13227 fmtpos++;
13228 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013229 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013230 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013231 if (nonfmt == NULL)
13232 goto onError;
13233 r = _PyAccu_Accumulate(&acc, nonfmt);
13234 Py_DECREF(nonfmt);
13235 if (r)
13236 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013237 }
13238 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 /* Got a format specifier */
13240 int flags = 0;
13241 Py_ssize_t width = -1;
13242 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013244 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013245 int isnumok;
13246 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013247 void *pbuf = NULL;
13248 Py_ssize_t pindex, len;
13249 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013250
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013251 fmtpos++;
13252 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13253 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013254 Py_ssize_t keylen;
13255 PyObject *key;
13256 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013257
Benjamin Peterson29060642009-01-31 22:14:21 +000013258 if (dict == NULL) {
13259 PyErr_SetString(PyExc_TypeError,
13260 "format requires a mapping");
13261 goto onError;
13262 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013263 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013264 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013265 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013266 /* Skip over balanced parentheses */
13267 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013268 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013269 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013270 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013271 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013272 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013273 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013274 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013275 if (fmtcnt < 0 || pcount > 0) {
13276 PyErr_SetString(PyExc_ValueError,
13277 "incomplete format key");
13278 goto onError;
13279 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013280 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013281 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 if (key == NULL)
13283 goto onError;
13284 if (args_owned) {
13285 Py_DECREF(args);
13286 args_owned = 0;
13287 }
13288 args = PyObject_GetItem(dict, key);
13289 Py_DECREF(key);
13290 if (args == NULL) {
13291 goto onError;
13292 }
13293 args_owned = 1;
13294 arglen = -1;
13295 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013296 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013297 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013298 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013299 case '-': flags |= F_LJUST; continue;
13300 case '+': flags |= F_SIGN; continue;
13301 case ' ': flags |= F_BLANK; continue;
13302 case '#': flags |= F_ALT; continue;
13303 case '0': flags |= F_ZERO; continue;
13304 }
13305 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013306 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013307 if (c == '*') {
13308 v = getnextarg(args, arglen, &argidx);
13309 if (v == NULL)
13310 goto onError;
13311 if (!PyLong_Check(v)) {
13312 PyErr_SetString(PyExc_TypeError,
13313 "* wants int");
13314 goto onError;
13315 }
13316 width = PyLong_AsLong(v);
13317 if (width == -1 && PyErr_Occurred())
13318 goto onError;
13319 if (width < 0) {
13320 flags |= F_LJUST;
13321 width = -width;
13322 }
13323 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013324 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013325 }
13326 else if (c >= '0' && c <= '9') {
13327 width = c - '0';
13328 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013329 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013330 if (c < '0' || c > '9')
13331 break;
13332 if ((width*10) / 10 != width) {
13333 PyErr_SetString(PyExc_ValueError,
13334 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013335 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013336 }
13337 width = width*10 + (c - '0');
13338 }
13339 }
13340 if (c == '.') {
13341 prec = 0;
13342 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013343 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 if (c == '*') {
13345 v = getnextarg(args, arglen, &argidx);
13346 if (v == NULL)
13347 goto onError;
13348 if (!PyLong_Check(v)) {
13349 PyErr_SetString(PyExc_TypeError,
13350 "* wants int");
13351 goto onError;
13352 }
13353 prec = PyLong_AsLong(v);
13354 if (prec == -1 && PyErr_Occurred())
13355 goto onError;
13356 if (prec < 0)
13357 prec = 0;
13358 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013359 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013360 }
13361 else if (c >= '0' && c <= '9') {
13362 prec = c - '0';
13363 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013364 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013365 if (c < '0' || c > '9')
13366 break;
13367 if ((prec*10) / 10 != prec) {
13368 PyErr_SetString(PyExc_ValueError,
13369 "prec too big");
13370 goto onError;
13371 }
13372 prec = prec*10 + (c - '0');
13373 }
13374 }
13375 } /* prec */
13376 if (fmtcnt >= 0) {
13377 if (c == 'h' || c == 'l' || c == 'L') {
13378 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013379 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 }
13381 }
13382 if (fmtcnt < 0) {
13383 PyErr_SetString(PyExc_ValueError,
13384 "incomplete format");
13385 goto onError;
13386 }
13387 if (c != '%') {
13388 v = getnextarg(args, arglen, &argidx);
13389 if (v == NULL)
13390 goto onError;
13391 }
13392 sign = 0;
13393 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013394 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013395 switch (c) {
13396
13397 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013398 _PyAccu_Accumulate(&acc, percent);
13399 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013400
13401 case 's':
13402 case 'r':
13403 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013404 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013405 temp = v;
13406 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013407 }
13408 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013409 if (c == 's')
13410 temp = PyObject_Str(v);
13411 else if (c == 'r')
13412 temp = PyObject_Repr(v);
13413 else
13414 temp = PyObject_ASCII(v);
13415 if (temp == NULL)
13416 goto onError;
13417 if (PyUnicode_Check(temp))
13418 /* nothing to do */;
13419 else {
13420 Py_DECREF(temp);
13421 PyErr_SetString(PyExc_TypeError,
13422 "%s argument has non-string str()");
13423 goto onError;
13424 }
13425 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013426 if (PyUnicode_READY(temp) == -1) {
13427 Py_CLEAR(temp);
13428 goto onError;
13429 }
13430 pbuf = PyUnicode_DATA(temp);
13431 kind = PyUnicode_KIND(temp);
13432 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 if (prec >= 0 && len > prec)
13434 len = prec;
13435 break;
13436
13437 case 'i':
13438 case 'd':
13439 case 'u':
13440 case 'o':
13441 case 'x':
13442 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 isnumok = 0;
13444 if (PyNumber_Check(v)) {
13445 PyObject *iobj=NULL;
13446
13447 if (PyLong_Check(v)) {
13448 iobj = v;
13449 Py_INCREF(iobj);
13450 }
13451 else {
13452 iobj = PyNumber_Long(v);
13453 }
13454 if (iobj!=NULL) {
13455 if (PyLong_Check(iobj)) {
13456 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013457 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013458 Py_DECREF(iobj);
13459 if (!temp)
13460 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013461 if (PyUnicode_READY(temp) == -1) {
13462 Py_CLEAR(temp);
13463 goto onError;
13464 }
13465 pbuf = PyUnicode_DATA(temp);
13466 kind = PyUnicode_KIND(temp);
13467 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013468 sign = 1;
13469 }
13470 else {
13471 Py_DECREF(iobj);
13472 }
13473 }
13474 }
13475 if (!isnumok) {
13476 PyErr_Format(PyExc_TypeError,
13477 "%%%c format: a number is required, "
13478 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13479 goto onError;
13480 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013481 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013482 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013483 fillobj = zero;
13484 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013485 break;
13486
13487 case 'e':
13488 case 'E':
13489 case 'f':
13490 case 'F':
13491 case 'g':
13492 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013493 temp = formatfloat(v, flags, prec, c);
13494 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013495 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013496 if (PyUnicode_READY(temp) == -1) {
13497 Py_CLEAR(temp);
13498 goto onError;
13499 }
13500 pbuf = PyUnicode_DATA(temp);
13501 kind = PyUnicode_KIND(temp);
13502 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013503 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013504 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013505 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013506 fillobj = zero;
13507 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013508 break;
13509
13510 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013511 {
13512 Py_UCS4 ch = formatchar(v);
13513 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013514 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013515 temp = _PyUnicode_FromUCS4(&ch, 1);
13516 if (temp == NULL)
13517 goto onError;
13518 pbuf = PyUnicode_DATA(temp);
13519 kind = PyUnicode_KIND(temp);
13520 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013521 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013522 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013523
13524 default:
13525 PyErr_Format(PyExc_ValueError,
13526 "unsupported format character '%c' (0x%x) "
13527 "at index %zd",
13528 (31<=c && c<=126) ? (char)c : '?',
13529 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013530 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013531 goto onError;
13532 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013533 /* pbuf is initialized here. */
13534 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013535 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013536 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13537 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013538 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013539 pindex++;
13540 }
13541 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13542 signobj = plus;
13543 len--;
13544 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013545 }
13546 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013547 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013548 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013549 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013550 else
13551 sign = 0;
13552 }
13553 if (width < len)
13554 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013555 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013556 if (fill != ' ') {
13557 assert(signobj != NULL);
13558 if (_PyAccu_Accumulate(&acc, signobj))
13559 goto onError;
13560 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013561 if (width > len)
13562 width--;
13563 }
13564 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013565 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013566 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013567 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013568 second = get_latin1_char(
13569 PyUnicode_READ(kind, pbuf, pindex + 1));
13570 pindex += 2;
13571 if (second == NULL ||
13572 _PyAccu_Accumulate(&acc, zero) ||
13573 _PyAccu_Accumulate(&acc, second))
13574 goto onError;
13575 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013576 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013577 width -= 2;
13578 if (width < 0)
13579 width = 0;
13580 len -= 2;
13581 }
13582 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013583 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013584 if (repeat_accumulate(&acc, fillobj, width - len))
13585 goto onError;
13586 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013587 }
13588 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013589 if (sign) {
13590 assert(signobj != NULL);
13591 if (_PyAccu_Accumulate(&acc, signobj))
13592 goto onError;
13593 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013594 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013595 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13596 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013597 second = get_latin1_char(
13598 PyUnicode_READ(kind, pbuf, pindex + 1));
13599 pindex += 2;
13600 if (second == NULL ||
13601 _PyAccu_Accumulate(&acc, zero) ||
13602 _PyAccu_Accumulate(&acc, second))
13603 goto onError;
13604 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013605 }
13606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013607 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013608 if (temp != NULL) {
13609 assert(pbuf == PyUnicode_DATA(temp));
13610 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013611 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013612 else {
13613 const char *p = (const char *) pbuf;
13614 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013615 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013616 v = PyUnicode_FromKindAndData(kind, p, len);
13617 }
13618 if (v == NULL)
13619 goto onError;
13620 r = _PyAccu_Accumulate(&acc, v);
13621 Py_DECREF(v);
13622 if (r)
13623 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013624 if (width > len && repeat_accumulate(&acc, blank, width - len))
13625 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013626 if (dict && (argidx < arglen) && c != '%') {
13627 PyErr_SetString(PyExc_TypeError,
13628 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013629 goto onError;
13630 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013631 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013632 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013633 } /* until end */
13634 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013635 PyErr_SetString(PyExc_TypeError,
13636 "not all arguments converted during string formatting");
13637 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013638 }
13639
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013640 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013641 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013642 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013643 }
13644 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013645 Py_XDECREF(temp);
13646 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013647 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013648
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013650 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013651 Py_XDECREF(temp);
13652 Py_XDECREF(second);
13653 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013654 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013655 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013656 }
13657 return NULL;
13658}
13659
Jeremy Hylton938ace62002-07-17 16:30:39 +000013660static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013661unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13662
Tim Peters6d6c1a32001-08-02 04:15:00 +000013663static PyObject *
13664unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13665{
Benjamin Peterson29060642009-01-31 22:14:21 +000013666 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013667 static char *kwlist[] = {"object", "encoding", "errors", 0};
13668 char *encoding = NULL;
13669 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013670
Benjamin Peterson14339b62009-01-31 16:36:08 +000013671 if (type != &PyUnicode_Type)
13672 return unicode_subtype_new(type, args, kwds);
13673 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013674 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013675 return NULL;
13676 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013677 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013678 if (encoding == NULL && errors == NULL)
13679 return PyObject_Str(x);
13680 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013681 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013682}
13683
Guido van Rossume023fe02001-08-30 03:12:59 +000013684static PyObject *
13685unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13686{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013687 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013688 Py_ssize_t length, char_size;
13689 int share_wstr, share_utf8;
13690 unsigned int kind;
13691 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013692
Benjamin Peterson14339b62009-01-31 16:36:08 +000013693 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013694
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013695 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013696 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013697 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013698 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013699 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013700 return NULL;
13701
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013702 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013703 if (self == NULL) {
13704 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013705 return NULL;
13706 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013707 kind = PyUnicode_KIND(unicode);
13708 length = PyUnicode_GET_LENGTH(unicode);
13709
13710 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013711#ifdef Py_DEBUG
13712 _PyUnicode_HASH(self) = -1;
13713#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013714 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013715#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013716 _PyUnicode_STATE(self).interned = 0;
13717 _PyUnicode_STATE(self).kind = kind;
13718 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013719 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013720 _PyUnicode_STATE(self).ready = 1;
13721 _PyUnicode_WSTR(self) = NULL;
13722 _PyUnicode_UTF8_LENGTH(self) = 0;
13723 _PyUnicode_UTF8(self) = NULL;
13724 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013725 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013726
13727 share_utf8 = 0;
13728 share_wstr = 0;
13729 if (kind == PyUnicode_1BYTE_KIND) {
13730 char_size = 1;
13731 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13732 share_utf8 = 1;
13733 }
13734 else if (kind == PyUnicode_2BYTE_KIND) {
13735 char_size = 2;
13736 if (sizeof(wchar_t) == 2)
13737 share_wstr = 1;
13738 }
13739 else {
13740 assert(kind == PyUnicode_4BYTE_KIND);
13741 char_size = 4;
13742 if (sizeof(wchar_t) == 4)
13743 share_wstr = 1;
13744 }
13745
13746 /* Ensure we won't overflow the length. */
13747 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13748 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013749 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013750 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013751 data = PyObject_MALLOC((length + 1) * char_size);
13752 if (data == NULL) {
13753 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013754 goto onError;
13755 }
13756
Victor Stinnerc3c74152011-10-02 20:39:55 +020013757 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013758 if (share_utf8) {
13759 _PyUnicode_UTF8_LENGTH(self) = length;
13760 _PyUnicode_UTF8(self) = data;
13761 }
13762 if (share_wstr) {
13763 _PyUnicode_WSTR_LENGTH(self) = length;
13764 _PyUnicode_WSTR(self) = (wchar_t *)data;
13765 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013766
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013767 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013768 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013769 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013770#ifdef Py_DEBUG
13771 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13772#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013773 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013774 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013775
13776onError:
13777 Py_DECREF(unicode);
13778 Py_DECREF(self);
13779 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013780}
13781
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013782PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013783 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013784\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013785Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013786encoding defaults to the current default string encoding.\n\
13787errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013788
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013789static PyObject *unicode_iter(PyObject *seq);
13790
Guido van Rossumd57fd912000-03-10 22:53:23 +000013791PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013792 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013793 "str", /* tp_name */
13794 sizeof(PyUnicodeObject), /* tp_size */
13795 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013796 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013797 (destructor)unicode_dealloc, /* tp_dealloc */
13798 0, /* tp_print */
13799 0, /* tp_getattr */
13800 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013801 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013802 unicode_repr, /* tp_repr */
13803 &unicode_as_number, /* tp_as_number */
13804 &unicode_as_sequence, /* tp_as_sequence */
13805 &unicode_as_mapping, /* tp_as_mapping */
13806 (hashfunc) unicode_hash, /* tp_hash*/
13807 0, /* tp_call*/
13808 (reprfunc) unicode_str, /* tp_str */
13809 PyObject_GenericGetAttr, /* tp_getattro */
13810 0, /* tp_setattro */
13811 0, /* tp_as_buffer */
13812 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013813 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013814 unicode_doc, /* tp_doc */
13815 0, /* tp_traverse */
13816 0, /* tp_clear */
13817 PyUnicode_RichCompare, /* tp_richcompare */
13818 0, /* tp_weaklistoffset */
13819 unicode_iter, /* tp_iter */
13820 0, /* tp_iternext */
13821 unicode_methods, /* tp_methods */
13822 0, /* tp_members */
13823 0, /* tp_getset */
13824 &PyBaseObject_Type, /* tp_base */
13825 0, /* tp_dict */
13826 0, /* tp_descr_get */
13827 0, /* tp_descr_set */
13828 0, /* tp_dictoffset */
13829 0, /* tp_init */
13830 0, /* tp_alloc */
13831 unicode_new, /* tp_new */
13832 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013833};
13834
13835/* Initialize the Unicode implementation */
13836
Victor Stinner3a50e702011-10-18 21:21:00 +020013837int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013838{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013839 int i;
13840
Thomas Wouters477c8d52006-05-27 19:21:47 +000013841 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013842 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013843 0x000A, /* LINE FEED */
13844 0x000D, /* CARRIAGE RETURN */
13845 0x001C, /* FILE SEPARATOR */
13846 0x001D, /* GROUP SEPARATOR */
13847 0x001E, /* RECORD SEPARATOR */
13848 0x0085, /* NEXT LINE */
13849 0x2028, /* LINE SEPARATOR */
13850 0x2029, /* PARAGRAPH SEPARATOR */
13851 };
13852
Fred Drakee4315f52000-05-09 19:53:39 +000013853 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013854 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013855 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013856 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013857 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013858
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013859 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013860 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013861 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013862 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013863
13864 /* initialize the linebreak bloom filter */
13865 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013866 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013867 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013868
13869 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013870
13871#ifdef HAVE_MBCS
13872 winver.dwOSVersionInfoSize = sizeof(winver);
13873 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13874 PyErr_SetFromWindowsErr(0);
13875 return -1;
13876 }
13877#endif
13878 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013879}
13880
13881/* Finalize the Unicode implementation */
13882
Christian Heimesa156e092008-02-16 07:38:31 +000013883int
13884PyUnicode_ClearFreeList(void)
13885{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013886 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013887}
13888
Guido van Rossumd57fd912000-03-10 22:53:23 +000013889void
Thomas Wouters78890102000-07-22 19:25:51 +000013890_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013891{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013892 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013893
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013894 Py_XDECREF(unicode_empty);
13895 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013896
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013897 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013898 if (unicode_latin1[i]) {
13899 Py_DECREF(unicode_latin1[i]);
13900 unicode_latin1[i] = NULL;
13901 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013902 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013903 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013904 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013905}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013906
Walter Dörwald16807132007-05-25 13:52:07 +000013907void
13908PyUnicode_InternInPlace(PyObject **p)
13909{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013910 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013911 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013912#ifdef Py_DEBUG
13913 assert(s != NULL);
13914 assert(_PyUnicode_CHECK(s));
13915#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013916 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013917 return;
13918#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013919 /* If it's a subclass, we don't really know what putting
13920 it in the interned dict might do. */
13921 if (!PyUnicode_CheckExact(s))
13922 return;
13923 if (PyUnicode_CHECK_INTERNED(s))
13924 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013925 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013926 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013927 return;
13928 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013929 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013930 if (interned == NULL) {
13931 interned = PyDict_New();
13932 if (interned == NULL) {
13933 PyErr_Clear(); /* Don't leave an exception */
13934 return;
13935 }
13936 }
13937 /* It might be that the GetItem call fails even
13938 though the key is present in the dictionary,
13939 namely when this happens during a stack overflow. */
13940 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013941 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013943
Benjamin Peterson29060642009-01-31 22:14:21 +000013944 if (t) {
13945 Py_INCREF(t);
13946 Py_DECREF(*p);
13947 *p = t;
13948 return;
13949 }
Walter Dörwald16807132007-05-25 13:52:07 +000013950
Benjamin Peterson14339b62009-01-31 16:36:08 +000013951 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013952 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013953 PyErr_Clear();
13954 PyThreadState_GET()->recursion_critical = 0;
13955 return;
13956 }
13957 PyThreadState_GET()->recursion_critical = 0;
13958 /* The two references in interned are not counted by refcnt.
13959 The deallocator will take care of this */
13960 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013961 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013962}
13963
13964void
13965PyUnicode_InternImmortal(PyObject **p)
13966{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 PyUnicode_InternInPlace(p);
13968 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013969 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 Py_INCREF(*p);
13971 }
Walter Dörwald16807132007-05-25 13:52:07 +000013972}
13973
13974PyObject *
13975PyUnicode_InternFromString(const char *cp)
13976{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013977 PyObject *s = PyUnicode_FromString(cp);
13978 if (s == NULL)
13979 return NULL;
13980 PyUnicode_InternInPlace(&s);
13981 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013982}
13983
Alexander Belopolsky40018472011-02-26 01:02:56 +000013984void
13985_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013986{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013987 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013988 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013989 Py_ssize_t i, n;
13990 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013991
Benjamin Peterson14339b62009-01-31 16:36:08 +000013992 if (interned == NULL || !PyDict_Check(interned))
13993 return;
13994 keys = PyDict_Keys(interned);
13995 if (keys == NULL || !PyList_Check(keys)) {
13996 PyErr_Clear();
13997 return;
13998 }
Walter Dörwald16807132007-05-25 13:52:07 +000013999
Benjamin Peterson14339b62009-01-31 16:36:08 +000014000 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
14001 detector, interned unicode strings are not forcibly deallocated;
14002 rather, we give them their stolen references back, and then clear
14003 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000014004
Benjamin Peterson14339b62009-01-31 16:36:08 +000014005 n = PyList_GET_SIZE(keys);
14006 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000014007 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014008 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014009 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014010 if (PyUnicode_READY(s) == -1) {
14011 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014012 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020014013 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014014 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014015 case SSTATE_NOT_INTERNED:
14016 /* XXX Shouldn't happen */
14017 break;
14018 case SSTATE_INTERNED_IMMORTAL:
14019 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014020 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014021 break;
14022 case SSTATE_INTERNED_MORTAL:
14023 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014024 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014025 break;
14026 default:
14027 Py_FatalError("Inconsistent interned string state.");
14028 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014029 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014030 }
14031 fprintf(stderr, "total size of all interned strings: "
14032 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14033 "mortal/immortal\n", mortal_size, immortal_size);
14034 Py_DECREF(keys);
14035 PyDict_Clear(interned);
14036 Py_DECREF(interned);
14037 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014038}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014039
14040
14041/********************* Unicode Iterator **************************/
14042
14043typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 PyObject_HEAD
14045 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014046 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014047} unicodeiterobject;
14048
14049static void
14050unicodeiter_dealloc(unicodeiterobject *it)
14051{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014052 _PyObject_GC_UNTRACK(it);
14053 Py_XDECREF(it->it_seq);
14054 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014055}
14056
14057static int
14058unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14059{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014060 Py_VISIT(it->it_seq);
14061 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014062}
14063
14064static PyObject *
14065unicodeiter_next(unicodeiterobject *it)
14066{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014067 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014068
Benjamin Peterson14339b62009-01-31 16:36:08 +000014069 assert(it != NULL);
14070 seq = it->it_seq;
14071 if (seq == NULL)
14072 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014073 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014074
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014075 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14076 int kind = PyUnicode_KIND(seq);
14077 void *data = PyUnicode_DATA(seq);
14078 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14079 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014080 if (item != NULL)
14081 ++it->it_index;
14082 return item;
14083 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014084
Benjamin Peterson14339b62009-01-31 16:36:08 +000014085 Py_DECREF(seq);
14086 it->it_seq = NULL;
14087 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014088}
14089
14090static PyObject *
14091unicodeiter_len(unicodeiterobject *it)
14092{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 Py_ssize_t len = 0;
14094 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014095 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014096 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014097}
14098
14099PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14100
14101static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014102 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014103 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014104 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014105};
14106
14107PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014108 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14109 "str_iterator", /* tp_name */
14110 sizeof(unicodeiterobject), /* tp_basicsize */
14111 0, /* tp_itemsize */
14112 /* methods */
14113 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14114 0, /* tp_print */
14115 0, /* tp_getattr */
14116 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014117 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014118 0, /* tp_repr */
14119 0, /* tp_as_number */
14120 0, /* tp_as_sequence */
14121 0, /* tp_as_mapping */
14122 0, /* tp_hash */
14123 0, /* tp_call */
14124 0, /* tp_str */
14125 PyObject_GenericGetAttr, /* tp_getattro */
14126 0, /* tp_setattro */
14127 0, /* tp_as_buffer */
14128 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14129 0, /* tp_doc */
14130 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14131 0, /* tp_clear */
14132 0, /* tp_richcompare */
14133 0, /* tp_weaklistoffset */
14134 PyObject_SelfIter, /* tp_iter */
14135 (iternextfunc)unicodeiter_next, /* tp_iternext */
14136 unicodeiter_methods, /* tp_methods */
14137 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014138};
14139
14140static PyObject *
14141unicode_iter(PyObject *seq)
14142{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014143 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014144
Benjamin Peterson14339b62009-01-31 16:36:08 +000014145 if (!PyUnicode_Check(seq)) {
14146 PyErr_BadInternalCall();
14147 return NULL;
14148 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014149 if (PyUnicode_READY(seq) == -1)
14150 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014151 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14152 if (it == NULL)
14153 return NULL;
14154 it->it_index = 0;
14155 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014156 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014157 _PyObject_GC_TRACK(it);
14158 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014159}
14160
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014161
14162size_t
14163Py_UNICODE_strlen(const Py_UNICODE *u)
14164{
14165 int res = 0;
14166 while(*u++)
14167 res++;
14168 return res;
14169}
14170
14171Py_UNICODE*
14172Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14173{
14174 Py_UNICODE *u = s1;
14175 while ((*u++ = *s2++));
14176 return s1;
14177}
14178
14179Py_UNICODE*
14180Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14181{
14182 Py_UNICODE *u = s1;
14183 while ((*u++ = *s2++))
14184 if (n-- == 0)
14185 break;
14186 return s1;
14187}
14188
14189Py_UNICODE*
14190Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14191{
14192 Py_UNICODE *u1 = s1;
14193 u1 += Py_UNICODE_strlen(u1);
14194 Py_UNICODE_strcpy(u1, s2);
14195 return s1;
14196}
14197
14198int
14199Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14200{
14201 while (*s1 && *s2 && *s1 == *s2)
14202 s1++, s2++;
14203 if (*s1 && *s2)
14204 return (*s1 < *s2) ? -1 : +1;
14205 if (*s1)
14206 return 1;
14207 if (*s2)
14208 return -1;
14209 return 0;
14210}
14211
14212int
14213Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14214{
14215 register Py_UNICODE u1, u2;
14216 for (; n != 0; n--) {
14217 u1 = *s1;
14218 u2 = *s2;
14219 if (u1 != u2)
14220 return (u1 < u2) ? -1 : +1;
14221 if (u1 == '\0')
14222 return 0;
14223 s1++;
14224 s2++;
14225 }
14226 return 0;
14227}
14228
14229Py_UNICODE*
14230Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14231{
14232 const Py_UNICODE *p;
14233 for (p = s; *p; p++)
14234 if (*p == c)
14235 return (Py_UNICODE*)p;
14236 return NULL;
14237}
14238
14239Py_UNICODE*
14240Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14241{
14242 const Py_UNICODE *p;
14243 p = s + Py_UNICODE_strlen(s);
14244 while (p != s) {
14245 p--;
14246 if (*p == c)
14247 return (Py_UNICODE*)p;
14248 }
14249 return NULL;
14250}
Victor Stinner331ea922010-08-10 16:37:20 +000014251
Victor Stinner71133ff2010-09-01 23:43:53 +000014252Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014253PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014254{
Victor Stinner577db2c2011-10-11 22:12:48 +020014255 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014256 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014257
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014258 if (!PyUnicode_Check(unicode)) {
14259 PyErr_BadArgument();
14260 return NULL;
14261 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014262 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014263 if (u == NULL)
14264 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014265 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014266 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014267 PyErr_NoMemory();
14268 return NULL;
14269 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014270 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014271 size *= sizeof(Py_UNICODE);
14272 copy = PyMem_Malloc(size);
14273 if (copy == NULL) {
14274 PyErr_NoMemory();
14275 return NULL;
14276 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014277 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014278 return copy;
14279}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014280
Georg Brandl66c221e2010-10-14 07:04:07 +000014281/* A _string module, to export formatter_parser and formatter_field_name_split
14282 to the string.Formatter class implemented in Python. */
14283
14284static PyMethodDef _string_methods[] = {
14285 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14286 METH_O, PyDoc_STR("split the argument as a field name")},
14287 {"formatter_parser", (PyCFunction) formatter_parser,
14288 METH_O, PyDoc_STR("parse the argument as a format string")},
14289 {NULL, NULL}
14290};
14291
14292static struct PyModuleDef _string_module = {
14293 PyModuleDef_HEAD_INIT,
14294 "_string",
14295 PyDoc_STR("string helper module"),
14296 0,
14297 _string_methods,
14298 NULL,
14299 NULL,
14300 NULL,
14301 NULL
14302};
14303
14304PyMODINIT_FUNC
14305PyInit__string(void)
14306{
14307 return PyModule_Create(&_string_module);
14308}
14309
14310
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014311#ifdef __cplusplus
14312}
14313#endif