blob: 8f82502ff775170d56701e57e1d6fbf0e6bbe4e9 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100405 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Victor Stinner3a50e702011-10-18 21:21:00 +0200411#ifdef HAVE_MBCS
412static OSVERSIONINFOEX winver;
413#endif
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415/* --- Bloom Filters ----------------------------------------------------- */
416
417/* stuff to implement simple "bloom filters" for Unicode characters.
418 to keep things simple, we use a single bitmask, using the least 5
419 bits from each unicode characters as the bit index. */
420
421/* the linebreak mask is set up by Unicode_Init below */
422
Antoine Pitrouf068f942010-01-13 14:19:12 +0000423#if LONG_BIT >= 128
424#define BLOOM_WIDTH 128
425#elif LONG_BIT >= 64
426#define BLOOM_WIDTH 64
427#elif LONG_BIT >= 32
428#define BLOOM_WIDTH 32
429#else
430#error "LONG_BIT is smaller than 32"
431#endif
432
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433#define BLOOM_MASK unsigned long
434
435static BLOOM_MASK bloom_linebreak;
436
Antoine Pitrouf068f942010-01-13 14:19:12 +0000437#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
438#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Benjamin Peterson29060642009-01-31 22:14:21 +0000440#define BLOOM_LINEBREAK(ch) \
441 ((ch) < 128U ? ascii_linebreak[(ch)] : \
442 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Alexander Belopolsky40018472011-02-26 01:02:56 +0000444Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446{
447 /* calculate simple bloom-style bitmask for a given unicode string */
448
Antoine Pitrouf068f942010-01-13 14:19:12 +0000449 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 Py_ssize_t i;
451
452 mask = 0;
453 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455
456 return mask;
457}
458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200459#define BLOOM_MEMBER(mask, chr, str) \
460 (BLOOM(mask, chr) \
461 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200463/* Compilation of templated routines */
464
465#include "stringlib/asciilib.h"
466#include "stringlib/fastsearch.h"
467#include "stringlib/partition.h"
468#include "stringlib/split.h"
469#include "stringlib/count.h"
470#include "stringlib/find.h"
471#include "stringlib/find_max_char.h"
472#include "stringlib/localeutil.h"
473#include "stringlib/undef.h"
474
475#include "stringlib/ucs1lib.h"
476#include "stringlib/fastsearch.h"
477#include "stringlib/partition.h"
478#include "stringlib/split.h"
479#include "stringlib/count.h"
480#include "stringlib/find.h"
481#include "stringlib/find_max_char.h"
482#include "stringlib/localeutil.h"
483#include "stringlib/undef.h"
484
485#include "stringlib/ucs2lib.h"
486#include "stringlib/fastsearch.h"
487#include "stringlib/partition.h"
488#include "stringlib/split.h"
489#include "stringlib/count.h"
490#include "stringlib/find.h"
491#include "stringlib/find_max_char.h"
492#include "stringlib/localeutil.h"
493#include "stringlib/undef.h"
494
495#include "stringlib/ucs4lib.h"
496#include "stringlib/fastsearch.h"
497#include "stringlib/partition.h"
498#include "stringlib/split.h"
499#include "stringlib/count.h"
500#include "stringlib/find.h"
501#include "stringlib/find_max_char.h"
502#include "stringlib/localeutil.h"
503#include "stringlib/undef.h"
504
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200505#include "stringlib/unicodedefs.h"
506#include "stringlib/fastsearch.h"
507#include "stringlib/count.h"
508#include "stringlib/find.h"
509
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510/* --- Unicode Object ----------------------------------------------------- */
511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200513fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200515Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
516 Py_ssize_t size, Py_UCS4 ch,
517 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
520
521 switch (kind) {
522 case PyUnicode_1BYTE_KIND:
523 {
524 Py_UCS1 ch1 = (Py_UCS1) ch;
525 if (ch1 == ch)
526 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
527 else
528 return -1;
529 }
530 case PyUnicode_2BYTE_KIND:
531 {
532 Py_UCS2 ch2 = (Py_UCS2) ch;
533 if (ch2 == ch)
534 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
535 else
536 return -1;
537 }
538 case PyUnicode_4BYTE_KIND:
539 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
540 default:
541 assert(0);
542 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544}
545
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546static PyObject*
547resize_compact(PyObject *unicode, Py_ssize_t length)
548{
549 Py_ssize_t char_size;
550 Py_ssize_t struct_size;
551 Py_ssize_t new_size;
552 int share_wstr;
553
554 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200556 if (PyUnicode_IS_COMPACT_ASCII(unicode))
557 struct_size = sizeof(PyASCIIObject);
558 else
559 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200560 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200561
562 _Py_DEC_REFTOTAL;
563 _Py_ForgetReference(unicode);
564
565 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
566 PyErr_NoMemory();
567 return NULL;
568 }
569 new_size = (struct_size + (length + 1) * char_size);
570
571 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
572 if (unicode == NULL) {
573 PyObject_Del(unicode);
574 PyErr_NoMemory();
575 return NULL;
576 }
577 _Py_NewReference(unicode);
578 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200580 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200581 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
582 _PyUnicode_WSTR_LENGTH(unicode) = length;
583 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
585 length, 0);
586 return unicode;
587}
588
Alexander Belopolsky40018472011-02-26 01:02:56 +0000589static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200590resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591{
Victor Stinner95663112011-10-04 01:03:50 +0200592 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200594 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000595
Victor Stinner95663112011-10-04 01:03:50 +0200596 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597
598 if (PyUnicode_IS_READY(unicode)) {
599 Py_ssize_t char_size;
600 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200601 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 void *data;
603
604 data = _PyUnicode_DATA_ANY(unicode);
605 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200606 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200607 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
608 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200609 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
610 {
611 PyObject_DEL(_PyUnicode_UTF8(unicode));
612 _PyUnicode_UTF8(unicode) = NULL;
613 _PyUnicode_UTF8_LENGTH(unicode) = 0;
614 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 new_size = (length + 1) * char_size;
621
622 data = (PyObject *)PyObject_REALLOC(data, new_size);
623 if (data == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200629 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200630 _PyUnicode_WSTR_LENGTH(unicode) = length;
631 }
632 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200633 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_UTF8_LENGTH(unicode) = length;
635 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636 _PyUnicode_LENGTH(unicode) = length;
637 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200638 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200639 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200641 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642 }
Victor Stinner95663112011-10-04 01:03:50 +0200643 assert(_PyUnicode_WSTR(unicode) != NULL);
644
645 /* check for integer overflow */
646 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
647 PyErr_NoMemory();
648 return -1;
649 }
650 wstr = _PyUnicode_WSTR(unicode);
651 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
652 if (!wstr) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 _PyUnicode_WSTR(unicode) = wstr;
657 _PyUnicode_WSTR(unicode)[length] = 0;
658 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200659 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000660 return 0;
661}
662
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663static PyObject*
664resize_copy(PyObject *unicode, Py_ssize_t length)
665{
666 Py_ssize_t copy_length;
667 if (PyUnicode_IS_COMPACT(unicode)) {
668 PyObject *copy;
669 assert(PyUnicode_IS_READY(unicode));
670
671 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
672 if (copy == NULL)
673 return NULL;
674
675 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200676 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200678 }
679 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 assert(_PyUnicode_WSTR(unicode) != NULL);
682 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 if (w == NULL)
685 return NULL;
686 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
687 copy_length = Py_MIN(copy_length, length);
688 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
689 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200690 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200691 }
692}
693
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000695 Ux0000 terminated; some code (e.g. new_identifier)
696 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697
698 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000699 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701*/
702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200704static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#endif
706
Alexander Belopolsky40018472011-02-26 01:02:56 +0000707static PyUnicodeObject *
708_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000709{
710 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714 if (length == 0 && unicode_empty != NULL) {
715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200716 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 }
718
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000719 /* Ensure we won't overflow the size. */
720 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
721 return (PyUnicodeObject *)PyErr_NoMemory();
722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 if (length < 0) {
724 PyErr_SetString(PyExc_SystemError,
725 "Negative size passed to _PyUnicode_New");
726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727 }
728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729#ifdef Py_DEBUG
730 ++unicode_old_new_calls;
731#endif
732
733 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
734 if (unicode == NULL)
735 return NULL;
736 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
737 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
738 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000739 PyErr_NoMemory();
740 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742
Jeremy Hyltond8082792003-09-16 19:41:39 +0000743 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000744 * the caller fails before initializing str -- unicode_resize()
745 * reads str[0], and the Keep-Alive optimization can keep memory
746 * allocated for str alive across a call to unicode_dealloc(unicode).
747 * We don't want unicode_resize to read uninitialized memory in
748 * that case.
749 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 _PyUnicode_WSTR(unicode)[0] = 0;
751 _PyUnicode_WSTR(unicode)[length] = 0;
752 _PyUnicode_WSTR_LENGTH(unicode) = length;
753 _PyUnicode_HASH(unicode) = -1;
754 _PyUnicode_STATE(unicode).interned = 0;
755 _PyUnicode_STATE(unicode).kind = 0;
756 _PyUnicode_STATE(unicode).compact = 0;
757 _PyUnicode_STATE(unicode).ready = 0;
758 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200759 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200761 _PyUnicode_UTF8(unicode) = NULL;
762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100763 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000764 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000765
Benjamin Peterson29060642009-01-31 22:14:21 +0000766 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000767 /* XXX UNREF/NEWREF interface should be more symmetrical */
768 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000770 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000772}
773
Victor Stinnerf42dc442011-10-02 23:33:16 +0200774static const char*
775unicode_kind_name(PyObject *unicode)
776{
Victor Stinner42dfd712011-10-03 14:41:45 +0200777 /* don't check consistency: unicode_kind_name() is called from
778 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200779 if (!PyUnicode_IS_COMPACT(unicode))
780 {
781 if (!PyUnicode_IS_READY(unicode))
782 return "wstr";
783 switch(PyUnicode_KIND(unicode))
784 {
785 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200786 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200787 return "legacy ascii";
788 else
789 return "legacy latin1";
790 case PyUnicode_2BYTE_KIND:
791 return "legacy UCS2";
792 case PyUnicode_4BYTE_KIND:
793 return "legacy UCS4";
794 default:
795 return "<legacy invalid kind>";
796 }
797 }
798 assert(PyUnicode_IS_READY(unicode));
799 switch(PyUnicode_KIND(unicode))
800 {
801 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200802 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200803 return "ascii";
804 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 default:
811 return "<invalid compact kind>";
812 }
813}
814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200816static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817
818/* Functions wrapping macros for use in debugger */
819char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821}
822
823void *_PyUnicode_compact_data(void *unicode) {
824 return _PyUnicode_COMPACT_DATA(unicode);
825}
826void *_PyUnicode_data(void *unicode){
827 printf("obj %p\n", unicode);
828 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
829 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
830 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
831 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
832 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
833 return PyUnicode_DATA(unicode);
834}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200835
836void
837_PyUnicode_Dump(PyObject *op)
838{
839 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200840 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
841 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
842 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200843
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200845 {
846 if (ascii->state.ascii)
847 data = (ascii + 1);
848 else
849 data = (compact + 1);
850 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200851 else
852 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200853 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
854
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 if (ascii->wstr == data)
856 printf("shared ");
857 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200858
Victor Stinnera3b334d2011-10-03 13:53:37 +0200859 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200860 printf(" (%zu), ", compact->wstr_length);
861 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
862 printf("shared ");
863 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200865 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200866}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867#endif
868
869PyObject *
870PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
871{
872 PyObject *obj;
873 PyCompactUnicodeObject *unicode;
874 void *data;
875 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200876 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 Py_ssize_t char_size;
878 Py_ssize_t struct_size;
879
880 /* Optimization for empty strings */
881 if (size == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 }
885
886#ifdef Py_DEBUG
887 ++unicode_new_new_calls;
888#endif
889
Victor Stinner9e9d6892011-10-04 01:02:02 +0200890 is_ascii = 0;
891 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200892 struct_size = sizeof(PyCompactUnicodeObject);
893 if (maxchar < 128) {
894 kind_state = PyUnicode_1BYTE_KIND;
895 char_size = 1;
896 is_ascii = 1;
897 struct_size = sizeof(PyASCIIObject);
898 }
899 else if (maxchar < 256) {
900 kind_state = PyUnicode_1BYTE_KIND;
901 char_size = 1;
902 }
903 else if (maxchar < 65536) {
904 kind_state = PyUnicode_2BYTE_KIND;
905 char_size = 2;
906 if (sizeof(wchar_t) == 2)
907 is_sharing = 1;
908 }
909 else {
910 kind_state = PyUnicode_4BYTE_KIND;
911 char_size = 4;
912 if (sizeof(wchar_t) == 4)
913 is_sharing = 1;
914 }
915
916 /* Ensure we won't overflow the size. */
917 if (size < 0) {
918 PyErr_SetString(PyExc_SystemError,
919 "Negative size passed to PyUnicode_New");
920 return NULL;
921 }
922 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
923 return PyErr_NoMemory();
924
925 /* Duplicated allocation code from _PyObject_New() instead of a call to
926 * PyObject_New() so we are able to allocate space for the object and
927 * it's data buffer.
928 */
929 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
930 if (obj == NULL)
931 return PyErr_NoMemory();
932 obj = PyObject_INIT(obj, &PyUnicode_Type);
933 if (obj == NULL)
934 return NULL;
935
936 unicode = (PyCompactUnicodeObject *)obj;
937 if (is_ascii)
938 data = ((PyASCIIObject*)obj) + 1;
939 else
940 data = unicode + 1;
941 _PyUnicode_LENGTH(unicode) = size;
942 _PyUnicode_HASH(unicode) = -1;
943 _PyUnicode_STATE(unicode).interned = 0;
944 _PyUnicode_STATE(unicode).kind = kind_state;
945 _PyUnicode_STATE(unicode).compact = 1;
946 _PyUnicode_STATE(unicode).ready = 1;
947 _PyUnicode_STATE(unicode).ascii = is_ascii;
948 if (is_ascii) {
949 ((char*)data)[size] = 0;
950 _PyUnicode_WSTR(unicode) = NULL;
951 }
952 else if (kind_state == PyUnicode_1BYTE_KIND) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200957 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 }
959 else {
960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 if (kind_state == PyUnicode_2BYTE_KIND)
963 ((Py_UCS2*)data)[size] = 0;
964 else /* kind_state == PyUnicode_4BYTE_KIND */
965 ((Py_UCS4*)data)[size] = 0;
966 if (is_sharing) {
967 _PyUnicode_WSTR_LENGTH(unicode) = size;
968 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
969 }
970 else {
971 _PyUnicode_WSTR_LENGTH(unicode) = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 }
974 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100975 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return obj;
977}
978
979#if SIZEOF_WCHAR_T == 2
980/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
981 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200982 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983
984 This function assumes that unicode can hold one more code point than wstr
985 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200986static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200988 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989{
990 const wchar_t *iter;
991 Py_UCS4 *ucs4_out;
992
Victor Stinner910337b2011-10-03 03:20:16 +0200993 assert(unicode != NULL);
994 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
996 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
997
998 for (iter = begin; iter < end; ) {
999 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1000 _PyUnicode_GET_LENGTH(unicode)));
1001 if (*iter >= 0xD800 && *iter <= 0xDBFF
1002 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1003 {
1004 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1005 iter += 2;
1006 }
1007 else {
1008 *ucs4_out++ = *iter;
1009 iter++;
1010 }
1011 }
1012 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1013 _PyUnicode_GET_LENGTH(unicode)));
1014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015}
1016#endif
1017
Victor Stinnercd9950f2011-10-02 00:34:53 +02001018static int
1019_PyUnicode_Dirty(PyObject *unicode)
1020{
Victor Stinner910337b2011-10-03 03:20:16 +02001021 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001023 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001024 "Cannot modify a string having more than 1 reference");
1025 return -1;
1026 }
1027 _PyUnicode_DIRTY(unicode);
1028 return 0;
1029}
1030
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001031static int
1032_copy_characters(PyObject *to, Py_ssize_t to_start,
1033 PyObject *from, Py_ssize_t from_start,
1034 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001036 unsigned int from_kind, to_kind;
1037 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001040 assert(PyUnicode_Check(from));
1041 assert(PyUnicode_Check(to));
1042 assert(PyUnicode_IS_READY(from));
1043 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001045 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1046 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1047 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001049 if (how_many == 0)
1050 return 0;
1051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001055 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057#ifdef Py_DEBUG
1058 if (!check_maxchar
1059 && (from_kind > to_kind
1060 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001061 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1063 Py_UCS4 ch;
1064 Py_ssize_t i;
1065 for (i=0; i < how_many; i++) {
1066 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1067 assert(ch <= to_maxchar);
1068 }
1069 }
1070#endif
1071 fast = (from_kind == to_kind);
1072 if (check_maxchar
1073 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1074 {
1075 /* deny latin1 => ascii */
1076 fast = 0;
1077 }
1078
1079 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001080 Py_MEMCPY((char*)to_data + to_kind * to_start,
1081 (char*)from_data + from_kind * from_start,
1082 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
1085 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS2,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_2BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001094 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS1, Py_UCS4,
1099 PyUnicode_1BYTE_DATA(from) + from_start,
1100 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
1104 else if (from_kind == PyUnicode_2BYTE_KIND
1105 && to_kind == PyUnicode_4BYTE_KIND)
1106 {
1107 _PyUnicode_CONVERT_BYTES(
1108 Py_UCS2, Py_UCS4,
1109 PyUnicode_2BYTE_DATA(from) + from_start,
1110 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1111 PyUnicode_4BYTE_DATA(to) + to_start
1112 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001114 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001115 /* check if max_char(from substring) <= max_char(to) */
1116 if (from_kind > to_kind
1117 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001118 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001120 /* slow path to check for character overflow */
1121 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 Py_ssize_t i;
1124
Victor Stinner56c161a2011-10-06 02:47:11 +02001125#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 for (i=0; i < how_many; i++) {
1127 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001128 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1130 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001131#else
1132 if (!check_maxchar) {
1133 for (i=0; i < how_many; i++) {
1134 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1135 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1136 }
1137 }
1138 else {
1139 for (i=0; i < how_many; i++) {
1140 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1141 if (ch > to_maxchar)
1142 return 1;
1143 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1144 }
1145 }
1146#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001149 assert(0 && "inconsistent state");
1150 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
1152 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 return 0;
1154}
1155
1156static void
1157copy_characters(PyObject *to, Py_ssize_t to_start,
1158 PyObject *from, Py_ssize_t from_start,
1159 Py_ssize_t how_many)
1160{
1161 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1162}
1163
1164Py_ssize_t
1165PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1166 PyObject *from, Py_ssize_t from_start,
1167 Py_ssize_t how_many)
1168{
1169 int err;
1170
1171 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175
1176 if (PyUnicode_READY(from))
1177 return -1;
1178 if (PyUnicode_READY(to))
1179 return -1;
1180
1181 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1182 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1183 PyErr_Format(PyExc_SystemError,
1184 "Cannot write %zi characters at %zi "
1185 "in a string of %zi characters",
1186 how_many, to_start, PyUnicode_GET_LENGTH(to));
1187 return -1;
1188 }
1189
1190 if (how_many == 0)
1191 return 0;
1192
1193 if (_PyUnicode_Dirty(to))
1194 return -1;
1195
1196 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1197 if (err) {
1198 PyErr_Format(PyExc_SystemError,
1199 "Cannot copy %s characters "
1200 "into a string of %s characters",
1201 unicode_kind_name(from),
1202 unicode_kind_name(to));
1203 return -1;
1204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206}
1207
Victor Stinner17222162011-09-28 22:15:37 +02001208/* Find the maximum code point and count the number of surrogate pairs so a
1209 correct string length can be computed before converting a string to UCS4.
1210 This function counts single surrogates as a character and not as a pair.
1211
1212 Return 0 on success, or -1 on error. */
1213static int
1214find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1215 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216{
1217 const wchar_t *iter;
1218
Victor Stinnerc53be962011-10-02 21:33:54 +02001219 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 *num_surrogates = 0;
1221 *maxchar = 0;
1222
1223 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001224 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001226#if SIZEOF_WCHAR_T != 2
1227 if (*maxchar >= 0x10000)
1228 return 0;
1229#endif
1230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231#if SIZEOF_WCHAR_T == 2
1232 if (*iter >= 0xD800 && *iter <= 0xDBFF
1233 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1234 {
1235 Py_UCS4 surrogate_val;
1236 surrogate_val = (((iter[0] & 0x3FF)<<10)
1237 | (iter[1] & 0x3FF)) + 0x10000;
1238 ++(*num_surrogates);
1239 if (surrogate_val > *maxchar)
1240 *maxchar = surrogate_val;
1241 iter += 2;
1242 }
1243 else
1244 iter++;
1245#else
1246 iter++;
1247#endif
1248 }
1249 return 0;
1250}
1251
1252#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001253static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254#endif
1255
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001256static int
1257unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001259 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 wchar_t *end;
1261 Py_UCS4 maxchar = 0;
1262 Py_ssize_t num_surrogates;
1263#if SIZEOF_WCHAR_T == 2
1264 Py_ssize_t length_wo_surrogates;
1265#endif
1266
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001268 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001269
Georg Brandl7597add2011-10-05 16:36:47 +02001270 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001271 strings were created using _PyObject_New() and where no canonical
1272 representation (the str field) has been set yet aka strings
1273 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001274 assert(_PyUnicode_CHECK(unicode));
1275 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001277 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001278 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001279 /* Actually, it should neither be interned nor be anything else: */
1280 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001281
1282#ifdef Py_DEBUG
1283 ++unicode_ready_calls;
1284#endif
1285
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286#ifdef Py_DEBUG
1287 assert(!replace || Py_REFCNT(unicode) == 1);
1288#else
1289 if (replace && Py_REFCNT(unicode) != 1)
1290 replace = 0;
1291#endif
1292 if (replace) {
1293 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1294 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1295 /* Optimization for empty strings */
1296 if (len == 0) {
1297 Py_INCREF(unicode_empty);
1298 Py_DECREF(*p_obj);
1299 *p_obj = unicode_empty;
1300 return 0;
1301 }
1302 if (len == 1 && wstr[0] < 256) {
1303 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1304 if (latin1_char == NULL)
1305 return -1;
1306 Py_DECREF(*p_obj);
1307 *p_obj = latin1_char;
1308 return 0;
1309 }
1310 }
1311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001313 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001314 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001318 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1319 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 PyErr_NoMemory();
1321 return -1;
1322 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001323 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 _PyUnicode_WSTR(unicode), end,
1325 PyUnicode_1BYTE_DATA(unicode));
1326 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1327 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1328 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1329 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001330 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001331 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 }
1334 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001335 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8(unicode) = NULL;
1337 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 PyObject_FREE(_PyUnicode_WSTR(unicode));
1340 _PyUnicode_WSTR(unicode) = NULL;
1341 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1342 }
1343 /* In this case we might have to convert down from 4-byte native
1344 wchar_t to 2-byte unicode. */
1345 else if (maxchar < 65536) {
1346 assert(num_surrogates == 0 &&
1347 "FindMaxCharAndNumSurrogatePairs() messed up");
1348
Victor Stinner506f5922011-09-28 22:34:18 +02001349#if SIZEOF_WCHAR_T == 2
1350 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1353 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1354 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001355 _PyUnicode_UTF8(unicode) = NULL;
1356 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001357#else
1358 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001360 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001361 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001362 PyErr_NoMemory();
1363 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 }
Victor Stinner506f5922011-09-28 22:34:18 +02001365 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1366 _PyUnicode_WSTR(unicode), end,
1367 PyUnicode_2BYTE_DATA(unicode));
1368 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1369 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1370 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001371 _PyUnicode_UTF8(unicode) = NULL;
1372 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001373 PyObject_FREE(_PyUnicode_WSTR(unicode));
1374 _PyUnicode_WSTR(unicode) = NULL;
1375 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 }
1378 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1379 else {
1380#if SIZEOF_WCHAR_T == 2
1381 /* in case the native representation is 2-bytes, we need to allocate a
1382 new normalized 4-byte version. */
1383 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
1389 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001391 _PyUnicode_UTF8(unicode) = NULL;
1392 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001393 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1394 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001395 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 PyObject_FREE(_PyUnicode_WSTR(unicode));
1397 _PyUnicode_WSTR(unicode) = NULL;
1398 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1399#else
1400 assert(num_surrogates == 0);
1401
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1407#endif
1408 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1409 }
1410 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001411 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 return 0;
1413}
1414
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001415int
1416_PyUnicode_ReadyReplace(PyObject **op)
1417{
1418 return unicode_ready(op, 1);
1419}
1420
1421int
1422_PyUnicode_Ready(PyObject *op)
1423{
1424 return unicode_ready(&op, 0);
1425}
1426
Alexander Belopolsky40018472011-02-26 01:02:56 +00001427static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001428unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001429{
Walter Dörwald16807132007-05-25 13:52:07 +00001430 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001431 case SSTATE_NOT_INTERNED:
1432 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_INTERNED_MORTAL:
1435 /* revive dead object temporarily for DelItem */
1436 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001437 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 Py_FatalError(
1439 "deletion of interned string failed");
1440 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001441
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 case SSTATE_INTERNED_IMMORTAL:
1443 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 default:
1446 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447 }
1448
Victor Stinner03490912011-10-03 23:45:12 +02001449 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001451 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453
1454 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001456 }
1457 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 if (_PyUnicode_DATA_ANY(unicode))
1459 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001460 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001461 }
1462}
1463
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001464#ifdef Py_DEBUG
1465static int
1466unicode_is_singleton(PyObject *unicode)
1467{
1468 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1469 if (unicode == unicode_empty)
1470 return 1;
1471 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1472 {
1473 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1474 if (ch < 256 && unicode_latin1[ch] == unicode)
1475 return 1;
1476 }
1477 return 0;
1478}
1479#endif
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001483{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001484 if (Py_REFCNT(unicode) != 1)
1485 return 0;
1486 if (PyUnicode_CHECK_INTERNED(unicode))
1487 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001488#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001489 /* singleton refcount is greater than 1 */
1490 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001492 return 1;
1493}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001494
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495static int
1496unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1497{
1498 PyObject *unicode;
1499 Py_ssize_t old_length;
1500
1501 assert(p_unicode != NULL);
1502 unicode = *p_unicode;
1503
1504 assert(unicode != NULL);
1505 assert(PyUnicode_Check(unicode));
1506 assert(0 <= length);
1507
Victor Stinner910337b2011-10-03 03:20:16 +02001508 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 old_length = PyUnicode_WSTR_LENGTH(unicode);
1510 else
1511 old_length = PyUnicode_GET_LENGTH(unicode);
1512 if (old_length == length)
1513 return 0;
1514
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001515 if (length == 0) {
1516 Py_DECREF(*p_unicode);
1517 *p_unicode = unicode_empty;
1518 Py_INCREF(*p_unicode);
1519 return 0;
1520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (!unicode_resizable(unicode)) {
1523 PyObject *copy = resize_copy(unicode, length);
1524 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 Py_DECREF(*p_unicode);
1527 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001529 }
1530
Victor Stinnerfe226c02011-10-03 03:52:20 +02001531 if (PyUnicode_IS_COMPACT(unicode)) {
1532 *p_unicode = resize_compact(unicode, length);
1533 if (*p_unicode == NULL)
1534 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001535 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001537 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001538 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001539}
1540
Alexander Belopolsky40018472011-02-26 01:02:56 +00001541int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001543{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 PyObject *unicode;
1545 if (p_unicode == NULL) {
1546 PyErr_BadInternalCall();
1547 return -1;
1548 }
1549 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001550 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001551 {
1552 PyErr_BadInternalCall();
1553 return -1;
1554 }
1555 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001556}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001558static int
1559unicode_widen(PyObject **p_unicode, int maxchar)
1560{
1561 PyObject *result;
1562 assert(PyUnicode_IS_READY(*p_unicode));
1563 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1564 return 0;
1565 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1566 maxchar);
1567 if (result == NULL)
1568 return -1;
1569 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1570 PyUnicode_GET_LENGTH(*p_unicode));
1571 Py_DECREF(*p_unicode);
1572 *p_unicode = result;
1573 return 0;
1574}
1575
1576static int
1577unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1578 Py_UCS4 ch)
1579{
1580 if (unicode_widen(p_unicode, ch) < 0)
1581 return -1;
1582 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1583 PyUnicode_DATA(*p_unicode),
1584 (*pos)++, ch);
1585 return 0;
1586}
1587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588static PyObject*
1589get_latin1_char(unsigned char ch)
1590{
Victor Stinnera464fc12011-10-02 20:39:30 +02001591 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001593 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 if (!unicode)
1595 return NULL;
1596 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001597 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 unicode_latin1[ch] = unicode;
1599 }
1600 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001601 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602}
1603
Alexander Belopolsky40018472011-02-26 01:02:56 +00001604PyObject *
1605PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 Py_UCS4 maxchar = 0;
1609 Py_ssize_t num_surrogates;
1610
1611 if (u == NULL)
1612 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001613
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001614 /* If the Unicode data is known at construction time, we can apply
1615 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* Optimization for empty strings */
1618 if (size == 0 && unicode_empty != NULL) {
1619 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001620 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001621 }
Tim Petersced69f82003-09-16 20:30:58 +00001622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 /* Single character Unicode objects in the Latin-1 range are
1624 shared when using this constructor */
1625 if (size == 1 && *u < 256)
1626 return get_latin1_char((unsigned char)*u);
1627
1628 /* If not empty and not single character, copy the Unicode data
1629 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001630 if (find_maxchar_surrogates(u, u + size,
1631 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 return NULL;
1633
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636 if (!unicode)
1637 return NULL;
1638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 switch (PyUnicode_KIND(unicode)) {
1640 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001641 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1643 break;
1644 case PyUnicode_2BYTE_KIND:
1645#if Py_UNICODE_SIZE == 2
1646 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1647#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001648 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1650#endif
1651 break;
1652 case PyUnicode_4BYTE_KIND:
1653#if SIZEOF_WCHAR_T == 2
1654 /* This is the only case which has to process surrogates, thus
1655 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001656 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#else
1658 assert(num_surrogates == 0);
1659 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1660#endif
1661 break;
1662 default:
1663 assert(0 && "Impossible state");
1664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001665
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001666 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001672{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001673 if (size < 0) {
1674 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001676 return NULL;
1677 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001678
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001679 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001680 some optimizations which share commonly used objects.
1681 Also, this means the input must be UTF-8, so fall back to the
1682 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 if (u != NULL) {
1684
Benjamin Peterson29060642009-01-31 22:14:21 +00001685 /* Optimization for empty strings */
1686 if (size == 0 && unicode_empty != NULL) {
1687 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001688 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001690
1691 /* Single characters are shared when using this constructor.
1692 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001693 if (size == 1 && (unsigned char)*u < 128)
1694 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001695
1696 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 }
1698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001699 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001704{
1705 size_t size = strlen(u);
1706 if (size > PY_SSIZE_T_MAX) {
1707 PyErr_SetString(PyExc_OverflowError, "input too long");
1708 return NULL;
1709 }
1710
1711 return PyUnicode_FromStringAndSize(u, size);
1712}
1713
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001714PyObject *
1715_PyUnicode_FromId(_Py_Identifier *id)
1716{
1717 if (!id->object) {
1718 id->object = PyUnicode_FromString(id->string);
1719 if (!id->object)
1720 return NULL;
1721 PyUnicode_InternInPlace(&id->object);
1722 assert(!id->next);
1723 id->next = static_strings;
1724 static_strings = id;
1725 }
1726 Py_INCREF(id->object);
1727 return id->object;
1728}
1729
1730void
1731_PyUnicode_ClearStaticStrings()
1732{
1733 _Py_Identifier *i;
1734 for (i = static_strings; i; i = i->next) {
1735 Py_DECREF(i->object);
1736 i->object = NULL;
1737 i->next = NULL;
1738 }
1739}
1740
Victor Stinnere57b1c02011-09-28 22:20:48 +02001741static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001742unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001743{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001744 PyObject *res;
1745#ifdef Py_DEBUG
1746 const unsigned char *p;
1747 const unsigned char *end = s + size;
1748 for (p=s; p < end; p++) {
1749 assert(*p < 128);
1750 }
1751#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001752 if (size == 1)
1753 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001754 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001755 if (!res)
1756 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001757 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001758 return res;
1759}
1760
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001761static Py_UCS4
1762kind_maxchar_limit(unsigned int kind)
1763{
1764 switch(kind) {
1765 case PyUnicode_1BYTE_KIND:
1766 return 0x80;
1767 case PyUnicode_2BYTE_KIND:
1768 return 0x100;
1769 case PyUnicode_4BYTE_KIND:
1770 return 0x10000;
1771 default:
1772 assert(0 && "invalid kind");
1773 return 0x10ffff;
1774 }
1775}
1776
Victor Stinner702c7342011-10-05 13:50:52 +02001777static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001778_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001779{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001780 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001781 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001782
1783 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001784 if (size == 1)
1785 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001786 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001787 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001788 if (!res)
1789 return NULL;
1790 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001791 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001792 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001793}
1794
Victor Stinnere57b1c02011-09-28 22:20:48 +02001795static PyObject*
1796_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001797{
1798 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001799 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001800
1801 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001802 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001803 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001804 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001805 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001806 if (!res)
1807 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001808 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001809 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001810 else {
1811 _PyUnicode_CONVERT_BYTES(
1812 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1813 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001814 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001815 return res;
1816}
1817
Victor Stinnere57b1c02011-09-28 22:20:48 +02001818static PyObject*
1819_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001820{
1821 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001823
1824 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001825 if (size == 1 && u[0] < 256)
1826 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001827 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001828 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001829 if (!res)
1830 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001831 if (max_char < 256)
1832 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1833 PyUnicode_1BYTE_DATA(res));
1834 else if (max_char < 0x10000)
1835 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1836 PyUnicode_2BYTE_DATA(res));
1837 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001838 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001839 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001840 return res;
1841}
1842
1843PyObject*
1844PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1845{
1846 switch(kind) {
1847 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001848 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001849 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001850 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001851 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001852 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001853 default:
1854 assert(0 && "invalid kind");
1855 PyErr_SetString(PyExc_SystemError, "invalid kind");
1856 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001858}
1859
Victor Stinner25a4b292011-10-06 12:31:55 +02001860/* Ensure that a string uses the most efficient storage, if it is not the
1861 case: create a new string with of the right kind. Write NULL into *p_unicode
1862 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001863static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001864unicode_adjust_maxchar(PyObject **p_unicode)
1865{
1866 PyObject *unicode, *copy;
1867 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001868 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001869 unsigned int kind;
1870
1871 assert(p_unicode != NULL);
1872 unicode = *p_unicode;
1873 assert(PyUnicode_IS_READY(unicode));
1874 if (PyUnicode_IS_ASCII(unicode))
1875 return;
1876
1877 len = PyUnicode_GET_LENGTH(unicode);
1878 kind = PyUnicode_KIND(unicode);
1879 if (kind == PyUnicode_1BYTE_KIND) {
1880 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001881 max_char = ucs1lib_find_max_char(u, u + len);
1882 if (max_char >= 128)
1883 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001884 }
1885 else if (kind == PyUnicode_2BYTE_KIND) {
1886 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001887 max_char = ucs2lib_find_max_char(u, u + len);
1888 if (max_char >= 256)
1889 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001890 }
1891 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001892 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001893 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001894 max_char = ucs4lib_find_max_char(u, u + len);
1895 if (max_char >= 0x10000)
1896 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001897 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001898 copy = PyUnicode_New(len, max_char);
1899 copy_characters(copy, 0, unicode, 0, len);
1900 Py_DECREF(unicode);
1901 *p_unicode = copy;
1902}
1903
Victor Stinner034f6cf2011-09-30 02:26:44 +02001904PyObject*
1905PyUnicode_Copy(PyObject *unicode)
1906{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001907 Py_ssize_t size;
1908 PyObject *copy;
1909 void *data;
1910
Victor Stinner034f6cf2011-09-30 02:26:44 +02001911 if (!PyUnicode_Check(unicode)) {
1912 PyErr_BadInternalCall();
1913 return NULL;
1914 }
1915 if (PyUnicode_READY(unicode))
1916 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001917
1918 size = PyUnicode_GET_LENGTH(unicode);
1919 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1920 if (!copy)
1921 return NULL;
1922 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1923
1924 data = PyUnicode_DATA(unicode);
1925 switch (PyUnicode_KIND(unicode))
1926 {
1927 case PyUnicode_1BYTE_KIND:
1928 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1929 break;
1930 case PyUnicode_2BYTE_KIND:
1931 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1932 break;
1933 case PyUnicode_4BYTE_KIND:
1934 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1935 break;
1936 default:
1937 assert(0);
1938 break;
1939 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001940 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001941 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001942}
1943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001944
Victor Stinnerbc603d12011-10-02 01:00:40 +02001945/* Widen Unicode objects to larger buffers. Don't write terminating null
1946 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001947
1948void*
1949_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1950{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001951 Py_ssize_t len;
1952 void *result;
1953 unsigned int skind;
1954
1955 if (PyUnicode_READY(s))
1956 return NULL;
1957
1958 len = PyUnicode_GET_LENGTH(s);
1959 skind = PyUnicode_KIND(s);
1960 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001961 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001962 return NULL;
1963 }
1964 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001965 case PyUnicode_2BYTE_KIND:
1966 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1967 if (!result)
1968 return PyErr_NoMemory();
1969 assert(skind == PyUnicode_1BYTE_KIND);
1970 _PyUnicode_CONVERT_BYTES(
1971 Py_UCS1, Py_UCS2,
1972 PyUnicode_1BYTE_DATA(s),
1973 PyUnicode_1BYTE_DATA(s) + len,
1974 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001975 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001976 case PyUnicode_4BYTE_KIND:
1977 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1978 if (!result)
1979 return PyErr_NoMemory();
1980 if (skind == PyUnicode_2BYTE_KIND) {
1981 _PyUnicode_CONVERT_BYTES(
1982 Py_UCS2, Py_UCS4,
1983 PyUnicode_2BYTE_DATA(s),
1984 PyUnicode_2BYTE_DATA(s) + len,
1985 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001986 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001987 else {
1988 assert(skind == PyUnicode_1BYTE_KIND);
1989 _PyUnicode_CONVERT_BYTES(
1990 Py_UCS1, Py_UCS4,
1991 PyUnicode_1BYTE_DATA(s),
1992 PyUnicode_1BYTE_DATA(s) + len,
1993 result);
1994 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001995 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001996 default:
1997 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001998 }
Victor Stinner01698042011-10-04 00:04:26 +02001999 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002000 return NULL;
2001}
2002
2003static Py_UCS4*
2004as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2005 int copy_null)
2006{
2007 int kind;
2008 void *data;
2009 Py_ssize_t len, targetlen;
2010 if (PyUnicode_READY(string) == -1)
2011 return NULL;
2012 kind = PyUnicode_KIND(string);
2013 data = PyUnicode_DATA(string);
2014 len = PyUnicode_GET_LENGTH(string);
2015 targetlen = len;
2016 if (copy_null)
2017 targetlen++;
2018 if (!target) {
2019 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2020 PyErr_NoMemory();
2021 return NULL;
2022 }
2023 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2024 if (!target) {
2025 PyErr_NoMemory();
2026 return NULL;
2027 }
2028 }
2029 else {
2030 if (targetsize < targetlen) {
2031 PyErr_Format(PyExc_SystemError,
2032 "string is longer than the buffer");
2033 if (copy_null && 0 < targetsize)
2034 target[0] = 0;
2035 return NULL;
2036 }
2037 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002038 if (kind == PyUnicode_1BYTE_KIND) {
2039 Py_UCS1 *start = (Py_UCS1 *) data;
2040 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002041 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002042 else if (kind == PyUnicode_2BYTE_KIND) {
2043 Py_UCS2 *start = (Py_UCS2 *) data;
2044 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2045 }
2046 else {
2047 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002048 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002049 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002050 if (copy_null)
2051 target[len] = 0;
2052 return target;
2053}
2054
2055Py_UCS4*
2056PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2057 int copy_null)
2058{
2059 if (target == NULL || targetsize < 1) {
2060 PyErr_BadInternalCall();
2061 return NULL;
2062 }
2063 return as_ucs4(string, target, targetsize, copy_null);
2064}
2065
2066Py_UCS4*
2067PyUnicode_AsUCS4Copy(PyObject *string)
2068{
2069 return as_ucs4(string, NULL, 0, 1);
2070}
2071
2072#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002073
Alexander Belopolsky40018472011-02-26 01:02:56 +00002074PyObject *
2075PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002076{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002077 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002078 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002079 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002080 PyErr_BadInternalCall();
2081 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002082 }
2083
Martin v. Löwis790465f2008-04-05 20:41:37 +00002084 if (size == -1) {
2085 size = wcslen(w);
2086 }
2087
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002088 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002089}
2090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002091#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002092
Walter Dörwald346737f2007-05-31 10:44:43 +00002093static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002094makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2095 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002096{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002097 *fmt++ = '%';
2098 if (width) {
2099 if (zeropad)
2100 *fmt++ = '0';
2101 fmt += sprintf(fmt, "%d", width);
2102 }
2103 if (precision)
2104 fmt += sprintf(fmt, ".%d", precision);
2105 if (longflag)
2106 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002107 else if (longlongflag) {
2108 /* longlongflag should only ever be nonzero on machines with
2109 HAVE_LONG_LONG defined */
2110#ifdef HAVE_LONG_LONG
2111 char *f = PY_FORMAT_LONG_LONG;
2112 while (*f)
2113 *fmt++ = *f++;
2114#else
2115 /* we shouldn't ever get here */
2116 assert(0);
2117 *fmt++ = 'l';
2118#endif
2119 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002120 else if (size_tflag) {
2121 char *f = PY_FORMAT_SIZE_T;
2122 while (*f)
2123 *fmt++ = *f++;
2124 }
2125 *fmt++ = c;
2126 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002127}
2128
Victor Stinner96865452011-03-01 23:44:09 +00002129/* helper for PyUnicode_FromFormatV() */
2130
2131static const char*
2132parse_format_flags(const char *f,
2133 int *p_width, int *p_precision,
2134 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2135{
2136 int width, precision, longflag, longlongflag, size_tflag;
2137
2138 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2139 f++;
2140 width = 0;
2141 while (Py_ISDIGIT((unsigned)*f))
2142 width = (width*10) + *f++ - '0';
2143 precision = 0;
2144 if (*f == '.') {
2145 f++;
2146 while (Py_ISDIGIT((unsigned)*f))
2147 precision = (precision*10) + *f++ - '0';
2148 if (*f == '%') {
2149 /* "%.3%s" => f points to "3" */
2150 f--;
2151 }
2152 }
2153 if (*f == '\0') {
2154 /* bogus format "%.1" => go backward, f points to "1" */
2155 f--;
2156 }
2157 if (p_width != NULL)
2158 *p_width = width;
2159 if (p_precision != NULL)
2160 *p_precision = precision;
2161
2162 /* Handle %ld, %lu, %lld and %llu. */
2163 longflag = 0;
2164 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002165 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002166
2167 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002168 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002169 longflag = 1;
2170 ++f;
2171 }
2172#ifdef HAVE_LONG_LONG
2173 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002174 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002175 longlongflag = 1;
2176 f += 2;
2177 }
2178#endif
2179 }
2180 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002181 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002182 size_tflag = 1;
2183 ++f;
2184 }
2185 if (p_longflag != NULL)
2186 *p_longflag = longflag;
2187 if (p_longlongflag != NULL)
2188 *p_longlongflag = longlongflag;
2189 if (p_size_tflag != NULL)
2190 *p_size_tflag = size_tflag;
2191 return f;
2192}
2193
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002194/* maximum number of characters required for output of %ld. 21 characters
2195 allows for 64-bit integers (in decimal) and an optional sign. */
2196#define MAX_LONG_CHARS 21
2197/* maximum number of characters required for output of %lld.
2198 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2199 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2200#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2201
Walter Dörwaldd2034312007-05-18 16:29:38 +00002202PyObject *
2203PyUnicode_FromFormatV(const char *format, va_list vargs)
2204{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002205 va_list count;
2206 Py_ssize_t callcount = 0;
2207 PyObject **callresults = NULL;
2208 PyObject **callresult = NULL;
2209 Py_ssize_t n = 0;
2210 int width = 0;
2211 int precision = 0;
2212 int zeropad;
2213 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002214 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002215 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002216 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002217 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2218 Py_UCS4 argmaxchar;
2219 Py_ssize_t numbersize = 0;
2220 char *numberresults = NULL;
2221 char *numberresult = NULL;
2222 Py_ssize_t i;
2223 int kind;
2224 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002225
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002226 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002227 /* step 1: count the number of %S/%R/%A/%s format specifications
2228 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2229 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002230 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002231 * also estimate a upper bound for all the number formats in the string,
2232 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002233 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002234 for (f = format; *f; f++) {
2235 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002236 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002237 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2238 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2239 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2240 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002241
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002242 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002243#ifdef HAVE_LONG_LONG
2244 if (longlongflag) {
2245 if (width < MAX_LONG_LONG_CHARS)
2246 width = MAX_LONG_LONG_CHARS;
2247 }
2248 else
2249#endif
2250 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2251 including sign. Decimal takes the most space. This
2252 isn't enough for octal. If a width is specified we
2253 need more (which we allocate later). */
2254 if (width < MAX_LONG_CHARS)
2255 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002256
2257 /* account for the size + '\0' to separate numbers
2258 inside of the numberresults buffer */
2259 numbersize += (width + 1);
2260 }
2261 }
2262 else if ((unsigned char)*f > 127) {
2263 PyErr_Format(PyExc_ValueError,
2264 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2265 "string, got a non-ASCII byte: 0x%02x",
2266 (unsigned char)*f);
2267 return NULL;
2268 }
2269 }
2270 /* step 2: allocate memory for the results of
2271 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2272 if (callcount) {
2273 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2274 if (!callresults) {
2275 PyErr_NoMemory();
2276 return NULL;
2277 }
2278 callresult = callresults;
2279 }
2280 /* step 2.5: allocate memory for the results of formating numbers */
2281 if (numbersize) {
2282 numberresults = PyObject_Malloc(numbersize);
2283 if (!numberresults) {
2284 PyErr_NoMemory();
2285 goto fail;
2286 }
2287 numberresult = numberresults;
2288 }
2289
2290 /* step 3: format numbers and figure out how large a buffer we need */
2291 for (f = format; *f; f++) {
2292 if (*f == '%') {
2293 const char* p;
2294 int longflag;
2295 int longlongflag;
2296 int size_tflag;
2297 int numprinted;
2298
2299 p = f;
2300 zeropad = (f[1] == '0');
2301 f = parse_format_flags(f, &width, &precision,
2302 &longflag, &longlongflag, &size_tflag);
2303 switch (*f) {
2304 case 'c':
2305 {
2306 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002307 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002308 n++;
2309 break;
2310 }
2311 case '%':
2312 n++;
2313 break;
2314 case 'i':
2315 case 'd':
2316 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2317 width, precision, *f);
2318 if (longflag)
2319 numprinted = sprintf(numberresult, fmt,
2320 va_arg(count, long));
2321#ifdef HAVE_LONG_LONG
2322 else if (longlongflag)
2323 numprinted = sprintf(numberresult, fmt,
2324 va_arg(count, PY_LONG_LONG));
2325#endif
2326 else if (size_tflag)
2327 numprinted = sprintf(numberresult, fmt,
2328 va_arg(count, Py_ssize_t));
2329 else
2330 numprinted = sprintf(numberresult, fmt,
2331 va_arg(count, int));
2332 n += numprinted;
2333 /* advance by +1 to skip over the '\0' */
2334 numberresult += (numprinted + 1);
2335 assert(*(numberresult - 1) == '\0');
2336 assert(*(numberresult - 2) != '\0');
2337 assert(numprinted >= 0);
2338 assert(numberresult <= numberresults + numbersize);
2339 break;
2340 case 'u':
2341 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2342 width, precision, 'u');
2343 if (longflag)
2344 numprinted = sprintf(numberresult, fmt,
2345 va_arg(count, unsigned long));
2346#ifdef HAVE_LONG_LONG
2347 else if (longlongflag)
2348 numprinted = sprintf(numberresult, fmt,
2349 va_arg(count, unsigned PY_LONG_LONG));
2350#endif
2351 else if (size_tflag)
2352 numprinted = sprintf(numberresult, fmt,
2353 va_arg(count, size_t));
2354 else
2355 numprinted = sprintf(numberresult, fmt,
2356 va_arg(count, unsigned int));
2357 n += numprinted;
2358 numberresult += (numprinted + 1);
2359 assert(*(numberresult - 1) == '\0');
2360 assert(*(numberresult - 2) != '\0');
2361 assert(numprinted >= 0);
2362 assert(numberresult <= numberresults + numbersize);
2363 break;
2364 case 'x':
2365 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2366 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2367 n += numprinted;
2368 numberresult += (numprinted + 1);
2369 assert(*(numberresult - 1) == '\0');
2370 assert(*(numberresult - 2) != '\0');
2371 assert(numprinted >= 0);
2372 assert(numberresult <= numberresults + numbersize);
2373 break;
2374 case 'p':
2375 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2376 /* %p is ill-defined: ensure leading 0x. */
2377 if (numberresult[1] == 'X')
2378 numberresult[1] = 'x';
2379 else if (numberresult[1] != 'x') {
2380 memmove(numberresult + 2, numberresult,
2381 strlen(numberresult) + 1);
2382 numberresult[0] = '0';
2383 numberresult[1] = 'x';
2384 numprinted += 2;
2385 }
2386 n += numprinted;
2387 numberresult += (numprinted + 1);
2388 assert(*(numberresult - 1) == '\0');
2389 assert(*(numberresult - 2) != '\0');
2390 assert(numprinted >= 0);
2391 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002392 break;
2393 case 's':
2394 {
2395 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002396 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002397 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2398 if (!str)
2399 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002400 /* since PyUnicode_DecodeUTF8 returns already flexible
2401 unicode objects, there is no need to call ready on them */
2402 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002403 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002404 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002405 /* Remember the str and switch to the next slot */
2406 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002407 break;
2408 }
2409 case 'U':
2410 {
2411 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002412 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002413 if (PyUnicode_READY(obj) == -1)
2414 goto fail;
2415 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002416 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002417 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002418 break;
2419 }
2420 case 'V':
2421 {
2422 PyObject *obj = va_arg(count, PyObject *);
2423 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002424 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002425 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002426 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002427 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002428 if (PyUnicode_READY(obj) == -1)
2429 goto fail;
2430 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002431 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002432 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002433 *callresult++ = NULL;
2434 }
2435 else {
2436 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2437 if (!str_obj)
2438 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002439 if (PyUnicode_READY(str_obj)) {
2440 Py_DECREF(str_obj);
2441 goto fail;
2442 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002443 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002444 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002445 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002446 *callresult++ = str_obj;
2447 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002448 break;
2449 }
2450 case 'S':
2451 {
2452 PyObject *obj = va_arg(count, PyObject *);
2453 PyObject *str;
2454 assert(obj);
2455 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002456 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002457 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002458 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002459 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002460 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002461 /* Remember the str and switch to the next slot */
2462 *callresult++ = str;
2463 break;
2464 }
2465 case 'R':
2466 {
2467 PyObject *obj = va_arg(count, PyObject *);
2468 PyObject *repr;
2469 assert(obj);
2470 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002471 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002472 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002473 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002474 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002475 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002476 /* Remember the repr and switch to the next slot */
2477 *callresult++ = repr;
2478 break;
2479 }
2480 case 'A':
2481 {
2482 PyObject *obj = va_arg(count, PyObject *);
2483 PyObject *ascii;
2484 assert(obj);
2485 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002486 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002487 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002488 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002489 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002490 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002491 /* Remember the repr and switch to the next slot */
2492 *callresult++ = ascii;
2493 break;
2494 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002495 default:
2496 /* if we stumble upon an unknown
2497 formatting code, copy the rest of
2498 the format string to the output
2499 string. (we cannot just skip the
2500 code, since there's no way to know
2501 what's in the argument list) */
2502 n += strlen(p);
2503 goto expand;
2504 }
2505 } else
2506 n++;
2507 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002508 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002509 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002510 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002511 we don't have to resize the string.
2512 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002513 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002514 if (!string)
2515 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002516 kind = PyUnicode_KIND(string);
2517 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002518 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002519 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002520
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002521 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002522 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002523 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002524
2525 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002526 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2527 /* checking for == because the last argument could be a empty
2528 string, which causes i to point to end, the assert at the end of
2529 the loop */
2530 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002531
Benjamin Peterson14339b62009-01-31 16:36:08 +00002532 switch (*f) {
2533 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002534 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002535 const int ordinal = va_arg(vargs, int);
2536 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002537 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002538 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002539 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002542 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002543 case 'p':
2544 /* unused, since we already have the result */
2545 if (*f == 'p')
2546 (void) va_arg(vargs, void *);
2547 else
2548 (void) va_arg(vargs, int);
2549 /* extract the result from numberresults and append. */
2550 for (; *numberresult; ++i, ++numberresult)
2551 PyUnicode_WRITE(kind, data, i, *numberresult);
2552 /* skip over the separating '\0' */
2553 assert(*numberresult == '\0');
2554 numberresult++;
2555 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002556 break;
2557 case 's':
2558 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002559 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002560 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002561 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002562 size = PyUnicode_GET_LENGTH(*callresult);
2563 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002564 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002565 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002566 /* We're done with the unicode()/repr() => forget it */
2567 Py_DECREF(*callresult);
2568 /* switch to next unicode()/repr() result */
2569 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002570 break;
2571 }
2572 case 'U':
2573 {
2574 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002575 Py_ssize_t size;
2576 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2577 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002578 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002579 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002580 break;
2581 }
2582 case 'V':
2583 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002584 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002585 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002586 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002587 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002588 size = PyUnicode_GET_LENGTH(obj);
2589 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002590 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002591 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002592 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002593 size = PyUnicode_GET_LENGTH(*callresult);
2594 assert(PyUnicode_KIND(*callresult) <=
2595 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002596 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002597 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002598 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002599 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002600 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002601 break;
2602 }
2603 case 'S':
2604 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002605 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002606 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002607 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002608 /* unused, since we already have the result */
2609 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002610 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002611 copy_characters(string, i, *callresult, 0, size);
2612 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002613 /* We're done with the unicode()/repr() => forget it */
2614 Py_DECREF(*callresult);
2615 /* switch to next unicode()/repr() result */
2616 ++callresult;
2617 break;
2618 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002619 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002620 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002621 break;
2622 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002623 for (; *p; ++p, ++i)
2624 PyUnicode_WRITE(kind, data, i, *p);
2625 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002626 goto end;
2627 }
Victor Stinner1205f272010-09-11 00:54:47 +00002628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002629 else {
2630 assert(i < PyUnicode_GET_LENGTH(string));
2631 PyUnicode_WRITE(kind, data, i++, *f);
2632 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002634 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002635
Benjamin Peterson29060642009-01-31 22:14:21 +00002636 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002637 if (callresults)
2638 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002639 if (numberresults)
2640 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002641 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002642 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002643 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002644 if (callresults) {
2645 PyObject **callresult2 = callresults;
2646 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002647 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002648 ++callresult2;
2649 }
2650 PyObject_Free(callresults);
2651 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002652 if (numberresults)
2653 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002654 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002655}
2656
Walter Dörwaldd2034312007-05-18 16:29:38 +00002657PyObject *
2658PyUnicode_FromFormat(const char *format, ...)
2659{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002660 PyObject* ret;
2661 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002662
2663#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002664 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002665#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002666 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002667#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002668 ret = PyUnicode_FromFormatV(format, vargs);
2669 va_end(vargs);
2670 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002671}
2672
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002673#ifdef HAVE_WCHAR_H
2674
Victor Stinner5593d8a2010-10-02 11:11:27 +00002675/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2676 convert a Unicode object to a wide character string.
2677
Victor Stinnerd88d9832011-09-06 02:00:05 +02002678 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002679 character) required to convert the unicode object. Ignore size argument.
2680
Victor Stinnerd88d9832011-09-06 02:00:05 +02002681 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002682 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002683 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002684static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002685unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002686 wchar_t *w,
2687 Py_ssize_t size)
2688{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002689 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002690 const wchar_t *wstr;
2691
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002692 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002693 if (wstr == NULL)
2694 return -1;
2695
Victor Stinner5593d8a2010-10-02 11:11:27 +00002696 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002697 if (size > res)
2698 size = res + 1;
2699 else
2700 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002701 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002702 return res;
2703 }
2704 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002705 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002706}
2707
2708Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002709PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002710 wchar_t *w,
2711 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002712{
2713 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002714 PyErr_BadInternalCall();
2715 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002716 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002717 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002718}
2719
Victor Stinner137c34c2010-09-29 10:25:54 +00002720wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002721PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002722 Py_ssize_t *size)
2723{
2724 wchar_t* buffer;
2725 Py_ssize_t buflen;
2726
2727 if (unicode == NULL) {
2728 PyErr_BadInternalCall();
2729 return NULL;
2730 }
2731
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002732 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002733 if (buflen == -1)
2734 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002735 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002736 PyErr_NoMemory();
2737 return NULL;
2738 }
2739
Victor Stinner137c34c2010-09-29 10:25:54 +00002740 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2741 if (buffer == NULL) {
2742 PyErr_NoMemory();
2743 return NULL;
2744 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002745 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002746 if (buflen == -1)
2747 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002748 if (size != NULL)
2749 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002750 return buffer;
2751}
2752
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002753#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002754
Alexander Belopolsky40018472011-02-26 01:02:56 +00002755PyObject *
2756PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002757{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002758 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002759 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002760 PyErr_SetString(PyExc_ValueError,
2761 "chr() arg not in range(0x110000)");
2762 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002763 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002764
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002765 if (ordinal < 256)
2766 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002768 v = PyUnicode_New(1, ordinal);
2769 if (v == NULL)
2770 return NULL;
2771 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002772 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002773 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002774}
2775
Alexander Belopolsky40018472011-02-26 01:02:56 +00002776PyObject *
2777PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002778{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002779 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002780 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002781 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002782 if (PyUnicode_READY(obj))
2783 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002784 Py_INCREF(obj);
2785 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002786 }
2787 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002788 /* For a Unicode subtype that's not a Unicode object,
2789 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002790 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002791 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002792 PyErr_Format(PyExc_TypeError,
2793 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002794 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002795 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002796}
2797
Alexander Belopolsky40018472011-02-26 01:02:56 +00002798PyObject *
2799PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002800 const char *encoding,
2801 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002802{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002803 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002804 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002805
Guido van Rossumd57fd912000-03-10 22:53:23 +00002806 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002807 PyErr_BadInternalCall();
2808 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002809 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002810
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002811 /* Decoding bytes objects is the most common case and should be fast */
2812 if (PyBytes_Check(obj)) {
2813 if (PyBytes_GET_SIZE(obj) == 0) {
2814 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002815 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002816 }
2817 else {
2818 v = PyUnicode_Decode(
2819 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2820 encoding, errors);
2821 }
2822 return v;
2823 }
2824
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002825 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002826 PyErr_SetString(PyExc_TypeError,
2827 "decoding str is not supported");
2828 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002829 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002830
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002831 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2832 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2833 PyErr_Format(PyExc_TypeError,
2834 "coercing to str: need bytes, bytearray "
2835 "or buffer-like object, %.80s found",
2836 Py_TYPE(obj)->tp_name);
2837 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002838 }
Tim Petersced69f82003-09-16 20:30:58 +00002839
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002840 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002841 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002842 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002843 }
Tim Petersced69f82003-09-16 20:30:58 +00002844 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002845 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002846
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002847 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002848 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002849}
2850
Victor Stinner600d3be2010-06-10 12:00:55 +00002851/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002852 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2853 1 on success. */
2854static int
2855normalize_encoding(const char *encoding,
2856 char *lower,
2857 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002858{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002859 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002860 char *l;
2861 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002862
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002863 if (encoding == NULL) {
2864 strcpy(lower, "utf-8");
2865 return 1;
2866 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002867 e = encoding;
2868 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002869 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002870 while (*e) {
2871 if (l == l_end)
2872 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002873 if (Py_ISUPPER(*e)) {
2874 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002875 }
2876 else if (*e == '_') {
2877 *l++ = '-';
2878 e++;
2879 }
2880 else {
2881 *l++ = *e++;
2882 }
2883 }
2884 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002885 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002886}
2887
Alexander Belopolsky40018472011-02-26 01:02:56 +00002888PyObject *
2889PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002890 Py_ssize_t size,
2891 const char *encoding,
2892 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002893{
2894 PyObject *buffer = NULL, *unicode;
2895 Py_buffer info;
2896 char lower[11]; /* Enough for any encoding shortcut */
2897
Fred Drakee4315f52000-05-09 19:53:39 +00002898 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002899 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002900 if ((strcmp(lower, "utf-8") == 0) ||
2901 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002902 return PyUnicode_DecodeUTF8(s, size, errors);
2903 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002904 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002905 (strcmp(lower, "iso-8859-1") == 0))
2906 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002907#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002908 else if (strcmp(lower, "mbcs") == 0)
2909 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002910#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002911 else if (strcmp(lower, "ascii") == 0)
2912 return PyUnicode_DecodeASCII(s, size, errors);
2913 else if (strcmp(lower, "utf-16") == 0)
2914 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2915 else if (strcmp(lower, "utf-32") == 0)
2916 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2917 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002918
2919 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002920 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002921 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002922 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002923 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002924 if (buffer == NULL)
2925 goto onError;
2926 unicode = PyCodec_Decode(buffer, encoding, errors);
2927 if (unicode == NULL)
2928 goto onError;
2929 if (!PyUnicode_Check(unicode)) {
2930 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002931 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002932 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002933 Py_DECREF(unicode);
2934 goto onError;
2935 }
2936 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002937#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002938 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002939 Py_DECREF(unicode);
2940 return NULL;
2941 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002942#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002943 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002944 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002945
Benjamin Peterson29060642009-01-31 22:14:21 +00002946 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002947 Py_XDECREF(buffer);
2948 return NULL;
2949}
2950
Alexander Belopolsky40018472011-02-26 01:02:56 +00002951PyObject *
2952PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002953 const char *encoding,
2954 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002955{
2956 PyObject *v;
2957
2958 if (!PyUnicode_Check(unicode)) {
2959 PyErr_BadArgument();
2960 goto onError;
2961 }
2962
2963 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002964 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002965
2966 /* Decode via the codec registry */
2967 v = PyCodec_Decode(unicode, encoding, errors);
2968 if (v == NULL)
2969 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002970 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002971 return v;
2972
Benjamin Peterson29060642009-01-31 22:14:21 +00002973 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002974 return NULL;
2975}
2976
Alexander Belopolsky40018472011-02-26 01:02:56 +00002977PyObject *
2978PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002979 const char *encoding,
2980 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002981{
2982 PyObject *v;
2983
2984 if (!PyUnicode_Check(unicode)) {
2985 PyErr_BadArgument();
2986 goto onError;
2987 }
2988
2989 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002990 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002991
2992 /* Decode via the codec registry */
2993 v = PyCodec_Decode(unicode, encoding, errors);
2994 if (v == NULL)
2995 goto onError;
2996 if (!PyUnicode_Check(v)) {
2997 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002998 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002999 Py_TYPE(v)->tp_name);
3000 Py_DECREF(v);
3001 goto onError;
3002 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003003 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003004 return v;
3005
Benjamin Peterson29060642009-01-31 22:14:21 +00003006 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003007 return NULL;
3008}
3009
Alexander Belopolsky40018472011-02-26 01:02:56 +00003010PyObject *
3011PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003012 Py_ssize_t size,
3013 const char *encoding,
3014 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003015{
3016 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003017
Guido van Rossumd57fd912000-03-10 22:53:23 +00003018 unicode = PyUnicode_FromUnicode(s, size);
3019 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003020 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003021 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3022 Py_DECREF(unicode);
3023 return v;
3024}
3025
Alexander Belopolsky40018472011-02-26 01:02:56 +00003026PyObject *
3027PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003028 const char *encoding,
3029 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003030{
3031 PyObject *v;
3032
3033 if (!PyUnicode_Check(unicode)) {
3034 PyErr_BadArgument();
3035 goto onError;
3036 }
3037
3038 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003039 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003040
3041 /* Encode via the codec registry */
3042 v = PyCodec_Encode(unicode, encoding, errors);
3043 if (v == NULL)
3044 goto onError;
3045 return v;
3046
Benjamin Peterson29060642009-01-31 22:14:21 +00003047 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003048 return NULL;
3049}
3050
Victor Stinnerad158722010-10-27 00:25:46 +00003051PyObject *
3052PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003053{
Victor Stinner99b95382011-07-04 14:23:54 +02003054#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003055 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3056 PyUnicode_GET_SIZE(unicode),
3057 NULL);
3058#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003059 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003060#else
Victor Stinner793b5312011-04-27 00:24:21 +02003061 PyInterpreterState *interp = PyThreadState_GET()->interp;
3062 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3063 cannot use it to encode and decode filenames before it is loaded. Load
3064 the Python codec requires to encode at least its own filename. Use the C
3065 version of the locale codec until the codec registry is initialized and
3066 the Python codec is loaded.
3067
3068 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3069 cannot only rely on it: check also interp->fscodec_initialized for
3070 subinterpreters. */
3071 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003072 return PyUnicode_AsEncodedString(unicode,
3073 Py_FileSystemDefaultEncoding,
3074 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003075 }
3076 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003077 /* locale encoding with surrogateescape */
3078 wchar_t *wchar;
3079 char *bytes;
3080 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003081 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003082
3083 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3084 if (wchar == NULL)
3085 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003086 bytes = _Py_wchar2char(wchar, &error_pos);
3087 if (bytes == NULL) {
3088 if (error_pos != (size_t)-1) {
3089 char *errmsg = strerror(errno);
3090 PyObject *exc = NULL;
3091 if (errmsg == NULL)
3092 errmsg = "Py_wchar2char() failed";
3093 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003094 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003095 error_pos, error_pos+1,
3096 errmsg);
3097 Py_XDECREF(exc);
3098 }
3099 else
3100 PyErr_NoMemory();
3101 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003102 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003103 }
3104 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003105
3106 bytes_obj = PyBytes_FromString(bytes);
3107 PyMem_Free(bytes);
3108 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003109 }
Victor Stinnerad158722010-10-27 00:25:46 +00003110#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003111}
3112
Alexander Belopolsky40018472011-02-26 01:02:56 +00003113PyObject *
3114PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003115 const char *encoding,
3116 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003117{
3118 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003119 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003120
Guido van Rossumd57fd912000-03-10 22:53:23 +00003121 if (!PyUnicode_Check(unicode)) {
3122 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003123 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003124 }
Fred Drakee4315f52000-05-09 19:53:39 +00003125
Fred Drakee4315f52000-05-09 19:53:39 +00003126 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003127 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003128 if ((strcmp(lower, "utf-8") == 0) ||
3129 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003130 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003131 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003132 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003133 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003134 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003135 }
Victor Stinner37296e82010-06-10 13:36:23 +00003136 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003137 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003138 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003139 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003140#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003141 else if (strcmp(lower, "mbcs") == 0)
3142 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3143 PyUnicode_GET_SIZE(unicode),
3144 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003145#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003146 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003147 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003148 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003149
3150 /* Encode via the codec registry */
3151 v = PyCodec_Encode(unicode, encoding, errors);
3152 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003153 return NULL;
3154
3155 /* The normal path */
3156 if (PyBytes_Check(v))
3157 return v;
3158
3159 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003160 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003161 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003162 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003163
3164 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3165 "encoder %s returned bytearray instead of bytes",
3166 encoding);
3167 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003168 Py_DECREF(v);
3169 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003170 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003171
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003172 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3173 Py_DECREF(v);
3174 return b;
3175 }
3176
3177 PyErr_Format(PyExc_TypeError,
3178 "encoder did not return a bytes object (type=%.400s)",
3179 Py_TYPE(v)->tp_name);
3180 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003181 return NULL;
3182}
3183
Alexander Belopolsky40018472011-02-26 01:02:56 +00003184PyObject *
3185PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003186 const char *encoding,
3187 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003188{
3189 PyObject *v;
3190
3191 if (!PyUnicode_Check(unicode)) {
3192 PyErr_BadArgument();
3193 goto onError;
3194 }
3195
3196 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003197 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003198
3199 /* Encode via the codec registry */
3200 v = PyCodec_Encode(unicode, encoding, errors);
3201 if (v == NULL)
3202 goto onError;
3203 if (!PyUnicode_Check(v)) {
3204 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003205 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003206 Py_TYPE(v)->tp_name);
3207 Py_DECREF(v);
3208 goto onError;
3209 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003210 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003211
Benjamin Peterson29060642009-01-31 22:14:21 +00003212 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003213 return NULL;
3214}
3215
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003216PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003217PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003218 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003219 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3220}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003221
Christian Heimes5894ba72007-11-04 11:43:14 +00003222PyObject*
3223PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3224{
Victor Stinner99b95382011-07-04 14:23:54 +02003225#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003226 return PyUnicode_DecodeMBCS(s, size, NULL);
3227#elif defined(__APPLE__)
3228 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3229#else
Victor Stinner793b5312011-04-27 00:24:21 +02003230 PyInterpreterState *interp = PyThreadState_GET()->interp;
3231 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3232 cannot use it to encode and decode filenames before it is loaded. Load
3233 the Python codec requires to encode at least its own filename. Use the C
3234 version of the locale codec until the codec registry is initialized and
3235 the Python codec is loaded.
3236
3237 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3238 cannot only rely on it: check also interp->fscodec_initialized for
3239 subinterpreters. */
3240 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003241 return PyUnicode_Decode(s, size,
3242 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003243 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003244 }
3245 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003246 /* locale encoding with surrogateescape */
3247 wchar_t *wchar;
3248 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003249 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003250
3251 if (s[size] != '\0' || size != strlen(s)) {
3252 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3253 return NULL;
3254 }
3255
Victor Stinner168e1172010-10-16 23:16:16 +00003256 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003257 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003258 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003259
Victor Stinner168e1172010-10-16 23:16:16 +00003260 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003261 PyMem_Free(wchar);
3262 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003263 }
Victor Stinnerad158722010-10-27 00:25:46 +00003264#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003265}
3266
Martin v. Löwis011e8422009-05-05 04:43:17 +00003267
3268int
3269PyUnicode_FSConverter(PyObject* arg, void* addr)
3270{
3271 PyObject *output = NULL;
3272 Py_ssize_t size;
3273 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003274 if (arg == NULL) {
3275 Py_DECREF(*(PyObject**)addr);
3276 return 1;
3277 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003278 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003279 output = arg;
3280 Py_INCREF(output);
3281 }
3282 else {
3283 arg = PyUnicode_FromObject(arg);
3284 if (!arg)
3285 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003286 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003287 Py_DECREF(arg);
3288 if (!output)
3289 return 0;
3290 if (!PyBytes_Check(output)) {
3291 Py_DECREF(output);
3292 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3293 return 0;
3294 }
3295 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003296 size = PyBytes_GET_SIZE(output);
3297 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003298 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003299 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003300 Py_DECREF(output);
3301 return 0;
3302 }
3303 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003304 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003305}
3306
3307
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003308int
3309PyUnicode_FSDecoder(PyObject* arg, void* addr)
3310{
3311 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003312 if (arg == NULL) {
3313 Py_DECREF(*(PyObject**)addr);
3314 return 1;
3315 }
3316 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003317 if (PyUnicode_READY(arg))
3318 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003319 output = arg;
3320 Py_INCREF(output);
3321 }
3322 else {
3323 arg = PyBytes_FromObject(arg);
3324 if (!arg)
3325 return 0;
3326 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3327 PyBytes_GET_SIZE(arg));
3328 Py_DECREF(arg);
3329 if (!output)
3330 return 0;
3331 if (!PyUnicode_Check(output)) {
3332 Py_DECREF(output);
3333 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3334 return 0;
3335 }
3336 }
Victor Stinner065836e2011-10-27 01:56:33 +02003337 if (PyUnicode_READY(output) < 0) {
3338 Py_DECREF(output);
3339 return 0;
3340 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003341 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003342 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003343 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3344 Py_DECREF(output);
3345 return 0;
3346 }
3347 *(PyObject**)addr = output;
3348 return Py_CLEANUP_SUPPORTED;
3349}
3350
3351
Martin v. Löwis5b222132007-06-10 09:51:05 +00003352char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003353PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003354{
Christian Heimesf3863112007-11-22 07:46:41 +00003355 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003356
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003357 if (!PyUnicode_Check(unicode)) {
3358 PyErr_BadArgument();
3359 return NULL;
3360 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003361 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003362 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003363
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003364 if (PyUnicode_UTF8(unicode) == NULL) {
3365 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003366 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3367 if (bytes == NULL)
3368 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003369 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3370 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003371 Py_DECREF(bytes);
3372 return NULL;
3373 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003374 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3375 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3376 PyBytes_AS_STRING(bytes),
3377 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003378 Py_DECREF(bytes);
3379 }
3380
3381 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003382 *psize = PyUnicode_UTF8_LENGTH(unicode);
3383 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003384}
3385
3386char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003387PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003388{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003389 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3390}
3391
3392#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003393static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003394#endif
3395
3396
3397Py_UNICODE *
3398PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3399{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003400 const unsigned char *one_byte;
3401#if SIZEOF_WCHAR_T == 4
3402 const Py_UCS2 *two_bytes;
3403#else
3404 const Py_UCS4 *four_bytes;
3405 const Py_UCS4 *ucs4_end;
3406 Py_ssize_t num_surrogates;
3407#endif
3408 wchar_t *w;
3409 wchar_t *wchar_end;
3410
3411 if (!PyUnicode_Check(unicode)) {
3412 PyErr_BadArgument();
3413 return NULL;
3414 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003415 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003416 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003417 assert(_PyUnicode_KIND(unicode) != 0);
3418 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003419
3420#ifdef Py_DEBUG
3421 ++unicode_as_unicode_calls;
3422#endif
3423
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003424 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003425#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003426 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3427 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003428 num_surrogates = 0;
3429
3430 for (; four_bytes < ucs4_end; ++four_bytes) {
3431 if (*four_bytes > 0xFFFF)
3432 ++num_surrogates;
3433 }
3434
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003435 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3436 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3437 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003438 PyErr_NoMemory();
3439 return NULL;
3440 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003441 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003442
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003443 w = _PyUnicode_WSTR(unicode);
3444 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3445 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003446 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3447 if (*four_bytes > 0xFFFF) {
3448 /* encode surrogate pair in this case */
3449 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3450 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3451 }
3452 else
3453 *w = *four_bytes;
3454
3455 if (w > wchar_end) {
3456 assert(0 && "Miscalculated string end");
3457 }
3458 }
3459 *w = 0;
3460#else
3461 /* sizeof(wchar_t) == 4 */
3462 Py_FatalError("Impossible unicode object state, wstr and str "
3463 "should share memory already.");
3464 return NULL;
3465#endif
3466 }
3467 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003468 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3469 (_PyUnicode_LENGTH(unicode) + 1));
3470 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003471 PyErr_NoMemory();
3472 return NULL;
3473 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003474 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3475 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3476 w = _PyUnicode_WSTR(unicode);
3477 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003478
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003479 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3480 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003481 for (; w < wchar_end; ++one_byte, ++w)
3482 *w = *one_byte;
3483 /* null-terminate the wstr */
3484 *w = 0;
3485 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003486 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003487#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003488 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003489 for (; w < wchar_end; ++two_bytes, ++w)
3490 *w = *two_bytes;
3491 /* null-terminate the wstr */
3492 *w = 0;
3493#else
3494 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003495 PyObject_FREE(_PyUnicode_WSTR(unicode));
3496 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003497 Py_FatalError("Impossible unicode object state, wstr "
3498 "and str should share memory already.");
3499 return NULL;
3500#endif
3501 }
3502 else {
3503 assert(0 && "This should never happen.");
3504 }
3505 }
3506 }
3507 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003508 *size = PyUnicode_WSTR_LENGTH(unicode);
3509 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003510}
3511
Alexander Belopolsky40018472011-02-26 01:02:56 +00003512Py_UNICODE *
3513PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003514{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003515 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003516}
3517
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003518
Alexander Belopolsky40018472011-02-26 01:02:56 +00003519Py_ssize_t
3520PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003521{
3522 if (!PyUnicode_Check(unicode)) {
3523 PyErr_BadArgument();
3524 goto onError;
3525 }
3526 return PyUnicode_GET_SIZE(unicode);
3527
Benjamin Peterson29060642009-01-31 22:14:21 +00003528 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003529 return -1;
3530}
3531
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003532Py_ssize_t
3533PyUnicode_GetLength(PyObject *unicode)
3534{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003535 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003536 PyErr_BadArgument();
3537 return -1;
3538 }
3539
3540 return PyUnicode_GET_LENGTH(unicode);
3541}
3542
3543Py_UCS4
3544PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3545{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003546 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3547 PyErr_BadArgument();
3548 return (Py_UCS4)-1;
3549 }
3550 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3551 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003552 return (Py_UCS4)-1;
3553 }
3554 return PyUnicode_READ_CHAR(unicode, index);
3555}
3556
3557int
3558PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3559{
3560 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003561 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003562 return -1;
3563 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003564 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3565 PyErr_SetString(PyExc_IndexError, "string index out of range");
3566 return -1;
3567 }
3568 if (_PyUnicode_Dirty(unicode))
3569 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003570 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3571 index, ch);
3572 return 0;
3573}
3574
Alexander Belopolsky40018472011-02-26 01:02:56 +00003575const char *
3576PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003577{
Victor Stinner42cb4622010-09-01 19:39:01 +00003578 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003579}
3580
Victor Stinner554f3f02010-06-16 23:33:54 +00003581/* create or adjust a UnicodeDecodeError */
3582static void
3583make_decode_exception(PyObject **exceptionObject,
3584 const char *encoding,
3585 const char *input, Py_ssize_t length,
3586 Py_ssize_t startpos, Py_ssize_t endpos,
3587 const char *reason)
3588{
3589 if (*exceptionObject == NULL) {
3590 *exceptionObject = PyUnicodeDecodeError_Create(
3591 encoding, input, length, startpos, endpos, reason);
3592 }
3593 else {
3594 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3595 goto onError;
3596 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3597 goto onError;
3598 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3599 goto onError;
3600 }
3601 return;
3602
3603onError:
3604 Py_DECREF(*exceptionObject);
3605 *exceptionObject = NULL;
3606}
3607
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003608/* error handling callback helper:
3609 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003610 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003611 and adjust various state variables.
3612 return 0 on success, -1 on error
3613*/
3614
Alexander Belopolsky40018472011-02-26 01:02:56 +00003615static int
3616unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003617 const char *encoding, const char *reason,
3618 const char **input, const char **inend, Py_ssize_t *startinpos,
3619 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003620 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003621{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003622 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003623
3624 PyObject *restuple = NULL;
3625 PyObject *repunicode = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003626 Py_ssize_t outsize = PyUnicode_GET_LENGTH(*output);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003627 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003628 Py_ssize_t requiredsize;
3629 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003630 PyObject *inputobj = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003631 Py_ssize_t replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003632 int res = -1;
3633
3634 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003635 *errorHandler = PyCodec_LookupError(errors);
3636 if (*errorHandler == NULL)
3637 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003638 }
3639
Victor Stinner554f3f02010-06-16 23:33:54 +00003640 make_decode_exception(exceptionObject,
3641 encoding,
3642 *input, *inend - *input,
3643 *startinpos, *endinpos,
3644 reason);
3645 if (*exceptionObject == NULL)
3646 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003647
3648 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3649 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003650 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003651 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003652 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003654 }
3655 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003656 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003657 if (PyUnicode_READY(repunicode) < 0)
3658 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003659
3660 /* Copy back the bytes variables, which might have been modified by the
3661 callback */
3662 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3663 if (!inputobj)
3664 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003665 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003666 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003667 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003668 *input = PyBytes_AS_STRING(inputobj);
3669 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003670 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003671 /* we can DECREF safely, as the exception has another reference,
3672 so the object won't go away. */
3673 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003674
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003675 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003676 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003677 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003678 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3679 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003680 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003681
3682 /* need more space? (at least enough for what we
3683 have+the replacement+the rest of the string (starting
3684 at the new input position), so we won't have to check space
3685 when there are no errors in the rest of the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003686 replen = PyUnicode_GET_LENGTH(repunicode);
3687 requiredsize = *outpos + replen + insize-newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003688 if (requiredsize > outsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003689 if (requiredsize<2*outsize)
3690 requiredsize = 2*outsize;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003691 if (unicode_resize(output, requiredsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003692 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003693 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003694 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
3695 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003696 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003697 *inptr = *input + newpos;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003698 PyUnicode_CopyCharacters(*output, *outpos, repunicode, 0, replen);
3699 *outpos += replen;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003700
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003701 /* we made it! */
3702 res = 0;
3703
Benjamin Peterson29060642009-01-31 22:14:21 +00003704 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003705 Py_XDECREF(restuple);
3706 return res;
3707}
3708
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003709/* --- UTF-7 Codec -------------------------------------------------------- */
3710
Antoine Pitrou244651a2009-05-04 18:56:13 +00003711/* See RFC2152 for details. We encode conservatively and decode liberally. */
3712
3713/* Three simple macros defining base-64. */
3714
3715/* Is c a base-64 character? */
3716
3717#define IS_BASE64(c) \
3718 (((c) >= 'A' && (c) <= 'Z') || \
3719 ((c) >= 'a' && (c) <= 'z') || \
3720 ((c) >= '0' && (c) <= '9') || \
3721 (c) == '+' || (c) == '/')
3722
3723/* given that c is a base-64 character, what is its base-64 value? */
3724
3725#define FROM_BASE64(c) \
3726 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3727 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3728 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3729 (c) == '+' ? 62 : 63)
3730
3731/* What is the base-64 character of the bottom 6 bits of n? */
3732
3733#define TO_BASE64(n) \
3734 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3735
3736/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3737 * decoded as itself. We are permissive on decoding; the only ASCII
3738 * byte not decoding to itself is the + which begins a base64
3739 * string. */
3740
3741#define DECODE_DIRECT(c) \
3742 ((c) <= 127 && (c) != '+')
3743
3744/* The UTF-7 encoder treats ASCII characters differently according to
3745 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3746 * the above). See RFC2152. This array identifies these different
3747 * sets:
3748 * 0 : "Set D"
3749 * alphanumeric and '(),-./:?
3750 * 1 : "Set O"
3751 * !"#$%&*;<=>@[]^_`{|}
3752 * 2 : "whitespace"
3753 * ht nl cr sp
3754 * 3 : special (must be base64 encoded)
3755 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3756 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003757
Tim Petersced69f82003-09-16 20:30:58 +00003758static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003759char utf7_category[128] = {
3760/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3761 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3762/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3763 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3764/* sp ! " # $ % & ' ( ) * + , - . / */
3765 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3766/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3767 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3768/* @ A B C D E F G H I J K L M N O */
3769 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3770/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3771 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3772/* ` a b c d e f g h i j k l m n o */
3773 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3774/* p q r s t u v w x y z { | } ~ del */
3775 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003776};
3777
Antoine Pitrou244651a2009-05-04 18:56:13 +00003778/* ENCODE_DIRECT: this character should be encoded as itself. The
3779 * answer depends on whether we are encoding set O as itself, and also
3780 * on whether we are encoding whitespace as itself. RFC2152 makes it
3781 * clear that the answers to these questions vary between
3782 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003783
Antoine Pitrou244651a2009-05-04 18:56:13 +00003784#define ENCODE_DIRECT(c, directO, directWS) \
3785 ((c) < 128 && (c) > 0 && \
3786 ((utf7_category[(c)] == 0) || \
3787 (directWS && (utf7_category[(c)] == 2)) || \
3788 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003789
Alexander Belopolsky40018472011-02-26 01:02:56 +00003790PyObject *
3791PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003792 Py_ssize_t size,
3793 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003794{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003795 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3796}
3797
Antoine Pitrou244651a2009-05-04 18:56:13 +00003798/* The decoder. The only state we preserve is our read position,
3799 * i.e. how many characters we have consumed. So if we end in the
3800 * middle of a shift sequence we have to back off the read position
3801 * and the output to the beginning of the sequence, otherwise we lose
3802 * all the shift state (seen bits, number of bits seen, high
3803 * surrogate). */
3804
Alexander Belopolsky40018472011-02-26 01:02:56 +00003805PyObject *
3806PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003807 Py_ssize_t size,
3808 const char *errors,
3809 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003810{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003811 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003812 Py_ssize_t startinpos;
3813 Py_ssize_t endinpos;
3814 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003815 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003816 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003817 const char *errmsg = "";
3818 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003819 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003820 unsigned int base64bits = 0;
3821 unsigned long base64buffer = 0;
3822 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003823 PyObject *errorHandler = NULL;
3824 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003825
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003826 /* Start off assuming it's all ASCII. Widen later as necessary. */
3827 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003828 if (!unicode)
3829 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003830 if (size == 0) {
3831 if (consumed)
3832 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003833 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003834 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003835
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003836 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003837 e = s + size;
3838
3839 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003840 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003841 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003842 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003843
Antoine Pitrou244651a2009-05-04 18:56:13 +00003844 if (inShift) { /* in a base-64 section */
3845 if (IS_BASE64(ch)) { /* consume a base-64 character */
3846 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3847 base64bits += 6;
3848 s++;
3849 if (base64bits >= 16) {
3850 /* we have enough bits for a UTF-16 value */
3851 Py_UNICODE outCh = (Py_UNICODE)
3852 (base64buffer >> (base64bits-16));
3853 base64bits -= 16;
3854 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3855 if (surrogate) {
3856 /* expecting a second surrogate */
3857 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003858 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3859 | (outCh & 0x3FF)) + 0x10000;
3860 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3861 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003862 surrogate = 0;
3863 }
3864 else {
3865 surrogate = 0;
3866 errmsg = "second surrogate missing";
3867 goto utf7Error;
3868 }
3869 }
3870 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3871 /* first surrogate */
3872 surrogate = outCh;
3873 }
3874 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3875 errmsg = "unexpected second surrogate";
3876 goto utf7Error;
3877 }
3878 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003879 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3880 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003881 }
3882 }
3883 }
3884 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003885 inShift = 0;
3886 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003887 if (surrogate) {
3888 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003889 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003890 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003891 if (base64bits > 0) { /* left-over bits */
3892 if (base64bits >= 6) {
3893 /* We've seen at least one base-64 character */
3894 errmsg = "partial character in shift sequence";
3895 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003896 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003897 else {
3898 /* Some bits remain; they should be zero */
3899 if (base64buffer != 0) {
3900 errmsg = "non-zero padding bits in shift sequence";
3901 goto utf7Error;
3902 }
3903 }
3904 }
3905 if (ch != '-') {
3906 /* '-' is absorbed; other terminating
3907 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003908 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3909 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003910 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003911 }
3912 }
3913 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003914 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003915 s++; /* consume '+' */
3916 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003917 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003918 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3919 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003920 }
3921 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003922 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003923 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003924 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003925 }
3926 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003927 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003928 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3929 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003930 s++;
3931 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003932 else {
3933 startinpos = s-starts;
3934 s++;
3935 errmsg = "unexpected special character";
3936 goto utf7Error;
3937 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003938 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003939utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003940 endinpos = s-starts;
3941 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003942 errors, &errorHandler,
3943 "utf7", errmsg,
3944 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003945 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003946 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003947 }
3948
Antoine Pitrou244651a2009-05-04 18:56:13 +00003949 /* end of string */
3950
3951 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3952 /* if we're in an inconsistent state, that's an error */
3953 if (surrogate ||
3954 (base64bits >= 6) ||
3955 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003956 endinpos = size;
3957 if (unicode_decode_call_errorhandler(
3958 errors, &errorHandler,
3959 "utf7", "unterminated shift sequence",
3960 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003961 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003962 goto onError;
3963 if (s < e)
3964 goto restart;
3965 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003966 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003967
3968 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003969 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003970 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003971 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003972 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003973 }
3974 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003975 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003976 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003977 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003978
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003979 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003980 goto onError;
3981
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003982 Py_XDECREF(errorHandler);
3983 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02003984#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02003985 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003986 Py_DECREF(unicode);
3987 return NULL;
3988 }
Victor Stinner17efeed2011-10-04 20:05:46 +02003989#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003990 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01003991 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003992
Benjamin Peterson29060642009-01-31 22:14:21 +00003993 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003994 Py_XDECREF(errorHandler);
3995 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003996 Py_DECREF(unicode);
3997 return NULL;
3998}
3999
4000
Alexander Belopolsky40018472011-02-26 01:02:56 +00004001PyObject *
4002PyUnicode_EncodeUTF7(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004003 Py_ssize_t size,
4004 int base64SetO,
4005 int base64WhiteSpace,
4006 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004007{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004008 PyObject *v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004009 /* It might be possible to tighten this worst case */
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00004010 Py_ssize_t allocated = 8 * size;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004011 int inShift = 0;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004012 Py_ssize_t i = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004013 unsigned int base64bits = 0;
4014 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004015 char * out;
4016 char * start;
4017
4018 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004019 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004020
Alexandre Vassalottie85bd982009-07-21 00:39:03 +00004021 if (allocated / 8 != size)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004022 return PyErr_NoMemory();
4023
Antoine Pitrou244651a2009-05-04 18:56:13 +00004024 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004025 if (v == NULL)
4026 return NULL;
4027
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004028 start = out = PyBytes_AS_STRING(v);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004029 for (;i < size; ++i) {
4030 Py_UNICODE ch = s[i];
4031
Antoine Pitrou244651a2009-05-04 18:56:13 +00004032 if (inShift) {
4033 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4034 /* shifting out */
4035 if (base64bits) { /* output remaining bits */
4036 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4037 base64buffer = 0;
4038 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004039 }
4040 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004041 /* Characters not in the BASE64 set implicitly unshift the sequence
4042 so no '-' is required, except if the character is itself a '-' */
4043 if (IS_BASE64(ch) || ch == '-') {
4044 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004045 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004046 *out++ = (char) ch;
4047 }
4048 else {
4049 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004050 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004051 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004052 else { /* not in a shift sequence */
4053 if (ch == '+') {
4054 *out++ = '+';
4055 *out++ = '-';
4056 }
4057 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4058 *out++ = (char) ch;
4059 }
4060 else {
4061 *out++ = '+';
4062 inShift = 1;
4063 goto encode_char;
4064 }
4065 }
4066 continue;
4067encode_char:
4068#ifdef Py_UNICODE_WIDE
4069 if (ch >= 0x10000) {
4070 /* code first surrogate */
4071 base64bits += 16;
4072 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4073 while (base64bits >= 6) {
4074 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4075 base64bits -= 6;
4076 }
4077 /* prepare second surrogate */
4078 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4079 }
4080#endif
4081 base64bits += 16;
4082 base64buffer = (base64buffer << 16) | ch;
4083 while (base64bits >= 6) {
4084 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4085 base64bits -= 6;
4086 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004087 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004088 if (base64bits)
4089 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4090 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004091 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004092 if (_PyBytes_Resize(&v, out - start) < 0)
4093 return NULL;
4094 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004095}
4096
Antoine Pitrou244651a2009-05-04 18:56:13 +00004097#undef IS_BASE64
4098#undef FROM_BASE64
4099#undef TO_BASE64
4100#undef DECODE_DIRECT
4101#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004102
Guido van Rossumd57fd912000-03-10 22:53:23 +00004103/* --- UTF-8 Codec -------------------------------------------------------- */
4104
Tim Petersced69f82003-09-16 20:30:58 +00004105static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004106char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004107 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4108 illegal prefix. See RFC 3629 for details */
4109 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4110 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004111 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004112 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4113 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4114 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4115 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004116 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4117 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 +00004118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004120 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4121 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4122 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4123 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4124 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 +00004125};
4126
Alexander Belopolsky40018472011-02-26 01:02:56 +00004127PyObject *
4128PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004129 Py_ssize_t size,
4130 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004131{
Walter Dörwald69652032004-09-07 20:24:22 +00004132 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4133}
4134
Antoine Pitrouab868312009-01-10 15:40:25 +00004135/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4136#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4137
4138/* Mask to quickly check whether a C 'long' contains a
4139 non-ASCII, UTF8-encoded char. */
4140#if (SIZEOF_LONG == 8)
4141# define ASCII_CHAR_MASK 0x8080808080808080L
4142#elif (SIZEOF_LONG == 4)
4143# define ASCII_CHAR_MASK 0x80808080L
4144#else
4145# error C 'long' size should be either 4 or 8!
4146#endif
4147
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004148/* Scans a UTF-8 string and returns the maximum character to be expected,
4149 the size of the decoded unicode string and if any major errors were
4150 encountered.
4151
4152 This function does check basic UTF-8 sanity, it does however NOT CHECK
4153 if the string contains surrogates, and if all continuation bytes are
4154 within the correct ranges, these checks are performed in
4155 PyUnicode_DecodeUTF8Stateful.
4156
4157 If it sets has_errors to 1, it means the value of unicode_size and max_char
4158 will be bogus and you should not rely on useful information in them.
4159 */
4160static Py_UCS4
4161utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4162 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4163 int *has_errors)
4164{
4165 Py_ssize_t n;
4166 Py_ssize_t char_count = 0;
4167 Py_UCS4 max_char = 127, new_max;
4168 Py_UCS4 upper_bound;
4169 const unsigned char *p = (const unsigned char *)s;
4170 const unsigned char *end = p + string_size;
4171 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4172 int err = 0;
4173
4174 for (; p < end && !err; ++p, ++char_count) {
4175 /* Only check value if it's not a ASCII char... */
4176 if (*p < 0x80) {
4177 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4178 an explanation. */
4179 if (!((size_t) p & LONG_PTR_MASK)) {
4180 /* Help register allocation */
4181 register const unsigned char *_p = p;
4182 while (_p < aligned_end) {
4183 unsigned long value = *(unsigned long *) _p;
4184 if (value & ASCII_CHAR_MASK)
4185 break;
4186 _p += SIZEOF_LONG;
4187 char_count += SIZEOF_LONG;
4188 }
4189 p = _p;
4190 if (p == end)
4191 break;
4192 }
4193 }
4194 if (*p >= 0x80) {
4195 n = utf8_code_length[*p];
4196 new_max = max_char;
4197 switch (n) {
4198 /* invalid start byte */
4199 case 0:
4200 err = 1;
4201 break;
4202 case 2:
4203 /* Code points between 0x00FF and 0x07FF inclusive.
4204 Approximate the upper bound of the code point,
4205 if this flips over 255 we can be sure it will be more
4206 than 255 and the string will need 2 bytes per code coint,
4207 if it stays under or equal to 255, we can be sure 1 byte
4208 is enough.
4209 ((*p & 0b00011111) << 6) | 0b00111111 */
4210 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4211 if (max_char < upper_bound)
4212 new_max = upper_bound;
4213 /* Ensure we track at least that we left ASCII space. */
4214 if (new_max < 128)
4215 new_max = 128;
4216 break;
4217 case 3:
4218 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4219 always > 255 and <= 65535 and will always need 2 bytes. */
4220 if (max_char < 65535)
4221 new_max = 65535;
4222 break;
4223 case 4:
4224 /* Code point will be above 0xFFFF for sure in this case. */
4225 new_max = 65537;
4226 break;
4227 /* Internal error, this should be caught by the first if */
4228 case 1:
4229 default:
4230 assert(0 && "Impossible case in utf8_max_char_and_size");
4231 err = 1;
4232 }
4233 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004234 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004235 --n;
4236 /* Check if the follow up chars are all valid continuation bytes */
4237 if (n >= 1) {
4238 const unsigned char *cont;
4239 if ((p + n) >= end) {
4240 if (consumed == 0)
4241 /* incomplete data, non-incremental decoding */
4242 err = 1;
4243 break;
4244 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004245 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004246 if ((*cont & 0xc0) != 0x80) {
4247 err = 1;
4248 break;
4249 }
4250 }
4251 p += n;
4252 }
4253 else
4254 err = 1;
4255 max_char = new_max;
4256 }
4257 }
4258
4259 if (unicode_size)
4260 *unicode_size = char_count;
4261 if (has_errors)
4262 *has_errors = err;
4263 return max_char;
4264}
4265
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004266/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4267 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4268 onError. Potential resizing overallocates, so the result needs to shrink
4269 at the end.
4270*/
4271#define WRITE_MAYBE_FAIL(index, value) \
4272 do { \
4273 if (has_errors) { \
4274 Py_ssize_t pos = index; \
4275 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4276 unicode_resize(&unicode, pos + pos/8) < 0) \
4277 goto onError; \
4278 if (unicode_putchar(&unicode, &pos, value) < 0) \
4279 goto onError; \
4280 } \
4281 else \
4282 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004283 } while (0)
4284
Alexander Belopolsky40018472011-02-26 01:02:56 +00004285PyObject *
4286PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004287 Py_ssize_t size,
4288 const char *errors,
4289 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004290{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004291 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004292 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004293 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004294 Py_ssize_t startinpos;
4295 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004296 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004297 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004298 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004299 PyObject *errorHandler = NULL;
4300 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004301 Py_UCS4 maxchar = 0;
4302 Py_ssize_t unicode_size;
4303 Py_ssize_t i;
4304 int kind;
4305 void *data;
4306 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004307
Walter Dörwald69652032004-09-07 20:24:22 +00004308 if (size == 0) {
4309 if (consumed)
4310 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004311 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004312 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004313 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4314 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004315 if (has_errors)
4316 /* maxchar and size computation might be incorrect;
4317 code below widens and resizes as necessary. */
4318 unicode = PyUnicode_New(size, 127);
4319 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004320 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004321 if (!unicode)
4322 return NULL;
4323 /* When the string is ASCII only, just use memcpy and return.
4324 unicode_size may be != size if there is an incomplete UTF-8
4325 sequence at the end of the ASCII block. */
4326 if (!has_errors && maxchar < 128 && size == unicode_size) {
4327 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4328 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004329 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004330 kind = PyUnicode_KIND(unicode);
4331 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004332 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004333 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004334 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004335 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004336
4337 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004338 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004339
4340 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004341 /* Fast path for runs of ASCII characters. Given that common UTF-8
4342 input will consist of an overwhelming majority of ASCII
4343 characters, we try to optimize for this case by checking
4344 as many characters as a C 'long' can contain.
4345 First, check if we can do an aligned read, as most CPUs have
4346 a penalty for unaligned reads.
4347 */
4348 if (!((size_t) s & LONG_PTR_MASK)) {
4349 /* Help register allocation */
4350 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004351 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004352 while (_s < aligned_end) {
4353 /* Read a whole long at a time (either 4 or 8 bytes),
4354 and do a fast unrolled copy if it only contains ASCII
4355 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004356 unsigned long value = *(unsigned long *) _s;
4357 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004358 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004359 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4360 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4361 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4362 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004363#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004364 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4365 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4366 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4367 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004368#endif
4369 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004370 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004371 }
4372 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004373 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004374 if (s == e)
4375 break;
4376 ch = (unsigned char)*s;
4377 }
4378 }
4379
4380 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004381 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004382 s++;
4383 continue;
4384 }
4385
4386 n = utf8_code_length[ch];
4387
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004388 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004389 if (consumed)
4390 break;
4391 else {
4392 errmsg = "unexpected end of data";
4393 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004394 endinpos = startinpos+1;
4395 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4396 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004397 goto utf8Error;
4398 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004399 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004400
4401 switch (n) {
4402
4403 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004404 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004405 startinpos = s-starts;
4406 endinpos = startinpos+1;
4407 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004408
4409 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004410 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004411 startinpos = s-starts;
4412 endinpos = startinpos+1;
4413 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004414
4415 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004416 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004417 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004418 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004419 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004420 goto utf8Error;
4421 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004422 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004423 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004424 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004425 break;
4426
4427 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004428 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4429 will result in surrogates in range d800-dfff. Surrogates are
4430 not valid UTF-8 so they are rejected.
4431 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4432 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004433 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004434 (s[2] & 0xc0) != 0x80 ||
4435 ((unsigned char)s[0] == 0xE0 &&
4436 (unsigned char)s[1] < 0xA0) ||
4437 ((unsigned char)s[0] == 0xED &&
4438 (unsigned char)s[1] > 0x9F)) {
4439 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004440 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004441 endinpos = startinpos + 1;
4442
4443 /* if s[1] first two bits are 1 and 0, then the invalid
4444 continuation byte is s[2], so increment endinpos by 1,
4445 if not, s[1] is invalid and endinpos doesn't need to
4446 be incremented. */
4447 if ((s[1] & 0xC0) == 0x80)
4448 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004449 goto utf8Error;
4450 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004451 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004452 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004453 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004454 break;
4455
4456 case 4:
4457 if ((s[1] & 0xc0) != 0x80 ||
4458 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004459 (s[3] & 0xc0) != 0x80 ||
4460 ((unsigned char)s[0] == 0xF0 &&
4461 (unsigned char)s[1] < 0x90) ||
4462 ((unsigned char)s[0] == 0xF4 &&
4463 (unsigned char)s[1] > 0x8F)) {
4464 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004465 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004466 endinpos = startinpos + 1;
4467 if ((s[1] & 0xC0) == 0x80) {
4468 endinpos++;
4469 if ((s[2] & 0xC0) == 0x80)
4470 endinpos++;
4471 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004472 goto utf8Error;
4473 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004474 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004475 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4476 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4477
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004478 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004479 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004480 }
4481 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004482 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004483
Benjamin Peterson29060642009-01-31 22:14:21 +00004484 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004485 if (!has_errors) {
4486 PyObject *tmp;
4487 Py_ssize_t k;
4488 /* We encountered some error that wasn't detected in the original scan,
4489 e.g. an encoded surrogate character. The original maxchar computation may
4490 have been incorrect, so redo it now. */
4491 for (k = 0, maxchar = 0; k < i; k++)
4492 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4493 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4494 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004495 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004496 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004497 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004498 unicode = tmp;
4499 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004500 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004501 if (unicode_decode_call_errorhandler(
4502 errors, &errorHandler,
4503 "utf8", errmsg,
4504 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004505 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004506 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004507 /* Update data because unicode_decode_call_errorhandler might have
4508 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004509 data = PyUnicode_DATA(unicode);
4510 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004511 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004512 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004513 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004514 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004515
Walter Dörwald69652032004-09-07 20:24:22 +00004516 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004517 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004518
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004519 /* Adjust length and ready string when it contained errors and
4520 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004521 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004522 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004523 goto onError;
4524 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004525
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004526 Py_XDECREF(errorHandler);
4527 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004528 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004529 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004530
Benjamin Peterson29060642009-01-31 22:14:21 +00004531 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004532 Py_XDECREF(errorHandler);
4533 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004534 Py_DECREF(unicode);
4535 return NULL;
4536}
4537
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004538#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004539
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004540#ifdef __APPLE__
4541
4542/* Simplified UTF-8 decoder using surrogateescape error handler,
4543 used to decode the command line arguments on Mac OS X. */
4544
4545wchar_t*
4546_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4547{
4548 int n;
4549 const char *e;
4550 wchar_t *unicode, *p;
4551
4552 /* Note: size will always be longer than the resulting Unicode
4553 character count */
4554 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4555 PyErr_NoMemory();
4556 return NULL;
4557 }
4558 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4559 if (!unicode)
4560 return NULL;
4561
4562 /* Unpack UTF-8 encoded data */
4563 p = unicode;
4564 e = s + size;
4565 while (s < e) {
4566 Py_UCS4 ch = (unsigned char)*s;
4567
4568 if (ch < 0x80) {
4569 *p++ = (wchar_t)ch;
4570 s++;
4571 continue;
4572 }
4573
4574 n = utf8_code_length[ch];
4575 if (s + n > e) {
4576 goto surrogateescape;
4577 }
4578
4579 switch (n) {
4580 case 0:
4581 case 1:
4582 goto surrogateescape;
4583
4584 case 2:
4585 if ((s[1] & 0xc0) != 0x80)
4586 goto surrogateescape;
4587 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4588 assert ((ch > 0x007F) && (ch <= 0x07FF));
4589 *p++ = (wchar_t)ch;
4590 break;
4591
4592 case 3:
4593 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4594 will result in surrogates in range d800-dfff. Surrogates are
4595 not valid UTF-8 so they are rejected.
4596 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4597 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4598 if ((s[1] & 0xc0) != 0x80 ||
4599 (s[2] & 0xc0) != 0x80 ||
4600 ((unsigned char)s[0] == 0xE0 &&
4601 (unsigned char)s[1] < 0xA0) ||
4602 ((unsigned char)s[0] == 0xED &&
4603 (unsigned char)s[1] > 0x9F)) {
4604
4605 goto surrogateescape;
4606 }
4607 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4608 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004609 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004610 break;
4611
4612 case 4:
4613 if ((s[1] & 0xc0) != 0x80 ||
4614 (s[2] & 0xc0) != 0x80 ||
4615 (s[3] & 0xc0) != 0x80 ||
4616 ((unsigned char)s[0] == 0xF0 &&
4617 (unsigned char)s[1] < 0x90) ||
4618 ((unsigned char)s[0] == 0xF4 &&
4619 (unsigned char)s[1] > 0x8F)) {
4620 goto surrogateescape;
4621 }
4622 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4623 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4624 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4625
4626#if SIZEOF_WCHAR_T == 4
4627 *p++ = (wchar_t)ch;
4628#else
4629 /* compute and append the two surrogates: */
4630
4631 /* translate from 10000..10FFFF to 0..FFFF */
4632 ch -= 0x10000;
4633
4634 /* high surrogate = top 10 bits added to D800 */
4635 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4636
4637 /* low surrogate = bottom 10 bits added to DC00 */
4638 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4639#endif
4640 break;
4641 }
4642 s += n;
4643 continue;
4644
4645 surrogateescape:
4646 *p++ = 0xDC00 + ch;
4647 s++;
4648 }
4649 *p = L'\0';
4650 return unicode;
4651}
4652
4653#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004654
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004655/* Primary internal function which creates utf8 encoded bytes objects.
4656
4657 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004658 and allocate exactly as much space needed at the end. Else allocate the
4659 maximum possible needed (4 result bytes per Unicode character), and return
4660 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004661*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004662PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004663_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004664{
Tim Peters602f7402002-04-27 18:03:26 +00004665#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004666
Guido van Rossum98297ee2007-11-06 21:34:58 +00004667 Py_ssize_t i; /* index into s of next input byte */
4668 PyObject *result; /* result string object */
4669 char *p; /* next free byte in output buffer */
4670 Py_ssize_t nallocated; /* number of result bytes allocated */
4671 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004672 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004673 PyObject *errorHandler = NULL;
4674 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004675 int kind;
4676 void *data;
4677 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004678
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004679 if (!PyUnicode_Check(unicode)) {
4680 PyErr_BadArgument();
4681 return NULL;
4682 }
4683
4684 if (PyUnicode_READY(unicode) == -1)
4685 return NULL;
4686
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004687 if (PyUnicode_UTF8(unicode))
4688 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4689 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004690
4691 kind = PyUnicode_KIND(unicode);
4692 data = PyUnicode_DATA(unicode);
4693 size = PyUnicode_GET_LENGTH(unicode);
4694
Tim Peters602f7402002-04-27 18:03:26 +00004695 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004696
Tim Peters602f7402002-04-27 18:03:26 +00004697 if (size <= MAX_SHORT_UNICHARS) {
4698 /* Write into the stack buffer; nallocated can't overflow.
4699 * At the end, we'll allocate exactly as much heap space as it
4700 * turns out we need.
4701 */
4702 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004703 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004704 p = stackbuf;
4705 }
4706 else {
4707 /* Overallocate on the heap, and give the excess back at the end. */
4708 nallocated = size * 4;
4709 if (nallocated / 4 != size) /* overflow! */
4710 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004711 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004712 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004713 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004714 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004715 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004716
Tim Peters602f7402002-04-27 18:03:26 +00004717 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004718 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004719
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004720 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004721 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004722 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004723
Guido van Rossumd57fd912000-03-10 22:53:23 +00004724 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004725 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004726 *p++ = (char)(0xc0 | (ch >> 6));
4727 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004728 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004729 Py_ssize_t newpos;
4730 PyObject *rep;
4731 Py_ssize_t repsize, k, startpos;
4732 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004733 rep = unicode_encode_call_errorhandler(
4734 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004735 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004736 if (!rep)
4737 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004738
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004739 if (PyBytes_Check(rep))
4740 repsize = PyBytes_GET_SIZE(rep);
4741 else
4742 repsize = PyUnicode_GET_SIZE(rep);
4743
4744 if (repsize > 4) {
4745 Py_ssize_t offset;
4746
4747 if (result == NULL)
4748 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004749 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004750 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004752 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4753 /* integer overflow */
4754 PyErr_NoMemory();
4755 goto error;
4756 }
4757 nallocated += repsize - 4;
4758 if (result != NULL) {
4759 if (_PyBytes_Resize(&result, nallocated) < 0)
4760 goto error;
4761 } else {
4762 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004763 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004764 goto error;
4765 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4766 }
4767 p = PyBytes_AS_STRING(result) + offset;
4768 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004769
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004770 if (PyBytes_Check(rep)) {
4771 char *prep = PyBytes_AS_STRING(rep);
4772 for(k = repsize; k > 0; k--)
4773 *p++ = *prep++;
4774 } else /* rep is unicode */ {
4775 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4776 Py_UNICODE c;
4777
4778 for(k=0; k<repsize; k++) {
4779 c = prep[k];
4780 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004781 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004782 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004783 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004784 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004785 goto error;
4786 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004787 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004788 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004789 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004790 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004791 } else if (ch < 0x10000) {
4792 *p++ = (char)(0xe0 | (ch >> 12));
4793 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4794 *p++ = (char)(0x80 | (ch & 0x3f));
4795 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004796 /* Encode UCS4 Unicode ordinals */
4797 *p++ = (char)(0xf0 | (ch >> 18));
4798 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4799 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4800 *p++ = (char)(0x80 | (ch & 0x3f));
4801 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004802 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004803
Guido van Rossum98297ee2007-11-06 21:34:58 +00004804 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004805 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004806 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004807 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004808 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004809 }
4810 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004811 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004812 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004813 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004814 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004815 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004816
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004817 Py_XDECREF(errorHandler);
4818 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004819 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004820 error:
4821 Py_XDECREF(errorHandler);
4822 Py_XDECREF(exc);
4823 Py_XDECREF(result);
4824 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004825
Tim Peters602f7402002-04-27 18:03:26 +00004826#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004827}
4828
Alexander Belopolsky40018472011-02-26 01:02:56 +00004829PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004830PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4831 Py_ssize_t size,
4832 const char *errors)
4833{
4834 PyObject *v, *unicode;
4835
4836 unicode = PyUnicode_FromUnicode(s, size);
4837 if (unicode == NULL)
4838 return NULL;
4839 v = _PyUnicode_AsUTF8String(unicode, errors);
4840 Py_DECREF(unicode);
4841 return v;
4842}
4843
4844PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004845PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004846{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004847 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004848}
4849
Walter Dörwald41980ca2007-08-16 21:55:45 +00004850/* --- UTF-32 Codec ------------------------------------------------------- */
4851
4852PyObject *
4853PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004854 Py_ssize_t size,
4855 const char *errors,
4856 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004857{
4858 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4859}
4860
4861PyObject *
4862PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004863 Py_ssize_t size,
4864 const char *errors,
4865 int *byteorder,
4866 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004867{
4868 const char *starts = s;
4869 Py_ssize_t startinpos;
4870 Py_ssize_t endinpos;
4871 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004872 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004873 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004874 int bo = 0; /* assume native ordering by default */
4875 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004876 /* Offsets from q for retrieving bytes in the right order. */
4877#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4878 int iorder[] = {0, 1, 2, 3};
4879#else
4880 int iorder[] = {3, 2, 1, 0};
4881#endif
4882 PyObject *errorHandler = NULL;
4883 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004884
Walter Dörwald41980ca2007-08-16 21:55:45 +00004885 q = (unsigned char *)s;
4886 e = q + size;
4887
4888 if (byteorder)
4889 bo = *byteorder;
4890
4891 /* Check for BOM marks (U+FEFF) in the input and adjust current
4892 byte order setting accordingly. In native mode, the leading BOM
4893 mark is skipped, in all other modes, it is copied to the output
4894 stream as-is (giving a ZWNBSP character). */
4895 if (bo == 0) {
4896 if (size >= 4) {
4897 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004898 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004899#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004900 if (bom == 0x0000FEFF) {
4901 q += 4;
4902 bo = -1;
4903 }
4904 else if (bom == 0xFFFE0000) {
4905 q += 4;
4906 bo = 1;
4907 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004908#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004909 if (bom == 0x0000FEFF) {
4910 q += 4;
4911 bo = 1;
4912 }
4913 else if (bom == 0xFFFE0000) {
4914 q += 4;
4915 bo = -1;
4916 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004917#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004918 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004919 }
4920
4921 if (bo == -1) {
4922 /* force LE */
4923 iorder[0] = 0;
4924 iorder[1] = 1;
4925 iorder[2] = 2;
4926 iorder[3] = 3;
4927 }
4928 else if (bo == 1) {
4929 /* force BE */
4930 iorder[0] = 3;
4931 iorder[1] = 2;
4932 iorder[2] = 1;
4933 iorder[3] = 0;
4934 }
4935
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004936 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004937 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004938 if (!unicode)
4939 return NULL;
4940 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004941 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004942 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004943
Walter Dörwald41980ca2007-08-16 21:55:45 +00004944 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004945 Py_UCS4 ch;
4946 /* remaining bytes at the end? (size should be divisible by 4) */
4947 if (e-q<4) {
4948 if (consumed)
4949 break;
4950 errmsg = "truncated data";
4951 startinpos = ((const char *)q)-starts;
4952 endinpos = ((const char *)e)-starts;
4953 goto utf32Error;
4954 /* The remaining input chars are ignored if the callback
4955 chooses to skip the input */
4956 }
4957 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
4958 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004959
Benjamin Peterson29060642009-01-31 22:14:21 +00004960 if (ch >= 0x110000)
4961 {
4962 errmsg = "codepoint not in range(0x110000)";
4963 startinpos = ((const char *)q)-starts;
4964 endinpos = startinpos+4;
4965 goto utf32Error;
4966 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004967 if (unicode_putchar(&unicode, &outpos, ch) < 0)
4968 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00004969 q += 4;
4970 continue;
4971 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00004972 if (unicode_decode_call_errorhandler(
4973 errors, &errorHandler,
4974 "utf32", errmsg,
4975 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004976 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00004977 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004978 }
4979
4980 if (byteorder)
4981 *byteorder = bo;
4982
4983 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004984 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004985
4986 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004987 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004988 goto onError;
4989
4990 Py_XDECREF(errorHandler);
4991 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004992#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004993 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004994 Py_DECREF(unicode);
4995 return NULL;
4996 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004997#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004998 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004999 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005000
Benjamin Peterson29060642009-01-31 22:14:21 +00005001 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005002 Py_DECREF(unicode);
5003 Py_XDECREF(errorHandler);
5004 Py_XDECREF(exc);
5005 return NULL;
5006}
5007
5008PyObject *
5009PyUnicode_EncodeUTF32(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005010 Py_ssize_t size,
5011 const char *errors,
5012 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005013{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005014 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005015 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005016 Py_ssize_t nsize, bytesize;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005017#ifndef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005018 Py_ssize_t i, pairs;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005019#else
5020 const int pairs = 0;
5021#endif
5022 /* Offsets from p for storing byte pairs in the right order. */
5023#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5024 int iorder[] = {0, 1, 2, 3};
5025#else
5026 int iorder[] = {3, 2, 1, 0};
5027#endif
5028
Benjamin Peterson29060642009-01-31 22:14:21 +00005029#define STORECHAR(CH) \
5030 do { \
5031 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5032 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5033 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5034 p[iorder[0]] = (CH) & 0xff; \
5035 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005036 } while(0)
5037
5038 /* In narrow builds we can output surrogate pairs as one codepoint,
5039 so we need less space. */
5040#ifndef Py_UNICODE_WIDE
5041 for (i = pairs = 0; i < size-1; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005042 if (0xD800 <= s[i] && s[i] <= 0xDBFF &&
5043 0xDC00 <= s[i+1] && s[i+1] <= 0xDFFF)
5044 pairs++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005045#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005046 nsize = (size - pairs + (byteorder == 0));
5047 bytesize = nsize * 4;
5048 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005049 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005050 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005051 if (v == NULL)
5052 return NULL;
5053
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005054 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005055 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005056 STORECHAR(0xFEFF);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005057 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005058 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005059
5060 if (byteorder == -1) {
5061 /* force LE */
5062 iorder[0] = 0;
5063 iorder[1] = 1;
5064 iorder[2] = 2;
5065 iorder[3] = 3;
5066 }
5067 else if (byteorder == 1) {
5068 /* force BE */
5069 iorder[0] = 3;
5070 iorder[1] = 2;
5071 iorder[2] = 1;
5072 iorder[3] = 0;
5073 }
5074
5075 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005076 Py_UCS4 ch = *s++;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005077#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005078 if (0xD800 <= ch && ch <= 0xDBFF && size > 0) {
5079 Py_UCS4 ch2 = *s;
5080 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
5081 ch = (((ch & 0x3FF)<<10) | (ch2 & 0x3FF)) + 0x10000;
5082 s++;
5083 size--;
5084 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00005085 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00005086#endif
5087 STORECHAR(ch);
5088 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005089
5090 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005091 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005092#undef STORECHAR
5093}
5094
Alexander Belopolsky40018472011-02-26 01:02:56 +00005095PyObject *
5096PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005097{
5098 if (!PyUnicode_Check(unicode)) {
5099 PyErr_BadArgument();
5100 return NULL;
5101 }
5102 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005103 PyUnicode_GET_SIZE(unicode),
5104 NULL,
5105 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005106}
5107
Guido van Rossumd57fd912000-03-10 22:53:23 +00005108/* --- UTF-16 Codec ------------------------------------------------------- */
5109
Tim Peters772747b2001-08-09 22:21:55 +00005110PyObject *
5111PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005112 Py_ssize_t size,
5113 const char *errors,
5114 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005115{
Walter Dörwald69652032004-09-07 20:24:22 +00005116 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5117}
5118
Antoine Pitrouab868312009-01-10 15:40:25 +00005119/* Two masks for fast checking of whether a C 'long' may contain
5120 UTF16-encoded surrogate characters. This is an efficient heuristic,
5121 assuming that non-surrogate characters with a code point >= 0x8000 are
5122 rare in most input.
5123 FAST_CHAR_MASK is used when the input is in native byte ordering,
5124 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005125*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005126#if (SIZEOF_LONG == 8)
5127# define FAST_CHAR_MASK 0x8000800080008000L
5128# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5129#elif (SIZEOF_LONG == 4)
5130# define FAST_CHAR_MASK 0x80008000L
5131# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5132#else
5133# error C 'long' size should be either 4 or 8!
5134#endif
5135
Walter Dörwald69652032004-09-07 20:24:22 +00005136PyObject *
5137PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005138 Py_ssize_t size,
5139 const char *errors,
5140 int *byteorder,
5141 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005142{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005143 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005144 Py_ssize_t startinpos;
5145 Py_ssize_t endinpos;
5146 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005147 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005148 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005149 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005150 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005151 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005152 /* Offsets from q for retrieving byte pairs in the right order. */
5153#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5154 int ihi = 1, ilo = 0;
5155#else
5156 int ihi = 0, ilo = 1;
5157#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005158 PyObject *errorHandler = NULL;
5159 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005160
5161 /* Note: size will always be longer than the resulting Unicode
5162 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005163 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005164 if (!unicode)
5165 return NULL;
5166 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005167 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005168 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005169
Tim Peters772747b2001-08-09 22:21:55 +00005170 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005171 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005172
5173 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005174 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005175
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005176 /* Check for BOM marks (U+FEFF) in the input and adjust current
5177 byte order setting accordingly. In native mode, the leading BOM
5178 mark is skipped, in all other modes, it is copied to the output
5179 stream as-is (giving a ZWNBSP character). */
5180 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005181 if (size >= 2) {
5182 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005183#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005184 if (bom == 0xFEFF) {
5185 q += 2;
5186 bo = -1;
5187 }
5188 else if (bom == 0xFFFE) {
5189 q += 2;
5190 bo = 1;
5191 }
Tim Petersced69f82003-09-16 20:30:58 +00005192#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005193 if (bom == 0xFEFF) {
5194 q += 2;
5195 bo = 1;
5196 }
5197 else if (bom == 0xFFFE) {
5198 q += 2;
5199 bo = -1;
5200 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005201#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005202 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005203 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005204
Tim Peters772747b2001-08-09 22:21:55 +00005205 if (bo == -1) {
5206 /* force LE */
5207 ihi = 1;
5208 ilo = 0;
5209 }
5210 else if (bo == 1) {
5211 /* force BE */
5212 ihi = 0;
5213 ilo = 1;
5214 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005215#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5216 native_ordering = ilo < ihi;
5217#else
5218 native_ordering = ilo > ihi;
5219#endif
Tim Peters772747b2001-08-09 22:21:55 +00005220
Antoine Pitrouab868312009-01-10 15:40:25 +00005221 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005222 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005223 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005224 /* First check for possible aligned read of a C 'long'. Unaligned
5225 reads are more expensive, better to defer to another iteration. */
5226 if (!((size_t) q & LONG_PTR_MASK)) {
5227 /* Fast path for runs of non-surrogate chars. */
5228 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005229 int kind = PyUnicode_KIND(unicode);
5230 void *data = PyUnicode_DATA(unicode);
5231 while (_q < aligned_end) {
5232 unsigned long block = * (unsigned long *) _q;
5233 unsigned short *pblock = (unsigned short*)&block;
5234 Py_UCS4 maxch;
5235 if (native_ordering) {
5236 /* Can use buffer directly */
5237 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005238 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005239 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005240 else {
5241 /* Need to byte-swap */
5242 unsigned char *_p = (unsigned char*)pblock;
5243 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005244 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005245 _p[0] = _q[1];
5246 _p[1] = _q[0];
5247 _p[2] = _q[3];
5248 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005249#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005250 _p[4] = _q[5];
5251 _p[5] = _q[4];
5252 _p[6] = _q[7];
5253 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005254#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005255 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005256 maxch = Py_MAX(pblock[0], pblock[1]);
5257#if SIZEOF_LONG == 8
5258 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5259#endif
5260 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5261 if (unicode_widen(&unicode, maxch) < 0)
5262 goto onError;
5263 kind = PyUnicode_KIND(unicode);
5264 data = PyUnicode_DATA(unicode);
5265 }
5266 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5267 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5268#if SIZEOF_LONG == 8
5269 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5270 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5271#endif
5272 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005273 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005274 q = _q;
5275 if (q >= e)
5276 break;
5277 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005278 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005279
Benjamin Peterson14339b62009-01-31 16:36:08 +00005280 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005281
5282 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005283 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5284 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005285 continue;
5286 }
5287
5288 /* UTF-16 code pair: */
5289 if (q > e) {
5290 errmsg = "unexpected end of data";
5291 startinpos = (((const char *)q) - 2) - starts;
5292 endinpos = ((const char *)e) + 1 - starts;
5293 goto utf16Error;
5294 }
5295 if (0xD800 <= ch && ch <= 0xDBFF) {
5296 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5297 q += 2;
5298 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005299 if (unicode_putchar(&unicode, &outpos,
5300 (((ch & 0x3FF)<<10) |
5301 (ch2 & 0x3FF)) + 0x10000) < 0)
5302 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005303 continue;
5304 }
5305 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005306 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005307 startinpos = (((const char *)q)-4)-starts;
5308 endinpos = startinpos+2;
5309 goto utf16Error;
5310 }
5311
Benjamin Peterson14339b62009-01-31 16:36:08 +00005312 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005313 errmsg = "illegal encoding";
5314 startinpos = (((const char *)q)-2)-starts;
5315 endinpos = startinpos+2;
5316 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005317
Benjamin Peterson29060642009-01-31 22:14:21 +00005318 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005319 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005320 errors,
5321 &errorHandler,
5322 "utf16", errmsg,
5323 &starts,
5324 (const char **)&e,
5325 &startinpos,
5326 &endinpos,
5327 &exc,
5328 (const char **)&q,
5329 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005330 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005331 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005332 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005333 /* remaining byte at the end? (size should be even) */
5334 if (e == q) {
5335 if (!consumed) {
5336 errmsg = "truncated data";
5337 startinpos = ((const char *)q) - starts;
5338 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005339 if (unicode_decode_call_errorhandler(
5340 errors,
5341 &errorHandler,
5342 "utf16", errmsg,
5343 &starts,
5344 (const char **)&e,
5345 &startinpos,
5346 &endinpos,
5347 &exc,
5348 (const char **)&q,
5349 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005350 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005351 goto onError;
5352 /* The remaining input chars are ignored if the callback
5353 chooses to skip the input */
5354 }
5355 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005356
5357 if (byteorder)
5358 *byteorder = bo;
5359
Walter Dörwald69652032004-09-07 20:24:22 +00005360 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005362
Guido van Rossumd57fd912000-03-10 22:53:23 +00005363 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005364 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005365 goto onError;
5366
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005367 Py_XDECREF(errorHandler);
5368 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005369 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005370 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005371
Benjamin Peterson29060642009-01-31 22:14:21 +00005372 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005373 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005374 Py_XDECREF(errorHandler);
5375 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005376 return NULL;
5377}
5378
Antoine Pitrouab868312009-01-10 15:40:25 +00005379#undef FAST_CHAR_MASK
5380#undef SWAPPED_FAST_CHAR_MASK
5381
Tim Peters772747b2001-08-09 22:21:55 +00005382PyObject *
5383PyUnicode_EncodeUTF16(const Py_UNICODE *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005384 Py_ssize_t size,
5385 const char *errors,
5386 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005387{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005388 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005389 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005390 Py_ssize_t nsize, bytesize;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005391#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005392 Py_ssize_t i, pairs;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005393#else
5394 const int pairs = 0;
5395#endif
Tim Peters772747b2001-08-09 22:21:55 +00005396 /* Offsets from p for storing byte pairs in the right order. */
5397#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5398 int ihi = 1, ilo = 0;
5399#else
5400 int ihi = 0, ilo = 1;
5401#endif
5402
Benjamin Peterson29060642009-01-31 22:14:21 +00005403#define STORECHAR(CH) \
5404 do { \
5405 p[ihi] = ((CH) >> 8) & 0xff; \
5406 p[ilo] = (CH) & 0xff; \
5407 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005408 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005409
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005410#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005411 for (i = pairs = 0; i < size; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +00005412 if (s[i] >= 0x10000)
5413 pairs++;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005414#endif
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005415 /* 2 * (size + pairs + (byteorder == 0)) */
5416 if (size > PY_SSIZE_T_MAX ||
5417 size > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005418 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005419 nsize = size + pairs + (byteorder == 0);
5420 bytesize = nsize * 2;
5421 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005422 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005423 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424 if (v == NULL)
5425 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005426
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005427 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005428 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005429 STORECHAR(0xFEFF);
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005430 if (size == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005431 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005432
5433 if (byteorder == -1) {
5434 /* force LE */
5435 ihi = 1;
5436 ilo = 0;
5437 }
5438 else if (byteorder == 1) {
5439 /* force BE */
5440 ihi = 0;
5441 ilo = 1;
5442 }
5443
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005444 while (size-- > 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005445 Py_UNICODE ch = *s++;
5446 Py_UNICODE ch2 = 0;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005447#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00005448 if (ch >= 0x10000) {
5449 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5450 ch = 0xD800 | ((ch-0x10000) >> 10);
5451 }
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00005452#endif
Tim Peters772747b2001-08-09 22:21:55 +00005453 STORECHAR(ch);
5454 if (ch2)
5455 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005456 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005457
5458 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005459 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005460#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005461}
5462
Alexander Belopolsky40018472011-02-26 01:02:56 +00005463PyObject *
5464PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005465{
5466 if (!PyUnicode_Check(unicode)) {
5467 PyErr_BadArgument();
5468 return NULL;
5469 }
5470 return PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005471 PyUnicode_GET_SIZE(unicode),
5472 NULL,
5473 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005474}
5475
5476/* --- Unicode Escape Codec ----------------------------------------------- */
5477
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005478/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5479 if all the escapes in the string make it still a valid ASCII string.
5480 Returns -1 if any escapes were found which cause the string to
5481 pop out of ASCII range. Otherwise returns the length of the
5482 required buffer to hold the string.
5483 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005484static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005485length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5486{
5487 const unsigned char *p = (const unsigned char *)s;
5488 const unsigned char *end = p + size;
5489 Py_ssize_t length = 0;
5490
5491 if (size < 0)
5492 return -1;
5493
5494 for (; p < end; ++p) {
5495 if (*p > 127) {
5496 /* Non-ASCII */
5497 return -1;
5498 }
5499 else if (*p != '\\') {
5500 /* Normal character */
5501 ++length;
5502 }
5503 else {
5504 /* Backslash-escape, check next char */
5505 ++p;
5506 /* Escape sequence reaches till end of string or
5507 non-ASCII follow-up. */
5508 if (p >= end || *p > 127)
5509 return -1;
5510 switch (*p) {
5511 case '\n':
5512 /* backslash + \n result in zero characters */
5513 break;
5514 case '\\': case '\'': case '\"':
5515 case 'b': case 'f': case 't':
5516 case 'n': case 'r': case 'v': case 'a':
5517 ++length;
5518 break;
5519 case '0': case '1': case '2': case '3':
5520 case '4': case '5': case '6': case '7':
5521 case 'x': case 'u': case 'U': case 'N':
5522 /* these do not guarantee ASCII characters */
5523 return -1;
5524 default:
5525 /* count the backslash + the other character */
5526 length += 2;
5527 }
5528 }
5529 }
5530 return length;
5531}
5532
5533/* Similar to PyUnicode_WRITE but either write into wstr field
5534 or treat string as ASCII. */
5535#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5536 do { \
5537 if ((kind) != PyUnicode_WCHAR_KIND) \
5538 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5539 else \
5540 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5541 } while (0)
5542
5543#define WRITE_WSTR(buf, index, value) \
5544 assert(kind == PyUnicode_WCHAR_KIND), \
5545 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5546
5547
Fredrik Lundh06d12682001-01-24 07:59:11 +00005548static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005549
Alexander Belopolsky40018472011-02-26 01:02:56 +00005550PyObject *
5551PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005552 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005553 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005554{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005555 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005556 Py_ssize_t startinpos;
5557 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005558 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005559 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005560 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005561 char* message;
5562 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005563 PyObject *errorHandler = NULL;
5564 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005565 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005566 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005567
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005568 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005569
5570 /* After length_of_escaped_ascii_string() there are two alternatives,
5571 either the string is pure ASCII with named escapes like \n, etc.
5572 and we determined it's exact size (common case)
5573 or it contains \x, \u, ... escape sequences. then we create a
5574 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005575 if (len >= 0) {
5576 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005577 if (!v)
5578 goto onError;
5579 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005580 }
5581 else {
5582 /* Escaped strings will always be longer than the resulting
5583 Unicode string, so we start with size here and then reduce the
5584 length after conversion to the true value.
5585 (but if the error callback returns a long replacement string
5586 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005587 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005588 if (!v)
5589 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005590 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005591 }
5592
Guido van Rossumd57fd912000-03-10 22:53:23 +00005593 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005594 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005595 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005596 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005597
Guido van Rossumd57fd912000-03-10 22:53:23 +00005598 while (s < end) {
5599 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005600 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005601 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005602
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005603 /* The only case in which i == ascii_length is a backslash
5604 followed by a newline. */
5605 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005606
Guido van Rossumd57fd912000-03-10 22:53:23 +00005607 /* Non-escape characters are interpreted as Unicode ordinals */
5608 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005609 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5610 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005611 continue;
5612 }
5613
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005614 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615 /* \ - Escapes */
5616 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005617 c = *s++;
5618 if (s > end)
5619 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005620
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005621 /* The only case in which i == ascii_length is a backslash
5622 followed by a newline. */
5623 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005624
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005625 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005626
Benjamin Peterson29060642009-01-31 22:14:21 +00005627 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005628#define WRITECHAR(ch) \
5629 do { \
5630 if (unicode_putchar(&v, &i, ch) < 0) \
5631 goto onError; \
5632 }while(0)
5633
Guido van Rossumd57fd912000-03-10 22:53:23 +00005634 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005635 case '\\': WRITECHAR('\\'); break;
5636 case '\'': WRITECHAR('\''); break;
5637 case '\"': WRITECHAR('\"'); break;
5638 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005639 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005640 case 'f': WRITECHAR('\014'); break;
5641 case 't': WRITECHAR('\t'); break;
5642 case 'n': WRITECHAR('\n'); break;
5643 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005644 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005645 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005646 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005647 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005648
Benjamin Peterson29060642009-01-31 22:14:21 +00005649 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005650 case '0': case '1': case '2': case '3':
5651 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005652 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005653 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005654 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005655 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005656 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005657 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005658 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005659 break;
5660
Benjamin Peterson29060642009-01-31 22:14:21 +00005661 /* hex escapes */
5662 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005664 digits = 2;
5665 message = "truncated \\xXX escape";
5666 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005667
Benjamin Peterson29060642009-01-31 22:14:21 +00005668 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005669 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005670 digits = 4;
5671 message = "truncated \\uXXXX escape";
5672 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005673
Benjamin Peterson29060642009-01-31 22:14:21 +00005674 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005675 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005676 digits = 8;
5677 message = "truncated \\UXXXXXXXX escape";
5678 hexescape:
5679 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005680 if (s+digits>end) {
5681 endinpos = size;
5682 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005683 errors, &errorHandler,
5684 "unicodeescape", "end of string in escape sequence",
5685 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005686 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005687 goto onError;
5688 goto nextByte;
5689 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005690 for (j = 0; j < digits; ++j) {
5691 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005692 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005693 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005694 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005695 errors, &errorHandler,
5696 "unicodeescape", message,
5697 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005698 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005699 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005700 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005701 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005702 }
5703 chr = (chr<<4) & ~0xF;
5704 if (c >= '0' && c <= '9')
5705 chr += c - '0';
5706 else if (c >= 'a' && c <= 'f')
5707 chr += 10 + c - 'a';
5708 else
5709 chr += 10 + c - 'A';
5710 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005711 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005712 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005713 /* _decoding_error will have already written into the
5714 target buffer. */
5715 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005716 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005717 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005718 if (chr <= 0x10ffff) {
5719 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005720 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005721 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005722 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005723 errors, &errorHandler,
5724 "unicodeescape", "illegal Unicode character",
5725 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005726 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005727 goto onError;
5728 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005729 break;
5730
Benjamin Peterson29060642009-01-31 22:14:21 +00005731 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005732 case 'N':
5733 message = "malformed \\N character escape";
5734 if (ucnhash_CAPI == NULL) {
5735 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005736 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5737 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005738 if (ucnhash_CAPI == NULL)
5739 goto ucnhashError;
5740 }
5741 if (*s == '{') {
5742 const char *start = s+1;
5743 /* look for the closing brace */
5744 while (*s != '}' && s < end)
5745 s++;
5746 if (s > start && s < end && *s == '}') {
5747 /* found a name. look it up in the unicode database */
5748 message = "unknown Unicode character name";
5749 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005750 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005751 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005752 goto store;
5753 }
5754 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005755 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005756 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005757 errors, &errorHandler,
5758 "unicodeescape", message,
5759 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005760 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005761 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005762 break;
5763
5764 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005765 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005766 message = "\\ at end of string";
5767 s--;
5768 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005769 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005770 errors, &errorHandler,
5771 "unicodeescape", message,
5772 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005773 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005774 goto onError;
5775 }
5776 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005777 WRITECHAR('\\');
5778 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005779 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005780 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005781 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005782 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005783 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005784 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005785#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005786
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005787 if (PyUnicode_Resize(&v, i) < 0)
5788 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005789 Py_XDECREF(errorHandler);
5790 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005791#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005792 if (_PyUnicode_READY_REPLACE(&v)) {
5793 Py_DECREF(v);
5794 return NULL;
5795 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005796#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005797 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005798 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005799
Benjamin Peterson29060642009-01-31 22:14:21 +00005800 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005801 PyErr_SetString(
5802 PyExc_UnicodeError,
5803 "\\N escapes not supported (can't load unicodedata module)"
5804 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005805 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005806 Py_XDECREF(errorHandler);
5807 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005808 return NULL;
5809
Benjamin Peterson29060642009-01-31 22:14:21 +00005810 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005811 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005812 Py_XDECREF(errorHandler);
5813 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005814 return NULL;
5815}
5816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005817#undef WRITE_ASCII_OR_WSTR
5818#undef WRITE_WSTR
5819
Guido van Rossumd57fd912000-03-10 22:53:23 +00005820/* Return a Unicode-Escape string version of the Unicode object.
5821
5822 If quotes is true, the string is enclosed in u"" or u'' quotes as
5823 appropriate.
5824
5825*/
5826
Alexander Belopolsky40018472011-02-26 01:02:56 +00005827PyObject *
5828PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005829 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005830{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005831 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005832 char *p;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005833
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005834#ifdef Py_UNICODE_WIDE
5835 const Py_ssize_t expandsize = 10;
5836#else
5837 const Py_ssize_t expandsize = 6;
5838#endif
5839
Thomas Wouters89f507f2006-12-13 04:49:30 +00005840 /* XXX(nnorwitz): rather than over-allocating, it would be
5841 better to choose a different scheme. Perhaps scan the
5842 first N-chars of the string and allocate based on that size.
5843 */
5844 /* Initial allocation is based on the longest-possible unichr
5845 escape.
5846
5847 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5848 unichr, so in this case it's the longest unichr escape. In
5849 narrow (UTF-16) builds this is five chars per source unichr
5850 since there are two unichrs in the surrogate pair, so in narrow
5851 (UTF-16) builds it's not the longest unichr escape.
5852
5853 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5854 so in the narrow (UTF-16) build case it's the longest unichr
5855 escape.
5856 */
5857
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005858 if (size == 0)
5859 return PyBytes_FromStringAndSize(NULL, 0);
5860
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005861 if (size > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005862 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005863
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005864 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005865 2
5866 + expandsize*size
5867 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005868 if (repr == NULL)
5869 return NULL;
5870
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005871 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872
Guido van Rossumd57fd912000-03-10 22:53:23 +00005873 while (size-- > 0) {
5874 Py_UNICODE ch = *s++;
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005875
Walter Dörwald79e913e2007-05-12 11:08:06 +00005876 /* Escape backslashes */
5877 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005878 *p++ = '\\';
5879 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005880 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005881 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005882
Guido van Rossum0d42e0c2001-07-20 16:36:21 +00005883#ifdef Py_UNICODE_WIDE
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005884 /* Map 21-bit characters to '\U00xxxxxx' */
5885 else if (ch >= 0x10000) {
5886 *p++ = '\\';
5887 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005888 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5889 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5890 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5891 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5892 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5893 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5894 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5895 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005896 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005897 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005898#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005899 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
5900 else if (ch >= 0xD800 && ch < 0xDC00) {
5901 Py_UNICODE ch2;
5902 Py_UCS4 ucs;
Tim Petersced69f82003-09-16 20:30:58 +00005903
Benjamin Peterson29060642009-01-31 22:14:21 +00005904 ch2 = *s++;
5905 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00005906 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005907 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
5908 *p++ = '\\';
5909 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005910 *p++ = Py_hexdigits[(ucs >> 28) & 0x0000000F];
5911 *p++ = Py_hexdigits[(ucs >> 24) & 0x0000000F];
5912 *p++ = Py_hexdigits[(ucs >> 20) & 0x0000000F];
5913 *p++ = Py_hexdigits[(ucs >> 16) & 0x0000000F];
5914 *p++ = Py_hexdigits[(ucs >> 12) & 0x0000000F];
5915 *p++ = Py_hexdigits[(ucs >> 8) & 0x0000000F];
5916 *p++ = Py_hexdigits[(ucs >> 4) & 0x0000000F];
5917 *p++ = Py_hexdigits[ucs & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005918 continue;
5919 }
5920 /* Fall through: isolated surrogates are copied as-is */
5921 s--;
5922 size++;
Benjamin Peterson14339b62009-01-31 16:36:08 +00005923 }
Thomas Wouters89f507f2006-12-13 04:49:30 +00005924#endif
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005925
Guido van Rossumd57fd912000-03-10 22:53:23 +00005926 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005927 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005928 *p++ = '\\';
5929 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005930 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5931 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5932 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5933 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005934 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005935
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005936 /* Map special whitespace to '\t', \n', '\r' */
5937 else if (ch == '\t') {
5938 *p++ = '\\';
5939 *p++ = 't';
5940 }
5941 else if (ch == '\n') {
5942 *p++ = '\\';
5943 *p++ = 'n';
5944 }
5945 else if (ch == '\r') {
5946 *p++ = '\\';
5947 *p++ = 'r';
5948 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005949
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005950 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005951 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005952 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005953 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005954 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5955 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005956 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005957
Guido van Rossumd57fd912000-03-10 22:53:23 +00005958 /* Copy everything else as-is */
5959 else
5960 *p++ = (char) ch;
5961 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005962
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005963 assert(p - PyBytes_AS_STRING(repr) > 0);
5964 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
5965 return NULL;
5966 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967}
5968
Alexander Belopolsky40018472011-02-26 01:02:56 +00005969PyObject *
5970PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005971{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005972 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005973 if (!PyUnicode_Check(unicode)) {
5974 PyErr_BadArgument();
5975 return NULL;
5976 }
Walter Dörwald79e913e2007-05-12 11:08:06 +00005977 s = PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
5978 PyUnicode_GET_SIZE(unicode));
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00005979 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005980}
5981
5982/* --- Raw Unicode Escape Codec ------------------------------------------- */
5983
Alexander Belopolsky40018472011-02-26 01:02:56 +00005984PyObject *
5985PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005986 Py_ssize_t size,
5987 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005988{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005989 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005990 Py_ssize_t startinpos;
5991 Py_ssize_t endinpos;
5992 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005993 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005994 const char *end;
5995 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005996 PyObject *errorHandler = NULL;
5997 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00005998
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 /* Escaped strings will always be longer than the resulting
6000 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006001 length after conversion to the true value. (But decoding error
6002 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006003 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006004 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006005 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006006 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006007 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006008 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006009 end = s + size;
6010 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006011 unsigned char c;
6012 Py_UCS4 x;
6013 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006014 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006015
Benjamin Peterson29060642009-01-31 22:14:21 +00006016 /* Non-escape characters are interpreted as Unicode ordinals */
6017 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006018 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6019 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006020 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006021 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006022 startinpos = s-starts;
6023
6024 /* \u-escapes are only interpreted iff the number of leading
6025 backslashes if odd */
6026 bs = s;
6027 for (;s < end;) {
6028 if (*s != '\\')
6029 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006030 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6031 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006032 }
6033 if (((s - bs) & 1) == 0 ||
6034 s >= end ||
6035 (*s != 'u' && *s != 'U')) {
6036 continue;
6037 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006038 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006039 count = *s=='u' ? 4 : 8;
6040 s++;
6041
6042 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006043 for (x = 0, i = 0; i < count; ++i, ++s) {
6044 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006045 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 endinpos = s-starts;
6047 if (unicode_decode_call_errorhandler(
6048 errors, &errorHandler,
6049 "rawunicodeescape", "truncated \\uXXXX",
6050 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006051 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006052 goto onError;
6053 goto nextByte;
6054 }
6055 x = (x<<4) & ~0xF;
6056 if (c >= '0' && c <= '9')
6057 x += c - '0';
6058 else if (c >= 'a' && c <= 'f')
6059 x += 10 + c - 'a';
6060 else
6061 x += 10 + c - 'A';
6062 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006063 if (x <= 0x10ffff) {
6064 if (unicode_putchar(&v, &outpos, x) < 0)
6065 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006066 } else {
6067 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006068 if (unicode_decode_call_errorhandler(
6069 errors, &errorHandler,
6070 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006071 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006072 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006074 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006075 nextByte:
6076 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006077 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006078 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006079 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006080 Py_XDECREF(errorHandler);
6081 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006082 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006083 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006084
Benjamin Peterson29060642009-01-31 22:14:21 +00006085 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006086 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006087 Py_XDECREF(errorHandler);
6088 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006089 return NULL;
6090}
6091
Alexander Belopolsky40018472011-02-26 01:02:56 +00006092PyObject *
6093PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006094 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006095{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006096 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006097 char *p;
6098 char *q;
6099
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006100#ifdef Py_UNICODE_WIDE
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006101 const Py_ssize_t expandsize = 10;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006102#else
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006103 const Py_ssize_t expandsize = 6;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006104#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00006105
Neal Norwitz3ce5d922008-08-24 07:08:55 +00006106 if (size > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006107 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006108
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006109 repr = PyBytes_FromStringAndSize(NULL, expandsize * size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006110 if (repr == NULL)
6111 return NULL;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00006112 if (size == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006113 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006114
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006115 p = q = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006116 while (size-- > 0) {
6117 Py_UNICODE ch = *s++;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006118#ifdef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006119 /* Map 32-bit characters to '\Uxxxxxxxx' */
6120 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006121 *p++ = '\\';
6122 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006123 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6124 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6125 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6126 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6127 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6128 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6129 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6130 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006131 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006132 else
Christian Heimesfe337bf2008-03-23 21:54:12 +00006133#else
Benjamin Peterson29060642009-01-31 22:14:21 +00006134 /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
6135 if (ch >= 0xD800 && ch < 0xDC00) {
6136 Py_UNICODE ch2;
6137 Py_UCS4 ucs;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006138
Benjamin Peterson29060642009-01-31 22:14:21 +00006139 ch2 = *s++;
6140 size--;
Georg Brandl78eef3de2010-08-01 20:51:02 +00006141 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006142 ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
6143 *p++ = '\\';
6144 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006145 *p++ = Py_hexdigits[(ucs >> 28) & 0xf];
6146 *p++ = Py_hexdigits[(ucs >> 24) & 0xf];
6147 *p++ = Py_hexdigits[(ucs >> 20) & 0xf];
6148 *p++ = Py_hexdigits[(ucs >> 16) & 0xf];
6149 *p++ = Py_hexdigits[(ucs >> 12) & 0xf];
6150 *p++ = Py_hexdigits[(ucs >> 8) & 0xf];
6151 *p++ = Py_hexdigits[(ucs >> 4) & 0xf];
6152 *p++ = Py_hexdigits[ucs & 0xf];
Benjamin Peterson29060642009-01-31 22:14:21 +00006153 continue;
6154 }
6155 /* Fall through: isolated surrogates are copied as-is */
6156 s--;
6157 size++;
6158 }
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006159#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006160 /* Map 16-bit characters to '\uxxxx' */
6161 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006162 *p++ = '\\';
6163 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006164 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6165 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6166 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6167 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006168 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006169 /* Copy everything else as-is */
6170 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006171 *p++ = (char) ch;
6172 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006173 size = p - q;
6174
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006175 assert(size > 0);
6176 if (_PyBytes_Resize(&repr, size) < 0)
6177 return NULL;
6178 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006179}
6180
Alexander Belopolsky40018472011-02-26 01:02:56 +00006181PyObject *
6182PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006183{
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006184 PyObject *s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006185 if (!PyUnicode_Check(unicode)) {
Walter Dörwald711005d2007-05-12 12:03:26 +00006186 PyErr_BadArgument();
6187 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188 }
Walter Dörwald711005d2007-05-12 12:03:26 +00006189 s = PyUnicode_EncodeRawUnicodeEscape(PyUnicode_AS_UNICODE(unicode),
6190 PyUnicode_GET_SIZE(unicode));
6191
Alexandre Vassalotti9cb6f7f2008-12-27 09:09:15 +00006192 return s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006193}
6194
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006195/* --- Unicode Internal Codec ------------------------------------------- */
6196
Alexander Belopolsky40018472011-02-26 01:02:56 +00006197PyObject *
6198_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006199 Py_ssize_t size,
6200 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006201{
6202 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006203 Py_ssize_t startinpos;
6204 Py_ssize_t endinpos;
6205 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006206 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006207 const char *end;
6208 const char *reason;
6209 PyObject *errorHandler = NULL;
6210 PyObject *exc = NULL;
6211
Thomas Wouters89f507f2006-12-13 04:49:30 +00006212 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006213 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006214 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006215 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006216 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006217 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006218 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006219 end = s + size;
6220
6221 while (s < end) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006222 Py_UCS4 ch = *(Py_UNICODE*)s;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006223 /* We have to sanity check the raw data, otherwise doom looms for
6224 some malformed UCS-4 data. */
6225 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006226#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006227 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006228#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006229 end-s < Py_UNICODE_SIZE
6230 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006231 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006232 startinpos = s - starts;
6233 if (end-s < Py_UNICODE_SIZE) {
6234 endinpos = end-starts;
6235 reason = "truncated input";
6236 }
6237 else {
6238 endinpos = s - starts + Py_UNICODE_SIZE;
6239 reason = "illegal code point (> 0x10FFFF)";
6240 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006241 if (unicode_decode_call_errorhandler(
6242 errors, &errorHandler,
6243 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006244 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006245 &v, &outpos)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006246 goto onError;
6247 }
6248 }
6249 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006250 if (unicode_putchar(&v, &outpos, ch) < 0)
6251 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006252 s += Py_UNICODE_SIZE;
6253 }
6254 }
6255
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006256 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006257 goto onError;
6258 Py_XDECREF(errorHandler);
6259 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006260 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006261 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006262
Benjamin Peterson29060642009-01-31 22:14:21 +00006263 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006264 Py_XDECREF(v);
6265 Py_XDECREF(errorHandler);
6266 Py_XDECREF(exc);
6267 return NULL;
6268}
6269
Guido van Rossumd57fd912000-03-10 22:53:23 +00006270/* --- Latin-1 Codec ------------------------------------------------------ */
6271
Alexander Belopolsky40018472011-02-26 01:02:56 +00006272PyObject *
6273PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006274 Py_ssize_t size,
6275 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006276{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006277 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006278 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006279}
6280
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006281/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006282static void
6283make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006284 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006285 PyObject *unicode,
6286 Py_ssize_t startpos, Py_ssize_t endpos,
6287 const char *reason)
6288{
6289 if (*exceptionObject == NULL) {
6290 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006291 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006292 encoding, unicode, startpos, endpos, reason);
6293 }
6294 else {
6295 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6296 goto onError;
6297 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6298 goto onError;
6299 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6300 goto onError;
6301 return;
6302 onError:
6303 Py_DECREF(*exceptionObject);
6304 *exceptionObject = NULL;
6305 }
6306}
6307
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006308/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006309static void
6310raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006311 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006312 PyObject *unicode,
6313 Py_ssize_t startpos, Py_ssize_t endpos,
6314 const char *reason)
6315{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006316 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006317 encoding, unicode, startpos, endpos, reason);
6318 if (*exceptionObject != NULL)
6319 PyCodec_StrictErrors(*exceptionObject);
6320}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006321
6322/* error handling callback helper:
6323 build arguments, call the callback and check the arguments,
6324 put the result into newpos and return the replacement string, which
6325 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006326static PyObject *
6327unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006328 PyObject **errorHandler,
6329 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006330 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006331 Py_ssize_t startpos, Py_ssize_t endpos,
6332 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006333{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006334 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006335 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006336 PyObject *restuple;
6337 PyObject *resunicode;
6338
6339 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006340 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006341 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006342 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006343 }
6344
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006345 if (PyUnicode_READY(unicode) < 0)
6346 return NULL;
6347 len = PyUnicode_GET_LENGTH(unicode);
6348
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006349 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006350 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006351 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006352 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006353
6354 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006355 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006356 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006357 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006358 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006359 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006360 Py_DECREF(restuple);
6361 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006362 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006363 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006364 &resunicode, newpos)) {
6365 Py_DECREF(restuple);
6366 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006368 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6369 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6370 Py_DECREF(restuple);
6371 return NULL;
6372 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006373 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006374 *newpos = len + *newpos;
6375 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6377 Py_DECREF(restuple);
6378 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006379 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006380 Py_INCREF(resunicode);
6381 Py_DECREF(restuple);
6382 return resunicode;
6383}
6384
Alexander Belopolsky40018472011-02-26 01:02:56 +00006385static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006386unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006387 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006388 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006389{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006390 /* input state */
6391 Py_ssize_t pos=0, size;
6392 int kind;
6393 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006394 /* output object */
6395 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006396 /* pointer into the output */
6397 char *str;
6398 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006399 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006400 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6401 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006402 PyObject *errorHandler = NULL;
6403 PyObject *exc = NULL;
6404 /* the following variable is used for caching string comparisons
6405 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6406 int known_errorHandler = -1;
6407
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006408 if (PyUnicode_READY(unicode) < 0)
6409 return NULL;
6410 size = PyUnicode_GET_LENGTH(unicode);
6411 kind = PyUnicode_KIND(unicode);
6412 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006413 /* allocate enough for a simple encoding without
6414 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006415 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006416 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006417 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006419 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006420 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006421 ressize = size;
6422
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006423 while (pos < size) {
6424 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006425
Benjamin Peterson29060642009-01-31 22:14:21 +00006426 /* can we encode this? */
6427 if (c<limit) {
6428 /* no overflow check, because we know that the space is enough */
6429 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006430 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006431 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006432 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006433 Py_ssize_t requiredsize;
6434 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006435 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006436 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006437 Py_ssize_t collstart = pos;
6438 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006439 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006440 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006441 ++collend;
6442 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6443 if (known_errorHandler==-1) {
6444 if ((errors==NULL) || (!strcmp(errors, "strict")))
6445 known_errorHandler = 1;
6446 else if (!strcmp(errors, "replace"))
6447 known_errorHandler = 2;
6448 else if (!strcmp(errors, "ignore"))
6449 known_errorHandler = 3;
6450 else if (!strcmp(errors, "xmlcharrefreplace"))
6451 known_errorHandler = 4;
6452 else
6453 known_errorHandler = 0;
6454 }
6455 switch (known_errorHandler) {
6456 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006457 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006458 goto onError;
6459 case 2: /* replace */
6460 while (collstart++<collend)
6461 *str++ = '?'; /* fall through */
6462 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006463 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006464 break;
6465 case 4: /* xmlcharrefreplace */
6466 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006467 /* determine replacement size */
6468 for (i = collstart, repsize = 0; i < collend; ++i) {
6469 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6470 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006471 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006472 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006473 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006474 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006475 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006476 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006477 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006478#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006479 else
6480 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006481#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006482 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006483 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006484 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006485 repsize += 2+6+1;
6486 else
6487 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006488#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006489 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006490 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006491 if (requiredsize > ressize) {
6492 if (requiredsize<2*ressize)
6493 requiredsize = 2*ressize;
6494 if (_PyBytes_Resize(&res, requiredsize))
6495 goto onError;
6496 str = PyBytes_AS_STRING(res) + respos;
6497 ressize = requiredsize;
6498 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006499 /* generate replacement */
6500 for (i = collstart; i < collend; ++i) {
6501 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006502 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006503 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006504 break;
6505 default:
6506 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006507 encoding, reason, unicode, &exc,
6508 collstart, collend, &newpos);
6509 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6510 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006511 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006512 if (PyBytes_Check(repunicode)) {
6513 /* Directly copy bytes result to output. */
6514 repsize = PyBytes_Size(repunicode);
6515 if (repsize > 1) {
6516 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006517 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006518 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6519 Py_DECREF(repunicode);
6520 goto onError;
6521 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006522 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006523 ressize += repsize-1;
6524 }
6525 memcpy(str, PyBytes_AsString(repunicode), repsize);
6526 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006528 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006529 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006530 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006531 /* need more space? (at least enough for what we
6532 have+the replacement+the rest of the string, so
6533 we won't have to check space for encodable characters) */
6534 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006535 repsize = PyUnicode_GET_LENGTH(repunicode);
6536 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006537 if (requiredsize > ressize) {
6538 if (requiredsize<2*ressize)
6539 requiredsize = 2*ressize;
6540 if (_PyBytes_Resize(&res, requiredsize)) {
6541 Py_DECREF(repunicode);
6542 goto onError;
6543 }
6544 str = PyBytes_AS_STRING(res) + respos;
6545 ressize = requiredsize;
6546 }
6547 /* check if there is anything unencodable in the replacement
6548 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006549 for (i = 0; repsize-->0; ++i, ++str) {
6550 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006551 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006552 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006553 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006554 Py_DECREF(repunicode);
6555 goto onError;
6556 }
6557 *str = (char)c;
6558 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006559 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006560 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006561 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006562 }
6563 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006564 /* Resize if we allocated to much */
6565 size = str - PyBytes_AS_STRING(res);
6566 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006567 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006568 if (_PyBytes_Resize(&res, size) < 0)
6569 goto onError;
6570 }
6571
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006572 Py_XDECREF(errorHandler);
6573 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006574 return res;
6575
6576 onError:
6577 Py_XDECREF(res);
6578 Py_XDECREF(errorHandler);
6579 Py_XDECREF(exc);
6580 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006581}
6582
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006584PyObject *
6585PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006586 Py_ssize_t size,
6587 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006588{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006589 PyObject *result;
6590 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6591 if (unicode == NULL)
6592 return NULL;
6593 result = unicode_encode_ucs1(unicode, errors, 256);
6594 Py_DECREF(unicode);
6595 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006596}
6597
Alexander Belopolsky40018472011-02-26 01:02:56 +00006598PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006599_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006600{
6601 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006602 PyErr_BadArgument();
6603 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006604 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006605 if (PyUnicode_READY(unicode) == -1)
6606 return NULL;
6607 /* Fast path: if it is a one-byte string, construct
6608 bytes object directly. */
6609 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6610 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6611 PyUnicode_GET_LENGTH(unicode));
6612 /* Non-Latin-1 characters present. Defer to above function to
6613 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006614 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006615}
6616
6617PyObject*
6618PyUnicode_AsLatin1String(PyObject *unicode)
6619{
6620 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006621}
6622
6623/* --- 7-bit ASCII Codec -------------------------------------------------- */
6624
Alexander Belopolsky40018472011-02-26 01:02:56 +00006625PyObject *
6626PyUnicode_DecodeASCII(const char *s,
6627 Py_ssize_t size,
6628 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006629{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006630 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006631 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006632 int kind;
6633 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006634 Py_ssize_t startinpos;
6635 Py_ssize_t endinpos;
6636 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006637 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006638 int has_error;
6639 const unsigned char *p = (const unsigned char *)s;
6640 const unsigned char *end = p + size;
6641 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006642 PyObject *errorHandler = NULL;
6643 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006644
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006646 if (size == 1 && (unsigned char)s[0] < 128)
6647 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006648
Victor Stinner702c7342011-10-05 13:50:52 +02006649 has_error = 0;
6650 while (p < end && !has_error) {
6651 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6652 an explanation. */
6653 if (!((size_t) p & LONG_PTR_MASK)) {
6654 /* Help register allocation */
6655 register const unsigned char *_p = p;
6656 while (_p < aligned_end) {
6657 unsigned long value = *(unsigned long *) _p;
6658 if (value & ASCII_CHAR_MASK) {
6659 has_error = 1;
6660 break;
6661 }
6662 _p += SIZEOF_LONG;
6663 }
6664 if (_p == end)
6665 break;
6666 if (has_error)
6667 break;
6668 p = _p;
6669 }
6670 if (*p & 0x80) {
6671 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006672 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006673 }
6674 else {
6675 ++p;
6676 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006677 }
Victor Stinner702c7342011-10-05 13:50:52 +02006678 if (!has_error)
6679 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006680
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006681 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006682 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006683 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006684 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006685 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006686 kind = PyUnicode_KIND(v);
6687 data = PyUnicode_DATA(v);
6688 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006689 e = s + size;
6690 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006691 register unsigned char c = (unsigned char)*s;
6692 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006693 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006694 ++s;
6695 }
6696 else {
6697 startinpos = s-starts;
6698 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006699 if (unicode_decode_call_errorhandler(
6700 errors, &errorHandler,
6701 "ascii", "ordinal not in range(128)",
6702 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006703 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006704 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006705 kind = PyUnicode_KIND(v);
6706 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006708 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006709 if (PyUnicode_Resize(&v, outpos) < 0)
6710 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006711 Py_XDECREF(errorHandler);
6712 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006713 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006714 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006715
Benjamin Peterson29060642009-01-31 22:14:21 +00006716 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006717 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006718 Py_XDECREF(errorHandler);
6719 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006720 return NULL;
6721}
6722
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006723/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006724PyObject *
6725PyUnicode_EncodeASCII(const Py_UNICODE *p,
6726 Py_ssize_t size,
6727 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006728{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006729 PyObject *result;
6730 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6731 if (unicode == NULL)
6732 return NULL;
6733 result = unicode_encode_ucs1(unicode, errors, 128);
6734 Py_DECREF(unicode);
6735 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006736}
6737
Alexander Belopolsky40018472011-02-26 01:02:56 +00006738PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006739_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006740{
6741 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006742 PyErr_BadArgument();
6743 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006745 if (PyUnicode_READY(unicode) == -1)
6746 return NULL;
6747 /* Fast path: if it is an ASCII-only string, construct bytes object
6748 directly. Else defer to above function to raise the exception. */
6749 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6750 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6751 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006752 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006753}
6754
6755PyObject *
6756PyUnicode_AsASCIIString(PyObject *unicode)
6757{
6758 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006759}
6760
Victor Stinner99b95382011-07-04 14:23:54 +02006761#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006762
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006763/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006764
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006765#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006766#define NEED_RETRY
6767#endif
6768
Victor Stinner3a50e702011-10-18 21:21:00 +02006769#ifndef WC_ERR_INVALID_CHARS
6770# define WC_ERR_INVALID_CHARS 0x0080
6771#endif
6772
6773static char*
6774code_page_name(UINT code_page, PyObject **obj)
6775{
6776 *obj = NULL;
6777 if (code_page == CP_ACP)
6778 return "mbcs";
6779 if (code_page == CP_UTF7)
6780 return "CP_UTF7";
6781 if (code_page == CP_UTF8)
6782 return "CP_UTF8";
6783
6784 *obj = PyBytes_FromFormat("cp%u", code_page);
6785 if (*obj == NULL)
6786 return NULL;
6787 return PyBytes_AS_STRING(*obj);
6788}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006789
Alexander Belopolsky40018472011-02-26 01:02:56 +00006790static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006791is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006792{
6793 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006794 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006795
Victor Stinner3a50e702011-10-18 21:21:00 +02006796 if (!IsDBCSLeadByteEx(code_page, *curr))
6797 return 0;
6798
6799 prev = CharPrevExA(code_page, s, curr, 0);
6800 if (prev == curr)
6801 return 1;
6802 /* FIXME: This code is limited to "true" double-byte encodings,
6803 as it assumes an incomplete character consists of a single
6804 byte. */
6805 if (curr - prev == 2)
6806 return 1;
6807 if (!IsDBCSLeadByteEx(code_page, *prev))
6808 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006809 return 0;
6810}
6811
Victor Stinner3a50e702011-10-18 21:21:00 +02006812static DWORD
6813decode_code_page_flags(UINT code_page)
6814{
6815 if (code_page == CP_UTF7) {
6816 /* The CP_UTF7 decoder only supports flags=0 */
6817 return 0;
6818 }
6819 else
6820 return MB_ERR_INVALID_CHARS;
6821}
6822
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006823/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006824 * Decode a byte string from a Windows code page into unicode object in strict
6825 * mode.
6826 *
6827 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6828 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006829 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006830static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006831decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006832 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006833 const char *in,
6834 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006835{
Victor Stinner3a50e702011-10-18 21:21:00 +02006836 const DWORD flags = decode_code_page_flags(code_page);
6837 Py_UNICODE *out;
6838 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006839
6840 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006841 assert(insize > 0);
6842 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6843 if (outsize <= 0)
6844 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006845
6846 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006847 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006848 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006849 if (*v == NULL)
6850 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006851 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006852 }
6853 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006854 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006855 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006856 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006857 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006858 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006859 }
6860
6861 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006862 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6863 if (outsize <= 0)
6864 goto error;
6865 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006866
Victor Stinner3a50e702011-10-18 21:21:00 +02006867error:
6868 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6869 return -2;
6870 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006871 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006872}
6873
Victor Stinner3a50e702011-10-18 21:21:00 +02006874/*
6875 * Decode a byte string from a code page into unicode object with an error
6876 * handler.
6877 *
6878 * Returns consumed size if succeed, or raise a WindowsError or
6879 * UnicodeDecodeError exception and returns -1 on error.
6880 */
6881static int
6882decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006883 PyObject **v,
6884 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006885 const char *errors)
6886{
6887 const char *startin = in;
6888 const char *endin = in + size;
6889 const DWORD flags = decode_code_page_flags(code_page);
6890 /* Ideally, we should get reason from FormatMessage. This is the Windows
6891 2000 English version of the message. */
6892 const char *reason = "No mapping for the Unicode character exists "
6893 "in the target code page.";
6894 /* each step cannot decode more than 1 character, but a character can be
6895 represented as a surrogate pair */
6896 wchar_t buffer[2], *startout, *out;
6897 int insize, outsize;
6898 PyObject *errorHandler = NULL;
6899 PyObject *exc = NULL;
6900 PyObject *encoding_obj = NULL;
6901 char *encoding;
6902 DWORD err;
6903 int ret = -1;
6904
6905 assert(size > 0);
6906
6907 encoding = code_page_name(code_page, &encoding_obj);
6908 if (encoding == NULL)
6909 return -1;
6910
6911 if (errors == NULL || strcmp(errors, "strict") == 0) {
6912 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6913 UnicodeDecodeError. */
6914 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6915 if (exc != NULL) {
6916 PyCodec_StrictErrors(exc);
6917 Py_CLEAR(exc);
6918 }
6919 goto error;
6920 }
6921
6922 if (*v == NULL) {
6923 /* Create unicode object */
6924 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6925 PyErr_NoMemory();
6926 goto error;
6927 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006928 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006929 if (*v == NULL)
6930 goto error;
6931 startout = PyUnicode_AS_UNICODE(*v);
6932 }
6933 else {
6934 /* Extend unicode object */
6935 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6936 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6937 PyErr_NoMemory();
6938 goto error;
6939 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006940 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006941 goto error;
6942 startout = PyUnicode_AS_UNICODE(*v) + n;
6943 }
6944
6945 /* Decode the byte string character per character */
6946 out = startout;
6947 while (in < endin)
6948 {
6949 /* Decode a character */
6950 insize = 1;
6951 do
6952 {
6953 outsize = MultiByteToWideChar(code_page, flags,
6954 in, insize,
6955 buffer, Py_ARRAY_LENGTH(buffer));
6956 if (outsize > 0)
6957 break;
6958 err = GetLastError();
6959 if (err != ERROR_NO_UNICODE_TRANSLATION
6960 && err != ERROR_INSUFFICIENT_BUFFER)
6961 {
6962 PyErr_SetFromWindowsErr(0);
6963 goto error;
6964 }
6965 insize++;
6966 }
6967 /* 4=maximum length of a UTF-8 sequence */
6968 while (insize <= 4 && (in + insize) <= endin);
6969
6970 if (outsize <= 0) {
6971 Py_ssize_t startinpos, endinpos, outpos;
6972
6973 startinpos = in - startin;
6974 endinpos = startinpos + 1;
6975 outpos = out - PyUnicode_AS_UNICODE(*v);
6976 if (unicode_decode_call_errorhandler(
6977 errors, &errorHandler,
6978 encoding, reason,
6979 &startin, &endin, &startinpos, &endinpos, &exc, &in,
6980 v, &outpos, &out))
6981 {
6982 goto error;
6983 }
6984 }
6985 else {
6986 in += insize;
6987 memcpy(out, buffer, outsize * sizeof(wchar_t));
6988 out += outsize;
6989 }
6990 }
6991
6992 /* write a NUL character at the end */
6993 *out = 0;
6994
6995 /* Extend unicode object */
6996 outsize = out - startout;
6997 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01006998 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006999 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007000 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007001
7002error:
7003 Py_XDECREF(encoding_obj);
7004 Py_XDECREF(errorHandler);
7005 Py_XDECREF(exc);
7006 return ret;
7007}
7008
Victor Stinner3a50e702011-10-18 21:21:00 +02007009static PyObject *
7010decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007011 const char *s, Py_ssize_t size,
7012 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007013{
Victor Stinner76a31a62011-11-04 00:05:13 +01007014 PyObject *v = NULL;
7015 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007016
Victor Stinner3a50e702011-10-18 21:21:00 +02007017 if (code_page < 0) {
7018 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7019 return NULL;
7020 }
7021
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007022 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007023 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007024
Victor Stinner76a31a62011-11-04 00:05:13 +01007025 do
7026 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007027#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007028 if (size > INT_MAX) {
7029 chunk_size = INT_MAX;
7030 final = 0;
7031 done = 0;
7032 }
7033 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007034#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007035 {
7036 chunk_size = (int)size;
7037 final = (consumed == NULL);
7038 done = 1;
7039 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007040
Victor Stinner76a31a62011-11-04 00:05:13 +01007041 /* Skip trailing lead-byte unless 'final' is set */
7042 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7043 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007044
Victor Stinner76a31a62011-11-04 00:05:13 +01007045 if (chunk_size == 0 && done) {
7046 if (v != NULL)
7047 break;
7048 Py_INCREF(unicode_empty);
7049 return unicode_empty;
7050 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007051
Victor Stinner76a31a62011-11-04 00:05:13 +01007052
7053 converted = decode_code_page_strict(code_page, &v,
7054 s, chunk_size);
7055 if (converted == -2)
7056 converted = decode_code_page_errors(code_page, &v,
7057 s, chunk_size,
7058 errors);
7059 assert(converted != 0);
7060
7061 if (converted < 0) {
7062 Py_XDECREF(v);
7063 return NULL;
7064 }
7065
7066 if (consumed)
7067 *consumed += converted;
7068
7069 s += converted;
7070 size -= converted;
7071 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007072
Victor Stinner17efeed2011-10-04 20:05:46 +02007073#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007074 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007075 Py_DECREF(v);
7076 return NULL;
7077 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007078#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007079 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007080 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007081}
7082
Alexander Belopolsky40018472011-02-26 01:02:56 +00007083PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007084PyUnicode_DecodeCodePageStateful(int code_page,
7085 const char *s,
7086 Py_ssize_t size,
7087 const char *errors,
7088 Py_ssize_t *consumed)
7089{
7090 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7091}
7092
7093PyObject *
7094PyUnicode_DecodeMBCSStateful(const char *s,
7095 Py_ssize_t size,
7096 const char *errors,
7097 Py_ssize_t *consumed)
7098{
7099 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7100}
7101
7102PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007103PyUnicode_DecodeMBCS(const char *s,
7104 Py_ssize_t size,
7105 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007106{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007107 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7108}
7109
Victor Stinner3a50e702011-10-18 21:21:00 +02007110static DWORD
7111encode_code_page_flags(UINT code_page, const char *errors)
7112{
7113 if (code_page == CP_UTF8) {
7114 if (winver.dwMajorVersion >= 6)
7115 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7116 and later */
7117 return WC_ERR_INVALID_CHARS;
7118 else
7119 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7120 return 0;
7121 }
7122 else if (code_page == CP_UTF7) {
7123 /* CP_UTF7 only supports flags=0 */
7124 return 0;
7125 }
7126 else {
7127 if (errors != NULL && strcmp(errors, "replace") == 0)
7128 return 0;
7129 else
7130 return WC_NO_BEST_FIT_CHARS;
7131 }
7132}
7133
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007134/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007135 * Encode a Unicode string to a Windows code page into a byte string in strict
7136 * mode.
7137 *
7138 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7139 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007140 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007141static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007142encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007143 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007144 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007145{
Victor Stinner554f3f02010-06-16 23:33:54 +00007146 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007147 BOOL *pusedDefaultChar = &usedDefaultChar;
7148 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007149 PyObject *exc = NULL;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007150 Py_UNICODE *p;
7151 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007152 const DWORD flags = encode_code_page_flags(code_page, NULL);
7153 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007154 /* Create a substring so that we can get the UTF-16 representation
7155 of just the slice under consideration. */
7156 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007157
Martin v. Löwis3d325192011-11-04 18:23:06 +01007158 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007159
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007161 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007162 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007163 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007164
Victor Stinner2fc507f2011-11-04 20:06:39 +01007165 substring = PyUnicode_Substring(unicode, offset, offset+len);
7166 if (substring == NULL)
7167 return -1;
7168 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7169 if (p == NULL) {
7170 Py_DECREF(substring);
7171 return -1;
7172 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007173
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007174 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007175 outsize = WideCharToMultiByte(code_page, flags,
7176 p, size,
7177 NULL, 0,
7178 NULL, pusedDefaultChar);
7179 if (outsize <= 0)
7180 goto error;
7181 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007182 if (pusedDefaultChar && *pusedDefaultChar) {
7183 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007184 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007185 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007186
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007188 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007189 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007190 if (*outbytes == NULL) {
7191 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007192 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007193 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007194 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007195 }
7196 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007197 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007198 const Py_ssize_t n = PyBytes_Size(*outbytes);
7199 if (outsize > PY_SSIZE_T_MAX - n) {
7200 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007201 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007202 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007203 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007204 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7205 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007206 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007207 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007208 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007209 }
7210
7211 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007212 outsize = WideCharToMultiByte(code_page, flags,
7213 p, size,
7214 out, outsize,
7215 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007216 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007217 if (outsize <= 0)
7218 goto error;
7219 if (pusedDefaultChar && *pusedDefaultChar)
7220 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007221 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007222
Victor Stinner3a50e702011-10-18 21:21:00 +02007223error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007224 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007225 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7226 return -2;
7227 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007228 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007229}
7230
Victor Stinner3a50e702011-10-18 21:21:00 +02007231/*
7232 * Encode a Unicode string to a Windows code page into a byte string using a
7233 * error handler.
7234 *
7235 * Returns consumed characters if succeed, or raise a WindowsError and returns
7236 * -1 on other error.
7237 */
7238static int
7239encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007240 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007241 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007242{
Victor Stinner3a50e702011-10-18 21:21:00 +02007243 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007244 Py_ssize_t pos = unicode_offset;
7245 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007246 /* Ideally, we should get reason from FormatMessage. This is the Windows
7247 2000 English version of the message. */
7248 const char *reason = "invalid character";
7249 /* 4=maximum length of a UTF-8 sequence */
7250 char buffer[4];
7251 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7252 Py_ssize_t outsize;
7253 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007254 PyObject *errorHandler = NULL;
7255 PyObject *exc = NULL;
7256 PyObject *encoding_obj = NULL;
7257 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007258 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007259 PyObject *rep;
7260 int ret = -1;
7261
7262 assert(insize > 0);
7263
7264 encoding = code_page_name(code_page, &encoding_obj);
7265 if (encoding == NULL)
7266 return -1;
7267
7268 if (errors == NULL || strcmp(errors, "strict") == 0) {
7269 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7270 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007271 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007272 if (exc != NULL) {
7273 PyCodec_StrictErrors(exc);
7274 Py_DECREF(exc);
7275 }
7276 Py_XDECREF(encoding_obj);
7277 return -1;
7278 }
7279
7280 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7281 pusedDefaultChar = &usedDefaultChar;
7282 else
7283 pusedDefaultChar = NULL;
7284
7285 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7286 PyErr_NoMemory();
7287 goto error;
7288 }
7289 outsize = insize * Py_ARRAY_LENGTH(buffer);
7290
7291 if (*outbytes == NULL) {
7292 /* Create string object */
7293 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7294 if (*outbytes == NULL)
7295 goto error;
7296 out = PyBytes_AS_STRING(*outbytes);
7297 }
7298 else {
7299 /* Extend string object */
7300 Py_ssize_t n = PyBytes_Size(*outbytes);
7301 if (n > PY_SSIZE_T_MAX - outsize) {
7302 PyErr_NoMemory();
7303 goto error;
7304 }
7305 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7306 goto error;
7307 out = PyBytes_AS_STRING(*outbytes) + n;
7308 }
7309
7310 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007311 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007312 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007313 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7314 wchar_t chars[2];
7315 int charsize;
7316 if (ch < 0x10000) {
7317 chars[0] = (wchar_t)ch;
7318 charsize = 1;
7319 }
7320 else {
7321 ch -= 0x10000;
7322 chars[0] = 0xd800 + (ch >> 10);
7323 chars[1] = 0xdc00 + (ch & 0x3ff);
7324 charsize = 2;
7325 }
7326
Victor Stinner3a50e702011-10-18 21:21:00 +02007327 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007328 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007329 buffer, Py_ARRAY_LENGTH(buffer),
7330 NULL, pusedDefaultChar);
7331 if (outsize > 0) {
7332 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7333 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007334 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007335 memcpy(out, buffer, outsize);
7336 out += outsize;
7337 continue;
7338 }
7339 }
7340 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7341 PyErr_SetFromWindowsErr(0);
7342 goto error;
7343 }
7344
Victor Stinner3a50e702011-10-18 21:21:00 +02007345 rep = unicode_encode_call_errorhandler(
7346 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007347 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007348 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007349 if (rep == NULL)
7350 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007351 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007352
7353 if (PyBytes_Check(rep)) {
7354 outsize = PyBytes_GET_SIZE(rep);
7355 if (outsize != 1) {
7356 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7357 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7358 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7359 Py_DECREF(rep);
7360 goto error;
7361 }
7362 out = PyBytes_AS_STRING(*outbytes) + offset;
7363 }
7364 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7365 out += outsize;
7366 }
7367 else {
7368 Py_ssize_t i;
7369 enum PyUnicode_Kind kind;
7370 void *data;
7371
7372 if (PyUnicode_READY(rep) < 0) {
7373 Py_DECREF(rep);
7374 goto error;
7375 }
7376
7377 outsize = PyUnicode_GET_LENGTH(rep);
7378 if (outsize != 1) {
7379 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7380 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7381 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7382 Py_DECREF(rep);
7383 goto error;
7384 }
7385 out = PyBytes_AS_STRING(*outbytes) + offset;
7386 }
7387 kind = PyUnicode_KIND(rep);
7388 data = PyUnicode_DATA(rep);
7389 for (i=0; i < outsize; i++) {
7390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7391 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007392 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007393 encoding, unicode,
7394 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007395 "unable to encode error handler result to ASCII");
7396 Py_DECREF(rep);
7397 goto error;
7398 }
7399 *out = (unsigned char)ch;
7400 out++;
7401 }
7402 }
7403 Py_DECREF(rep);
7404 }
7405 /* write a NUL byte */
7406 *out = 0;
7407 outsize = out - PyBytes_AS_STRING(*outbytes);
7408 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7409 if (_PyBytes_Resize(outbytes, outsize) < 0)
7410 goto error;
7411 ret = 0;
7412
7413error:
7414 Py_XDECREF(encoding_obj);
7415 Py_XDECREF(errorHandler);
7416 Py_XDECREF(exc);
7417 return ret;
7418}
7419
Victor Stinner3a50e702011-10-18 21:21:00 +02007420static PyObject *
7421encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007422 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007423 const char *errors)
7424{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007425 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007426 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007427 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007428 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007429
Victor Stinner2fc507f2011-11-04 20:06:39 +01007430 if (PyUnicode_READY(unicode) < 0)
7431 return NULL;
7432 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007433
Victor Stinner3a50e702011-10-18 21:21:00 +02007434 if (code_page < 0) {
7435 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7436 return NULL;
7437 }
7438
Martin v. Löwis3d325192011-11-04 18:23:06 +01007439 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007440 return PyBytes_FromStringAndSize(NULL, 0);
7441
Victor Stinner7581cef2011-11-03 22:32:33 +01007442 offset = 0;
7443 do
7444 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007445#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007446 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007447 chunks. */
7448 if (len > INT_MAX/2) {
7449 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007450 done = 0;
7451 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007452 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007453#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007454 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007455 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007456 done = 1;
7457 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007458
Victor Stinner76a31a62011-11-04 00:05:13 +01007459 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007460 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007461 errors);
7462 if (ret == -2)
7463 ret = encode_code_page_errors(code_page, &outbytes,
7464 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007465 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007466 if (ret < 0) {
7467 Py_XDECREF(outbytes);
7468 return NULL;
7469 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007470
Victor Stinner7581cef2011-11-03 22:32:33 +01007471 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007473 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007474
Victor Stinner3a50e702011-10-18 21:21:00 +02007475 return outbytes;
7476}
7477
7478PyObject *
7479PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7480 Py_ssize_t size,
7481 const char *errors)
7482{
Victor Stinner7581cef2011-11-03 22:32:33 +01007483 PyObject *unicode, *res;
7484 unicode = PyUnicode_FromUnicode(p, size);
7485 if (unicode == NULL)
7486 return NULL;
7487 res = encode_code_page(CP_ACP, unicode, errors);
7488 Py_DECREF(unicode);
7489 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007490}
7491
7492PyObject *
7493PyUnicode_EncodeCodePage(int code_page,
7494 PyObject *unicode,
7495 const char *errors)
7496{
Victor Stinner7581cef2011-11-03 22:32:33 +01007497 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007498}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007499
Alexander Belopolsky40018472011-02-26 01:02:56 +00007500PyObject *
7501PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007502{
7503 if (!PyUnicode_Check(unicode)) {
7504 PyErr_BadArgument();
7505 return NULL;
7506 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007507 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007508}
7509
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007510#undef NEED_RETRY
7511
Victor Stinner99b95382011-07-04 14:23:54 +02007512#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007513
Guido van Rossumd57fd912000-03-10 22:53:23 +00007514/* --- Character Mapping Codec -------------------------------------------- */
7515
Alexander Belopolsky40018472011-02-26 01:02:56 +00007516PyObject *
7517PyUnicode_DecodeCharmap(const char *s,
7518 Py_ssize_t size,
7519 PyObject *mapping,
7520 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007521{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007522 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007523 Py_ssize_t startinpos;
7524 Py_ssize_t endinpos;
7525 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007526 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007527 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007528 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007529 PyObject *errorHandler = NULL;
7530 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007531 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007532 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007533
Guido van Rossumd57fd912000-03-10 22:53:23 +00007534 /* Default to Latin-1 */
7535 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007536 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007537
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007538 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007540 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007541 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007542 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007543 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007544 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007545 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007546 mapstring = PyUnicode_AS_UNICODE(mapping);
7547 maplen = PyUnicode_GET_SIZE(mapping);
7548 while (s < e) {
7549 unsigned char ch = *s;
7550 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007551
Benjamin Peterson29060642009-01-31 22:14:21 +00007552 if (ch < maplen)
7553 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007554
Benjamin Peterson29060642009-01-31 22:14:21 +00007555 if (x == 0xfffe) {
7556 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007557 startinpos = s-starts;
7558 endinpos = startinpos+1;
7559 if (unicode_decode_call_errorhandler(
7560 errors, &errorHandler,
7561 "charmap", "character maps to <undefined>",
7562 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007563 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007564 goto onError;
7565 }
7566 continue;
7567 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007568 if (unicode_putchar(&v, &outpos, x) < 0)
7569 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007570 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007571 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007572 }
7573 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007574 while (s < e) {
7575 unsigned char ch = *s;
7576 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007577
Benjamin Peterson29060642009-01-31 22:14:21 +00007578 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7579 w = PyLong_FromLong((long)ch);
7580 if (w == NULL)
7581 goto onError;
7582 x = PyObject_GetItem(mapping, w);
7583 Py_DECREF(w);
7584 if (x == NULL) {
7585 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7586 /* No mapping found means: mapping is undefined. */
7587 PyErr_Clear();
7588 x = Py_None;
7589 Py_INCREF(x);
7590 } else
7591 goto onError;
7592 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007593
Benjamin Peterson29060642009-01-31 22:14:21 +00007594 /* Apply mapping */
7595 if (PyLong_Check(x)) {
7596 long value = PyLong_AS_LONG(x);
7597 if (value < 0 || value > 65535) {
7598 PyErr_SetString(PyExc_TypeError,
7599 "character mapping must be in range(65536)");
7600 Py_DECREF(x);
7601 goto onError;
7602 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007603 if (unicode_putchar(&v, &outpos, value) < 0)
7604 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007605 }
7606 else if (x == Py_None) {
7607 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007608 startinpos = s-starts;
7609 endinpos = startinpos+1;
7610 if (unicode_decode_call_errorhandler(
7611 errors, &errorHandler,
7612 "charmap", "character maps to <undefined>",
7613 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007614 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007615 Py_DECREF(x);
7616 goto onError;
7617 }
7618 Py_DECREF(x);
7619 continue;
7620 }
7621 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007622 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007623
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007624 if (PyUnicode_READY(x) < 0)
7625 goto onError;
7626 targetsize = PyUnicode_GET_LENGTH(x);
7627
7628 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007629 /* 1-1 mapping */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007630 if (unicode_putchar(&v, &outpos,
7631 PyUnicode_READ_CHAR(x, 0)) < 0)
7632 goto onError;
7633 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007634 else if (targetsize > 1) {
7635 /* 1-n mapping */
7636 if (targetsize > extrachars) {
7637 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007638 Py_ssize_t needed = (targetsize - extrachars) + \
7639 (targetsize << 2);
7640 extrachars += needed;
7641 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007642 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007643 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007644 Py_DECREF(x);
7645 goto onError;
7646 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007647 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007648 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7649 goto onError;
7650 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7651 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007652 extrachars -= targetsize;
7653 }
7654 /* 1-0 mapping: skip the character */
7655 }
7656 else {
7657 /* wrong return value */
7658 PyErr_SetString(PyExc_TypeError,
7659 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007660 Py_DECREF(x);
7661 goto onError;
7662 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007663 Py_DECREF(x);
7664 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007665 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007666 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007667 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007668 Py_XDECREF(errorHandler);
7669 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007670 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007671 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007672
Benjamin Peterson29060642009-01-31 22:14:21 +00007673 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007674 Py_XDECREF(errorHandler);
7675 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007676 Py_XDECREF(v);
7677 return NULL;
7678}
7679
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007680/* Charmap encoding: the lookup table */
7681
Alexander Belopolsky40018472011-02-26 01:02:56 +00007682struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007683 PyObject_HEAD
7684 unsigned char level1[32];
7685 int count2, count3;
7686 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007687};
7688
7689static PyObject*
7690encoding_map_size(PyObject *obj, PyObject* args)
7691{
7692 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007693 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007694 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007695}
7696
7697static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007698 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007699 PyDoc_STR("Return the size (in bytes) of this object") },
7700 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007701};
7702
7703static void
7704encoding_map_dealloc(PyObject* o)
7705{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007706 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007707}
7708
7709static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007710 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007711 "EncodingMap", /*tp_name*/
7712 sizeof(struct encoding_map), /*tp_basicsize*/
7713 0, /*tp_itemsize*/
7714 /* methods */
7715 encoding_map_dealloc, /*tp_dealloc*/
7716 0, /*tp_print*/
7717 0, /*tp_getattr*/
7718 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007719 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 0, /*tp_repr*/
7721 0, /*tp_as_number*/
7722 0, /*tp_as_sequence*/
7723 0, /*tp_as_mapping*/
7724 0, /*tp_hash*/
7725 0, /*tp_call*/
7726 0, /*tp_str*/
7727 0, /*tp_getattro*/
7728 0, /*tp_setattro*/
7729 0, /*tp_as_buffer*/
7730 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7731 0, /*tp_doc*/
7732 0, /*tp_traverse*/
7733 0, /*tp_clear*/
7734 0, /*tp_richcompare*/
7735 0, /*tp_weaklistoffset*/
7736 0, /*tp_iter*/
7737 0, /*tp_iternext*/
7738 encoding_map_methods, /*tp_methods*/
7739 0, /*tp_members*/
7740 0, /*tp_getset*/
7741 0, /*tp_base*/
7742 0, /*tp_dict*/
7743 0, /*tp_descr_get*/
7744 0, /*tp_descr_set*/
7745 0, /*tp_dictoffset*/
7746 0, /*tp_init*/
7747 0, /*tp_alloc*/
7748 0, /*tp_new*/
7749 0, /*tp_free*/
7750 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007751};
7752
7753PyObject*
7754PyUnicode_BuildEncodingMap(PyObject* string)
7755{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007756 PyObject *result;
7757 struct encoding_map *mresult;
7758 int i;
7759 int need_dict = 0;
7760 unsigned char level1[32];
7761 unsigned char level2[512];
7762 unsigned char *mlevel1, *mlevel2, *mlevel3;
7763 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007764 int kind;
7765 void *data;
7766 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007767
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007768 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007769 PyErr_BadArgument();
7770 return NULL;
7771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007772 kind = PyUnicode_KIND(string);
7773 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007774 memset(level1, 0xFF, sizeof level1);
7775 memset(level2, 0xFF, sizeof level2);
7776
7777 /* If there isn't a one-to-one mapping of NULL to \0,
7778 or if there are non-BMP characters, we need to use
7779 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007780 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007781 need_dict = 1;
7782 for (i = 1; i < 256; i++) {
7783 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007784 ch = PyUnicode_READ(kind, data, i);
7785 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007786 need_dict = 1;
7787 break;
7788 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007789 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007790 /* unmapped character */
7791 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007792 l1 = ch >> 11;
7793 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007794 if (level1[l1] == 0xFF)
7795 level1[l1] = count2++;
7796 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007797 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007798 }
7799
7800 if (count2 >= 0xFF || count3 >= 0xFF)
7801 need_dict = 1;
7802
7803 if (need_dict) {
7804 PyObject *result = PyDict_New();
7805 PyObject *key, *value;
7806 if (!result)
7807 return NULL;
7808 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007809 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007810 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007811 if (!key || !value)
7812 goto failed1;
7813 if (PyDict_SetItem(result, key, value) == -1)
7814 goto failed1;
7815 Py_DECREF(key);
7816 Py_DECREF(value);
7817 }
7818 return result;
7819 failed1:
7820 Py_XDECREF(key);
7821 Py_XDECREF(value);
7822 Py_DECREF(result);
7823 return NULL;
7824 }
7825
7826 /* Create a three-level trie */
7827 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7828 16*count2 + 128*count3 - 1);
7829 if (!result)
7830 return PyErr_NoMemory();
7831 PyObject_Init(result, &EncodingMapType);
7832 mresult = (struct encoding_map*)result;
7833 mresult->count2 = count2;
7834 mresult->count3 = count3;
7835 mlevel1 = mresult->level1;
7836 mlevel2 = mresult->level23;
7837 mlevel3 = mresult->level23 + 16*count2;
7838 memcpy(mlevel1, level1, 32);
7839 memset(mlevel2, 0xFF, 16*count2);
7840 memset(mlevel3, 0, 128*count3);
7841 count3 = 0;
7842 for (i = 1; i < 256; i++) {
7843 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007844 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007845 /* unmapped character */
7846 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007847 o1 = PyUnicode_READ(kind, data, i)>>11;
7848 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007849 i2 = 16*mlevel1[o1] + o2;
7850 if (mlevel2[i2] == 0xFF)
7851 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007852 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007853 i3 = 128*mlevel2[i2] + o3;
7854 mlevel3[i3] = i;
7855 }
7856 return result;
7857}
7858
7859static int
7860encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7861{
7862 struct encoding_map *map = (struct encoding_map*)mapping;
7863 int l1 = c>>11;
7864 int l2 = (c>>7) & 0xF;
7865 int l3 = c & 0x7F;
7866 int i;
7867
7868#ifdef Py_UNICODE_WIDE
7869 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007870 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871 }
7872#endif
7873 if (c == 0)
7874 return 0;
7875 /* level 1*/
7876 i = map->level1[l1];
7877 if (i == 0xFF) {
7878 return -1;
7879 }
7880 /* level 2*/
7881 i = map->level23[16*i+l2];
7882 if (i == 0xFF) {
7883 return -1;
7884 }
7885 /* level 3 */
7886 i = map->level23[16*map->count2 + 128*i + l3];
7887 if (i == 0) {
7888 return -1;
7889 }
7890 return i;
7891}
7892
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007893/* Lookup the character ch in the mapping. If the character
7894 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007895 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007896static PyObject *
7897charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007898{
Christian Heimes217cfd12007-12-02 14:31:20 +00007899 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007900 PyObject *x;
7901
7902 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007903 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007904 x = PyObject_GetItem(mapping, w);
7905 Py_DECREF(w);
7906 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007907 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7908 /* No mapping found means: mapping is undefined. */
7909 PyErr_Clear();
7910 x = Py_None;
7911 Py_INCREF(x);
7912 return x;
7913 } else
7914 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007915 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007916 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007917 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007918 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007919 long value = PyLong_AS_LONG(x);
7920 if (value < 0 || value > 255) {
7921 PyErr_SetString(PyExc_TypeError,
7922 "character mapping must be in range(256)");
7923 Py_DECREF(x);
7924 return NULL;
7925 }
7926 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007927 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007928 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007929 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007930 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007931 /* wrong return value */
7932 PyErr_Format(PyExc_TypeError,
7933 "character mapping must return integer, bytes or None, not %.400s",
7934 x->ob_type->tp_name);
7935 Py_DECREF(x);
7936 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007937 }
7938}
7939
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007940static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007941charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007942{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007943 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7944 /* exponentially overallocate to minimize reallocations */
7945 if (requiredsize < 2*outsize)
7946 requiredsize = 2*outsize;
7947 if (_PyBytes_Resize(outobj, requiredsize))
7948 return -1;
7949 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007950}
7951
Benjamin Peterson14339b62009-01-31 16:36:08 +00007952typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007953 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007954} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007955/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007956 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007957 space is available. Return a new reference to the object that
7958 was put in the output buffer, or Py_None, if the mapping was undefined
7959 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007960 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007961static charmapencode_result
7962charmapencode_output(Py_UNICODE c, PyObject *mapping,
7963 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007964{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007965 PyObject *rep;
7966 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007967 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007968
Christian Heimes90aa7642007-12-19 02:45:37 +00007969 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007970 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007971 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007972 if (res == -1)
7973 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00007974 if (outsize<requiredsize)
7975 if (charmapencode_resize(outobj, outpos, requiredsize))
7976 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00007977 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007978 outstart[(*outpos)++] = (char)res;
7979 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007980 }
7981
7982 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007983 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007984 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007985 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007986 Py_DECREF(rep);
7987 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007988 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007989 if (PyLong_Check(rep)) {
7990 Py_ssize_t requiredsize = *outpos+1;
7991 if (outsize<requiredsize)
7992 if (charmapencode_resize(outobj, outpos, requiredsize)) {
7993 Py_DECREF(rep);
7994 return enc_EXCEPTION;
7995 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007996 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00007998 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007999 else {
8000 const char *repchars = PyBytes_AS_STRING(rep);
8001 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8002 Py_ssize_t requiredsize = *outpos+repsize;
8003 if (outsize<requiredsize)
8004 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8005 Py_DECREF(rep);
8006 return enc_EXCEPTION;
8007 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008008 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008009 memcpy(outstart + *outpos, repchars, repsize);
8010 *outpos += repsize;
8011 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008012 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008013 Py_DECREF(rep);
8014 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008015}
8016
8017/* handle an error in PyUnicode_EncodeCharmap
8018 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008019static int
8020charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008021 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008022 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008023 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008024 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008025{
8026 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008027 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008028 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008029 Py_UNICODE *uni2;
8030 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008031 Py_ssize_t collstartpos = *inpos;
8032 Py_ssize_t collendpos = *inpos+1;
8033 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008034 char *encoding = "charmap";
8035 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008036 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008037 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008038 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008039
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008040 if (PyUnicode_READY(unicode) < 0)
8041 return -1;
8042 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008043 /* find all unencodable characters */
8044 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008045 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008046 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008047 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008048 val = encoding_map_lookup(ch, mapping);
8049 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008050 break;
8051 ++collendpos;
8052 continue;
8053 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008054
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008055 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8056 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008057 if (rep==NULL)
8058 return -1;
8059 else if (rep!=Py_None) {
8060 Py_DECREF(rep);
8061 break;
8062 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008063 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008064 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065 }
8066 /* cache callback name lookup
8067 * (if not done yet, i.e. it's the first error) */
8068 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008069 if ((errors==NULL) || (!strcmp(errors, "strict")))
8070 *known_errorHandler = 1;
8071 else if (!strcmp(errors, "replace"))
8072 *known_errorHandler = 2;
8073 else if (!strcmp(errors, "ignore"))
8074 *known_errorHandler = 3;
8075 else if (!strcmp(errors, "xmlcharrefreplace"))
8076 *known_errorHandler = 4;
8077 else
8078 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008079 }
8080 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008081 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008082 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008083 return -1;
8084 case 2: /* replace */
8085 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008086 x = charmapencode_output('?', mapping, res, respos);
8087 if (x==enc_EXCEPTION) {
8088 return -1;
8089 }
8090 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008091 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008092 return -1;
8093 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008094 }
8095 /* fall through */
8096 case 3: /* ignore */
8097 *inpos = collendpos;
8098 break;
8099 case 4: /* xmlcharrefreplace */
8100 /* generate replacement (temporarily (mis)uses p) */
8101 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008102 char buffer[2+29+1+1];
8103 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008104 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008105 for (cp = buffer; *cp; ++cp) {
8106 x = charmapencode_output(*cp, mapping, res, respos);
8107 if (x==enc_EXCEPTION)
8108 return -1;
8109 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008110 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008111 return -1;
8112 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008113 }
8114 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008115 *inpos = collendpos;
8116 break;
8117 default:
8118 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008119 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008120 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008121 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008122 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008123 if (PyBytes_Check(repunicode)) {
8124 /* Directly copy bytes result to output. */
8125 Py_ssize_t outsize = PyBytes_Size(*res);
8126 Py_ssize_t requiredsize;
8127 repsize = PyBytes_Size(repunicode);
8128 requiredsize = *respos + repsize;
8129 if (requiredsize > outsize)
8130 /* Make room for all additional bytes. */
8131 if (charmapencode_resize(res, respos, requiredsize)) {
8132 Py_DECREF(repunicode);
8133 return -1;
8134 }
8135 memcpy(PyBytes_AsString(*res) + *respos,
8136 PyBytes_AsString(repunicode), repsize);
8137 *respos += repsize;
8138 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008139 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008140 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008141 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008142 /* generate replacement */
8143 repsize = PyUnicode_GET_SIZE(repunicode);
8144 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008145 x = charmapencode_output(*uni2, mapping, res, respos);
8146 if (x==enc_EXCEPTION) {
8147 return -1;
8148 }
8149 else if (x==enc_FAILED) {
8150 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008151 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008152 return -1;
8153 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008154 }
8155 *inpos = newpos;
8156 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008157 }
8158 return 0;
8159}
8160
Alexander Belopolsky40018472011-02-26 01:02:56 +00008161PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008162_PyUnicode_EncodeCharmap(PyObject *unicode,
8163 PyObject *mapping,
8164 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008165{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008166 /* output object */
8167 PyObject *res = NULL;
8168 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008169 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008170 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008171 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008172 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008173 PyObject *errorHandler = NULL;
8174 PyObject *exc = NULL;
8175 /* the following variable is used for caching string comparisons
8176 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8177 * 3=ignore, 4=xmlcharrefreplace */
8178 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008179
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008180 if (PyUnicode_READY(unicode) < 0)
8181 return NULL;
8182 size = PyUnicode_GET_LENGTH(unicode);
8183
Guido van Rossumd57fd912000-03-10 22:53:23 +00008184 /* Default to Latin-1 */
8185 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008186 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008187
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008188 /* allocate enough for a simple encoding without
8189 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008190 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008191 if (res == NULL)
8192 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008193 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008194 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008195
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008196 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008197 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008198 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008199 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008200 if (x==enc_EXCEPTION) /* error */
8201 goto onError;
8202 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008203 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008204 &exc,
8205 &known_errorHandler, &errorHandler, errors,
8206 &res, &respos)) {
8207 goto onError;
8208 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008209 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008210 else
8211 /* done with this character => adjust input position */
8212 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008213 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008214
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008215 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008216 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008217 if (_PyBytes_Resize(&res, respos) < 0)
8218 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008219
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008220 Py_XDECREF(exc);
8221 Py_XDECREF(errorHandler);
8222 return res;
8223
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008225 Py_XDECREF(res);
8226 Py_XDECREF(exc);
8227 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008228 return NULL;
8229}
8230
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008231/* Deprecated */
8232PyObject *
8233PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8234 Py_ssize_t size,
8235 PyObject *mapping,
8236 const char *errors)
8237{
8238 PyObject *result;
8239 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8240 if (unicode == NULL)
8241 return NULL;
8242 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8243 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008244 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008245}
8246
Alexander Belopolsky40018472011-02-26 01:02:56 +00008247PyObject *
8248PyUnicode_AsCharmapString(PyObject *unicode,
8249 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008250{
8251 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008252 PyErr_BadArgument();
8253 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008255 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008256}
8257
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008258/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008259static void
8260make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008261 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008262 Py_ssize_t startpos, Py_ssize_t endpos,
8263 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008264{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008265 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008266 *exceptionObject = _PyUnicodeTranslateError_Create(
8267 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008268 }
8269 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008270 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8271 goto onError;
8272 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8273 goto onError;
8274 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8275 goto onError;
8276 return;
8277 onError:
8278 Py_DECREF(*exceptionObject);
8279 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008280 }
8281}
8282
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008283/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008284static void
8285raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008286 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008287 Py_ssize_t startpos, Py_ssize_t endpos,
8288 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008289{
8290 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008291 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008292 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008293 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008294}
8295
8296/* error handling callback helper:
8297 build arguments, call the callback and check the arguments,
8298 put the result into newpos and return the replacement string, which
8299 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008300static PyObject *
8301unicode_translate_call_errorhandler(const char *errors,
8302 PyObject **errorHandler,
8303 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008304 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008305 Py_ssize_t startpos, Py_ssize_t endpos,
8306 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008307{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008308 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008310 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008311 PyObject *restuple;
8312 PyObject *resunicode;
8313
8314 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008315 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008316 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008317 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008318 }
8319
8320 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008321 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008322 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008323 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008324
8325 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008326 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008327 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008328 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008329 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008330 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008331 Py_DECREF(restuple);
8332 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333 }
8334 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008335 &resunicode, &i_newpos)) {
8336 Py_DECREF(restuple);
8337 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008338 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008339 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008340 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008341 else
8342 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008343 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008344 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8345 Py_DECREF(restuple);
8346 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008347 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348 Py_INCREF(resunicode);
8349 Py_DECREF(restuple);
8350 return resunicode;
8351}
8352
8353/* Lookup the character ch in the mapping and put the result in result,
8354 which must be decrefed by the caller.
8355 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008356static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008357charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008358{
Christian Heimes217cfd12007-12-02 14:31:20 +00008359 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008360 PyObject *x;
8361
8362 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008363 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 x = PyObject_GetItem(mapping, w);
8365 Py_DECREF(w);
8366 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008367 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8368 /* No mapping found means: use 1:1 mapping. */
8369 PyErr_Clear();
8370 *result = NULL;
8371 return 0;
8372 } else
8373 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374 }
8375 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008376 *result = x;
8377 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008378 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008379 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008380 long value = PyLong_AS_LONG(x);
8381 long max = PyUnicode_GetMax();
8382 if (value < 0 || value > max) {
8383 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008384 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008385 Py_DECREF(x);
8386 return -1;
8387 }
8388 *result = x;
8389 return 0;
8390 }
8391 else if (PyUnicode_Check(x)) {
8392 *result = x;
8393 return 0;
8394 }
8395 else {
8396 /* wrong return value */
8397 PyErr_SetString(PyExc_TypeError,
8398 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008399 Py_DECREF(x);
8400 return -1;
8401 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008402}
8403/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008404 if not reallocate and adjust various state variables.
8405 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008406static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008407charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008408 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008409{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008410 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008411 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008412 /* exponentially overallocate to minimize reallocations */
8413 if (requiredsize < 2 * oldsize)
8414 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008415 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8416 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008417 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008418 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008419 }
8420 return 0;
8421}
8422/* lookup the character, put the result in the output string and adjust
8423 various state variables. Return a new reference to the object that
8424 was put in the output buffer in *result, or Py_None, if the mapping was
8425 undefined (in which case no character was written).
8426 The called must decref result.
8427 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008428static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008429charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8430 PyObject *mapping, Py_UCS4 **output,
8431 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008432 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008433{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008434 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8435 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008436 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008437 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008439 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008440 }
8441 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008442 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008443 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008444 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008445 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008446 }
8447 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008448 Py_ssize_t repsize;
8449 if (PyUnicode_READY(*res) == -1)
8450 return -1;
8451 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008452 if (repsize==1) {
8453 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008454 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008455 }
8456 else if (repsize!=0) {
8457 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008458 Py_ssize_t requiredsize = *opos +
8459 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008460 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008461 Py_ssize_t i;
8462 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008463 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008464 for(i = 0; i < repsize; i++)
8465 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008466 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008467 }
8468 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008469 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008470 return 0;
8471}
8472
Alexander Belopolsky40018472011-02-26 01:02:56 +00008473PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008474_PyUnicode_TranslateCharmap(PyObject *input,
8475 PyObject *mapping,
8476 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008477{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008478 /* input object */
8479 char *idata;
8480 Py_ssize_t size, i;
8481 int kind;
8482 /* output buffer */
8483 Py_UCS4 *output = NULL;
8484 Py_ssize_t osize;
8485 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008486 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008487 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008488 char *reason = "character maps to <undefined>";
8489 PyObject *errorHandler = NULL;
8490 PyObject *exc = NULL;
8491 /* the following variable is used for caching string comparisons
8492 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8493 * 3=ignore, 4=xmlcharrefreplace */
8494 int known_errorHandler = -1;
8495
Guido van Rossumd57fd912000-03-10 22:53:23 +00008496 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008497 PyErr_BadArgument();
8498 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008499 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008500
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008501 if (PyUnicode_READY(input) == -1)
8502 return NULL;
8503 idata = (char*)PyUnicode_DATA(input);
8504 kind = PyUnicode_KIND(input);
8505 size = PyUnicode_GET_LENGTH(input);
8506 i = 0;
8507
8508 if (size == 0) {
8509 Py_INCREF(input);
8510 return input;
8511 }
8512
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008513 /* allocate enough for a simple 1:1 translation without
8514 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008515 osize = size;
8516 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8517 opos = 0;
8518 if (output == NULL) {
8519 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008520 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008521 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008523 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008524 /* try to encode it */
8525 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008526 if (charmaptranslate_output(input, i, mapping,
8527 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008528 Py_XDECREF(x);
8529 goto onError;
8530 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008531 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008532 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008533 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008534 else { /* untranslatable character */
8535 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8536 Py_ssize_t repsize;
8537 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008538 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008539 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008540 Py_ssize_t collstart = i;
8541 Py_ssize_t collend = i+1;
8542 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008543
Benjamin Peterson29060642009-01-31 22:14:21 +00008544 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008545 while (collend < size) {
8546 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008547 goto onError;
8548 Py_XDECREF(x);
8549 if (x!=Py_None)
8550 break;
8551 ++collend;
8552 }
8553 /* cache callback name lookup
8554 * (if not done yet, i.e. it's the first error) */
8555 if (known_errorHandler==-1) {
8556 if ((errors==NULL) || (!strcmp(errors, "strict")))
8557 known_errorHandler = 1;
8558 else if (!strcmp(errors, "replace"))
8559 known_errorHandler = 2;
8560 else if (!strcmp(errors, "ignore"))
8561 known_errorHandler = 3;
8562 else if (!strcmp(errors, "xmlcharrefreplace"))
8563 known_errorHandler = 4;
8564 else
8565 known_errorHandler = 0;
8566 }
8567 switch (known_errorHandler) {
8568 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008569 raise_translate_exception(&exc, input, collstart,
8570 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008571 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008572 case 2: /* replace */
8573 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008574 for (coll = collstart; coll<collend; coll++)
8575 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008576 /* fall through */
8577 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008578 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008579 break;
8580 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008581 /* generate replacement (temporarily (mis)uses i) */
8582 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008583 char buffer[2+29+1+1];
8584 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008585 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8586 if (charmaptranslate_makespace(&output, &osize,
8587 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008588 goto onError;
8589 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008590 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008591 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008592 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008593 break;
8594 default:
8595 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008596 reason, input, &exc,
8597 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008598 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008599 goto onError;
8600 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008601 repsize = PyUnicode_GET_LENGTH(repunicode);
8602 if (charmaptranslate_makespace(&output, &osize,
8603 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008604 Py_DECREF(repunicode);
8605 goto onError;
8606 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 for (uni2 = 0; repsize-->0; ++uni2)
8608 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8609 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008610 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008611 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008612 }
8613 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008614 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8615 if (!res)
8616 goto onError;
8617 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008618 Py_XDECREF(exc);
8619 Py_XDECREF(errorHandler);
8620 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008621
Benjamin Peterson29060642009-01-31 22:14:21 +00008622 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008623 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008624 Py_XDECREF(exc);
8625 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008626 return NULL;
8627}
8628
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008629/* Deprecated. Use PyUnicode_Translate instead. */
8630PyObject *
8631PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8632 Py_ssize_t size,
8633 PyObject *mapping,
8634 const char *errors)
8635{
8636 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8637 if (!unicode)
8638 return NULL;
8639 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8640}
8641
Alexander Belopolsky40018472011-02-26 01:02:56 +00008642PyObject *
8643PyUnicode_Translate(PyObject *str,
8644 PyObject *mapping,
8645 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008646{
8647 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008648
Guido van Rossumd57fd912000-03-10 22:53:23 +00008649 str = PyUnicode_FromObject(str);
8650 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008651 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008652 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008653 Py_DECREF(str);
8654 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008655
Benjamin Peterson29060642009-01-31 22:14:21 +00008656 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008657 Py_XDECREF(str);
8658 return NULL;
8659}
Tim Petersced69f82003-09-16 20:30:58 +00008660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008661static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008662fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008663{
8664 /* No need to call PyUnicode_READY(self) because this function is only
8665 called as a callback from fixup() which does it already. */
8666 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8667 const int kind = PyUnicode_KIND(self);
8668 void *data = PyUnicode_DATA(self);
8669 Py_UCS4 maxchar = 0, ch, fixed;
8670 Py_ssize_t i;
8671
8672 for (i = 0; i < len; ++i) {
8673 ch = PyUnicode_READ(kind, data, i);
8674 fixed = 0;
8675 if (ch > 127) {
8676 if (Py_UNICODE_ISSPACE(ch))
8677 fixed = ' ';
8678 else {
8679 const int decimal = Py_UNICODE_TODECIMAL(ch);
8680 if (decimal >= 0)
8681 fixed = '0' + decimal;
8682 }
8683 if (fixed != 0) {
8684 if (fixed > maxchar)
8685 maxchar = fixed;
8686 PyUnicode_WRITE(kind, data, i, fixed);
8687 }
8688 else if (ch > maxchar)
8689 maxchar = ch;
8690 }
8691 else if (ch > maxchar)
8692 maxchar = ch;
8693 }
8694
8695 return maxchar;
8696}
8697
8698PyObject *
8699_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8700{
8701 if (!PyUnicode_Check(unicode)) {
8702 PyErr_BadInternalCall();
8703 return NULL;
8704 }
8705 if (PyUnicode_READY(unicode) == -1)
8706 return NULL;
8707 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8708 /* If the string is already ASCII, just return the same string */
8709 Py_INCREF(unicode);
8710 return unicode;
8711 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008712 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008713}
8714
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008715PyObject *
8716PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8717 Py_ssize_t length)
8718{
8719 PyObject *result;
8720 Py_UNICODE *p; /* write pointer into result */
8721 Py_ssize_t i;
8722 /* Copy to a new string */
8723 result = (PyObject *)_PyUnicode_New(length);
8724 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8725 if (result == NULL)
8726 return result;
8727 p = PyUnicode_AS_UNICODE(result);
8728 /* Iterate over code points */
8729 for (i = 0; i < length; i++) {
8730 Py_UNICODE ch =s[i];
8731 if (ch > 127) {
8732 int decimal = Py_UNICODE_TODECIMAL(ch);
8733 if (decimal >= 0)
8734 p[i] = '0' + decimal;
8735 }
8736 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008737#ifndef DONT_MAKE_RESULT_READY
8738 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739 Py_DECREF(result);
8740 return NULL;
8741 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008742#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008743 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008744 return result;
8745}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008746/* --- Decimal Encoder ---------------------------------------------------- */
8747
Alexander Belopolsky40018472011-02-26 01:02:56 +00008748int
8749PyUnicode_EncodeDecimal(Py_UNICODE *s,
8750 Py_ssize_t length,
8751 char *output,
8752 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008753{
8754 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008755 PyObject *errorHandler = NULL;
8756 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008757 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008758 const char *encoding = "decimal";
8759 const char *reason = "invalid decimal Unicode string";
8760 /* the following variable is used for caching string comparisons
8761 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8762 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008763
8764 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008765 PyErr_BadArgument();
8766 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008767 }
8768
8769 p = s;
8770 end = s + length;
8771 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008772 register Py_UNICODE ch = *p;
8773 int decimal;
8774 PyObject *repunicode;
8775 Py_ssize_t repsize;
8776 Py_ssize_t newpos;
8777 Py_UNICODE *uni2;
8778 Py_UNICODE *collstart;
8779 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008780
Benjamin Peterson29060642009-01-31 22:14:21 +00008781 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008782 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008783 ++p;
8784 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008785 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008786 decimal = Py_UNICODE_TODECIMAL(ch);
8787 if (decimal >= 0) {
8788 *output++ = '0' + decimal;
8789 ++p;
8790 continue;
8791 }
8792 if (0 < ch && ch < 256) {
8793 *output++ = (char)ch;
8794 ++p;
8795 continue;
8796 }
8797 /* All other characters are considered unencodable */
8798 collstart = p;
8799 collend = p+1;
8800 while (collend < end) {
8801 if ((0 < *collend && *collend < 256) ||
8802 !Py_UNICODE_ISSPACE(*collend) ||
8803 Py_UNICODE_TODECIMAL(*collend))
8804 break;
8805 }
8806 /* cache callback name lookup
8807 * (if not done yet, i.e. it's the first error) */
8808 if (known_errorHandler==-1) {
8809 if ((errors==NULL) || (!strcmp(errors, "strict")))
8810 known_errorHandler = 1;
8811 else if (!strcmp(errors, "replace"))
8812 known_errorHandler = 2;
8813 else if (!strcmp(errors, "ignore"))
8814 known_errorHandler = 3;
8815 else if (!strcmp(errors, "xmlcharrefreplace"))
8816 known_errorHandler = 4;
8817 else
8818 known_errorHandler = 0;
8819 }
8820 switch (known_errorHandler) {
8821 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008822 unicode = PyUnicode_FromUnicode(s, length);
8823 if (unicode == NULL)
8824 goto onError;
8825 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8826 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008827 goto onError;
8828 case 2: /* replace */
8829 for (p = collstart; p < collend; ++p)
8830 *output++ = '?';
8831 /* fall through */
8832 case 3: /* ignore */
8833 p = collend;
8834 break;
8835 case 4: /* xmlcharrefreplace */
8836 /* generate replacement (temporarily (mis)uses p) */
8837 for (p = collstart; p < collend; ++p)
8838 output += sprintf(output, "&#%d;", (int)*p);
8839 p = collend;
8840 break;
8841 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008842 unicode = PyUnicode_FromUnicode(s, length);
8843 if (unicode == NULL)
8844 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008845 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008846 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008847 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008848 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008849 if (repunicode == NULL)
8850 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008851 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008852 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008853 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8854 Py_DECREF(repunicode);
8855 goto onError;
8856 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008857 /* generate replacement */
8858 repsize = PyUnicode_GET_SIZE(repunicode);
8859 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8860 Py_UNICODE ch = *uni2;
8861 if (Py_UNICODE_ISSPACE(ch))
8862 *output++ = ' ';
8863 else {
8864 decimal = Py_UNICODE_TODECIMAL(ch);
8865 if (decimal >= 0)
8866 *output++ = '0' + decimal;
8867 else if (0 < ch && ch < 256)
8868 *output++ = (char)ch;
8869 else {
8870 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008871 unicode = PyUnicode_FromUnicode(s, length);
8872 if (unicode == NULL)
8873 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008874 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008875 unicode, collstart-s, collend-s, reason);
8876 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008877 goto onError;
8878 }
8879 }
8880 }
8881 p = s + newpos;
8882 Py_DECREF(repunicode);
8883 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008884 }
8885 /* 0-terminate the output string */
8886 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008887 Py_XDECREF(exc);
8888 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008889 return 0;
8890
Benjamin Peterson29060642009-01-31 22:14:21 +00008891 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008892 Py_XDECREF(exc);
8893 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008894 return -1;
8895}
8896
Guido van Rossumd57fd912000-03-10 22:53:23 +00008897/* --- Helpers ------------------------------------------------------------ */
8898
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008899static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008900any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008901 Py_ssize_t start,
8902 Py_ssize_t end)
8903{
8904 int kind1, kind2, kind;
8905 void *buf1, *buf2;
8906 Py_ssize_t len1, len2, result;
8907
8908 kind1 = PyUnicode_KIND(s1);
8909 kind2 = PyUnicode_KIND(s2);
8910 kind = kind1 > kind2 ? kind1 : kind2;
8911 buf1 = PyUnicode_DATA(s1);
8912 buf2 = PyUnicode_DATA(s2);
8913 if (kind1 != kind)
8914 buf1 = _PyUnicode_AsKind(s1, kind);
8915 if (!buf1)
8916 return -2;
8917 if (kind2 != kind)
8918 buf2 = _PyUnicode_AsKind(s2, kind);
8919 if (!buf2) {
8920 if (kind1 != kind) PyMem_Free(buf1);
8921 return -2;
8922 }
8923 len1 = PyUnicode_GET_LENGTH(s1);
8924 len2 = PyUnicode_GET_LENGTH(s2);
8925
Victor Stinner794d5672011-10-10 03:21:36 +02008926 if (direction > 0) {
8927 switch(kind) {
8928 case PyUnicode_1BYTE_KIND:
8929 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8930 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8931 else
8932 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8933 break;
8934 case PyUnicode_2BYTE_KIND:
8935 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8936 break;
8937 case PyUnicode_4BYTE_KIND:
8938 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8939 break;
8940 default:
8941 assert(0); result = -2;
8942 }
8943 }
8944 else {
8945 switch(kind) {
8946 case PyUnicode_1BYTE_KIND:
8947 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8948 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8949 else
8950 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8951 break;
8952 case PyUnicode_2BYTE_KIND:
8953 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8954 break;
8955 case PyUnicode_4BYTE_KIND:
8956 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8957 break;
8958 default:
8959 assert(0); result = -2;
8960 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008961 }
8962
8963 if (kind1 != kind)
8964 PyMem_Free(buf1);
8965 if (kind2 != kind)
8966 PyMem_Free(buf2);
8967
8968 return result;
8969}
8970
8971Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008972_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008973 Py_ssize_t n_buffer,
8974 void *digits, Py_ssize_t n_digits,
8975 Py_ssize_t min_width,
8976 const char *grouping,
8977 const char *thousands_sep)
8978{
8979 switch(kind) {
8980 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02008981 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
8982 return _PyUnicode_ascii_InsertThousandsGrouping(
8983 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8984 min_width, grouping, thousands_sep);
8985 else
8986 return _PyUnicode_ucs1_InsertThousandsGrouping(
8987 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
8988 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008989 case PyUnicode_2BYTE_KIND:
8990 return _PyUnicode_ucs2_InsertThousandsGrouping(
8991 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
8992 min_width, grouping, thousands_sep);
8993 case PyUnicode_4BYTE_KIND:
8994 return _PyUnicode_ucs4_InsertThousandsGrouping(
8995 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
8996 min_width, grouping, thousands_sep);
8997 }
8998 assert(0);
8999 return -1;
9000}
9001
9002
Thomas Wouters477c8d52006-05-27 19:21:47 +00009003/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009004#define ADJUST_INDICES(start, end, len) \
9005 if (end > len) \
9006 end = len; \
9007 else if (end < 0) { \
9008 end += len; \
9009 if (end < 0) \
9010 end = 0; \
9011 } \
9012 if (start < 0) { \
9013 start += len; \
9014 if (start < 0) \
9015 start = 0; \
9016 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009017
Alexander Belopolsky40018472011-02-26 01:02:56 +00009018Py_ssize_t
9019PyUnicode_Count(PyObject *str,
9020 PyObject *substr,
9021 Py_ssize_t start,
9022 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009023{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009024 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009025 PyObject* str_obj;
9026 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009027 int kind1, kind2, kind;
9028 void *buf1 = NULL, *buf2 = NULL;
9029 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009030
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009031 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009032 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009033 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009034 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009035 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009036 Py_DECREF(str_obj);
9037 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009038 }
Tim Petersced69f82003-09-16 20:30:58 +00009039
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009040 kind1 = PyUnicode_KIND(str_obj);
9041 kind2 = PyUnicode_KIND(sub_obj);
9042 kind = kind1 > kind2 ? kind1 : kind2;
9043 buf1 = PyUnicode_DATA(str_obj);
9044 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009045 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009046 if (!buf1)
9047 goto onError;
9048 buf2 = PyUnicode_DATA(sub_obj);
9049 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009050 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009051 if (!buf2)
9052 goto onError;
9053 len1 = PyUnicode_GET_LENGTH(str_obj);
9054 len2 = PyUnicode_GET_LENGTH(sub_obj);
9055
9056 ADJUST_INDICES(start, end, len1);
9057 switch(kind) {
9058 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009059 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9060 result = asciilib_count(
9061 ((Py_UCS1*)buf1) + start, end - start,
9062 buf2, len2, PY_SSIZE_T_MAX
9063 );
9064 else
9065 result = ucs1lib_count(
9066 ((Py_UCS1*)buf1) + start, end - start,
9067 buf2, len2, PY_SSIZE_T_MAX
9068 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009069 break;
9070 case PyUnicode_2BYTE_KIND:
9071 result = ucs2lib_count(
9072 ((Py_UCS2*)buf1) + start, end - start,
9073 buf2, len2, PY_SSIZE_T_MAX
9074 );
9075 break;
9076 case PyUnicode_4BYTE_KIND:
9077 result = ucs4lib_count(
9078 ((Py_UCS4*)buf1) + start, end - start,
9079 buf2, len2, PY_SSIZE_T_MAX
9080 );
9081 break;
9082 default:
9083 assert(0); result = 0;
9084 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009085
9086 Py_DECREF(sub_obj);
9087 Py_DECREF(str_obj);
9088
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009089 if (kind1 != kind)
9090 PyMem_Free(buf1);
9091 if (kind2 != kind)
9092 PyMem_Free(buf2);
9093
Guido van Rossumd57fd912000-03-10 22:53:23 +00009094 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 onError:
9096 Py_DECREF(sub_obj);
9097 Py_DECREF(str_obj);
9098 if (kind1 != kind && buf1)
9099 PyMem_Free(buf1);
9100 if (kind2 != kind && buf2)
9101 PyMem_Free(buf2);
9102 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009103}
9104
Alexander Belopolsky40018472011-02-26 01:02:56 +00009105Py_ssize_t
9106PyUnicode_Find(PyObject *str,
9107 PyObject *sub,
9108 Py_ssize_t start,
9109 Py_ssize_t end,
9110 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009111{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009112 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009113
Guido van Rossumd57fd912000-03-10 22:53:23 +00009114 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009116 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009117 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009118 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009119 Py_DECREF(str);
9120 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009121 }
Tim Petersced69f82003-09-16 20:30:58 +00009122
Victor Stinner794d5672011-10-10 03:21:36 +02009123 result = any_find_slice(direction,
9124 str, sub, start, end
9125 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009126
Guido van Rossumd57fd912000-03-10 22:53:23 +00009127 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009128 Py_DECREF(sub);
9129
Guido van Rossumd57fd912000-03-10 22:53:23 +00009130 return result;
9131}
9132
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009133Py_ssize_t
9134PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9135 Py_ssize_t start, Py_ssize_t end,
9136 int direction)
9137{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009138 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009139 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009140 if (PyUnicode_READY(str) == -1)
9141 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009142 if (start < 0 || end < 0) {
9143 PyErr_SetString(PyExc_IndexError, "string index out of range");
9144 return -2;
9145 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009146 if (end > PyUnicode_GET_LENGTH(str))
9147 end = PyUnicode_GET_LENGTH(str);
9148 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009149 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9150 kind, end-start, ch, direction);
9151 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009152 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009153 else
9154 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009155}
9156
Alexander Belopolsky40018472011-02-26 01:02:56 +00009157static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009158tailmatch(PyObject *self,
9159 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009160 Py_ssize_t start,
9161 Py_ssize_t end,
9162 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009163{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 int kind_self;
9165 int kind_sub;
9166 void *data_self;
9167 void *data_sub;
9168 Py_ssize_t offset;
9169 Py_ssize_t i;
9170 Py_ssize_t end_sub;
9171
9172 if (PyUnicode_READY(self) == -1 ||
9173 PyUnicode_READY(substring) == -1)
9174 return 0;
9175
9176 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009177 return 1;
9178
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009179 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9180 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009181 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009182 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009183
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009184 kind_self = PyUnicode_KIND(self);
9185 data_self = PyUnicode_DATA(self);
9186 kind_sub = PyUnicode_KIND(substring);
9187 data_sub = PyUnicode_DATA(substring);
9188 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9189
9190 if (direction > 0)
9191 offset = end;
9192 else
9193 offset = start;
9194
9195 if (PyUnicode_READ(kind_self, data_self, offset) ==
9196 PyUnicode_READ(kind_sub, data_sub, 0) &&
9197 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9198 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9199 /* If both are of the same kind, memcmp is sufficient */
9200 if (kind_self == kind_sub) {
9201 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009202 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009203 data_sub,
9204 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009205 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009206 }
9207 /* otherwise we have to compare each character by first accesing it */
9208 else {
9209 /* We do not need to compare 0 and len(substring)-1 because
9210 the if statement above ensured already that they are equal
9211 when we end up here. */
9212 // TODO: honor direction and do a forward or backwards search
9213 for (i = 1; i < end_sub; ++i) {
9214 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9215 PyUnicode_READ(kind_sub, data_sub, i))
9216 return 0;
9217 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009218 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009219 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009220 }
9221
9222 return 0;
9223}
9224
Alexander Belopolsky40018472011-02-26 01:02:56 +00009225Py_ssize_t
9226PyUnicode_Tailmatch(PyObject *str,
9227 PyObject *substr,
9228 Py_ssize_t start,
9229 Py_ssize_t end,
9230 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009231{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009232 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009233
Guido van Rossumd57fd912000-03-10 22:53:23 +00009234 str = PyUnicode_FromObject(str);
9235 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009236 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009237 substr = PyUnicode_FromObject(substr);
9238 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009239 Py_DECREF(str);
9240 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009241 }
Tim Petersced69f82003-09-16 20:30:58 +00009242
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009243 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009244 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009245 Py_DECREF(str);
9246 Py_DECREF(substr);
9247 return result;
9248}
9249
Guido van Rossumd57fd912000-03-10 22:53:23 +00009250/* Apply fixfct filter to the Unicode object self and return a
9251 reference to the modified object */
9252
Alexander Belopolsky40018472011-02-26 01:02:56 +00009253static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009254fixup(PyObject *self,
9255 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009256{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009257 PyObject *u;
9258 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009259
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009260 if (PyUnicode_READY(self) == -1)
9261 return NULL;
9262 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9263 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9264 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009265 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009266 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009267
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009268 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009269 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009270
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009271 /* fix functions return the new maximum character in a string,
9272 if the kind of the resulting unicode object does not change,
9273 everything is fine. Otherwise we need to change the string kind
9274 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009275 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009276 if (maxchar_new == 0)
9277 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9278 else if (maxchar_new <= 127)
9279 maxchar_new = 127;
9280 else if (maxchar_new <= 255)
9281 maxchar_new = 255;
9282 else if (maxchar_new <= 65535)
9283 maxchar_new = 65535;
9284 else
9285 maxchar_new = 1114111; /* 0x10ffff */
9286
9287 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009288 /* fixfct should return TRUE if it modified the buffer. If
9289 FALSE, return a reference to the original buffer instead
9290 (to save space, not time) */
9291 Py_INCREF(self);
9292 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009293 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009294 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009295 else if (maxchar_new == maxchar_old) {
9296 return u;
9297 }
9298 else {
9299 /* In case the maximum character changed, we need to
9300 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009301 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 if (v == NULL) {
9303 Py_DECREF(u);
9304 return NULL;
9305 }
9306 if (maxchar_new > maxchar_old) {
9307 /* If the maxchar increased so that the kind changed, not all
9308 characters are representable anymore and we need to fix the
9309 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009310 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009311 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009312 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9313 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009314 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009315 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009316 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009317
9318 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009319 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009320 return v;
9321 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009322}
9323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009324static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009325fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009326{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009327 /* No need to call PyUnicode_READY(self) because this function is only
9328 called as a callback from fixup() which does it already. */
9329 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9330 const int kind = PyUnicode_KIND(self);
9331 void *data = PyUnicode_DATA(self);
9332 int touched = 0;
9333 Py_UCS4 maxchar = 0;
9334 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009335
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009336 for (i = 0; i < len; ++i) {
9337 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9338 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9339 if (up != ch) {
9340 if (up > maxchar)
9341 maxchar = up;
9342 PyUnicode_WRITE(kind, data, i, up);
9343 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009344 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009345 else if (ch > maxchar)
9346 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009347 }
9348
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009349 if (touched)
9350 return maxchar;
9351 else
9352 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009353}
9354
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009355static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009356fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009357{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009358 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9359 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9360 const int kind = PyUnicode_KIND(self);
9361 void *data = PyUnicode_DATA(self);
9362 int touched = 0;
9363 Py_UCS4 maxchar = 0;
9364 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009365
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009366 for(i = 0; i < len; ++i) {
9367 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9368 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9369 if (lo != ch) {
9370 if (lo > maxchar)
9371 maxchar = lo;
9372 PyUnicode_WRITE(kind, data, i, lo);
9373 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 else if (ch > maxchar)
9376 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009377 }
9378
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009379 if (touched)
9380 return maxchar;
9381 else
9382 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383}
9384
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009385static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009386fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009388 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9389 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9390 const int kind = PyUnicode_KIND(self);
9391 void *data = PyUnicode_DATA(self);
9392 int touched = 0;
9393 Py_UCS4 maxchar = 0;
9394 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009396 for(i = 0; i < len; ++i) {
9397 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9398 Py_UCS4 nu = 0;
9399
9400 if (Py_UNICODE_ISUPPER(ch))
9401 nu = Py_UNICODE_TOLOWER(ch);
9402 else if (Py_UNICODE_ISLOWER(ch))
9403 nu = Py_UNICODE_TOUPPER(ch);
9404
9405 if (nu != 0) {
9406 if (nu > maxchar)
9407 maxchar = nu;
9408 PyUnicode_WRITE(kind, data, i, nu);
9409 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009410 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411 else if (ch > maxchar)
9412 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413 }
9414
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009415 if (touched)
9416 return maxchar;
9417 else
9418 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009419}
9420
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009421static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009422fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009423{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009424 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9425 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9426 const int kind = PyUnicode_KIND(self);
9427 void *data = PyUnicode_DATA(self);
9428 int touched = 0;
9429 Py_UCS4 maxchar = 0;
9430 Py_ssize_t i = 0;
9431 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009432
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009433 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009434 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009435
9436 ch = PyUnicode_READ(kind, data, i);
9437 if (!Py_UNICODE_ISUPPER(ch)) {
9438 maxchar = Py_UNICODE_TOUPPER(ch);
9439 PyUnicode_WRITE(kind, data, i, maxchar);
9440 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009442 ++i;
9443 for(; i < len; ++i) {
9444 ch = PyUnicode_READ(kind, data, i);
9445 if (!Py_UNICODE_ISLOWER(ch)) {
9446 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9447 if (lo > maxchar)
9448 maxchar = lo;
9449 PyUnicode_WRITE(kind, data, i, lo);
9450 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009451 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009452 else if (ch > maxchar)
9453 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009454 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009455
9456 if (touched)
9457 return maxchar;
9458 else
9459 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009460}
9461
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009462static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009463fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009464{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009465 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9466 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9467 const int kind = PyUnicode_KIND(self);
9468 void *data = PyUnicode_DATA(self);
9469 Py_UCS4 maxchar = 0;
9470 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009471 int previous_is_cased;
9472
9473 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009474 if (len == 1) {
9475 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9476 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9477 if (ti != ch) {
9478 PyUnicode_WRITE(kind, data, i, ti);
9479 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009480 }
9481 else
9482 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009483 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009484 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009485 for(; i < len; ++i) {
9486 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9487 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009488
Benjamin Peterson29060642009-01-31 22:14:21 +00009489 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009490 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009491 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009492 nu = Py_UNICODE_TOTITLE(ch);
9493
9494 if (nu > maxchar)
9495 maxchar = nu;
9496 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009497
Benjamin Peterson29060642009-01-31 22:14:21 +00009498 if (Py_UNICODE_ISLOWER(ch) ||
9499 Py_UNICODE_ISUPPER(ch) ||
9500 Py_UNICODE_ISTITLE(ch))
9501 previous_is_cased = 1;
9502 else
9503 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009504 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009505 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009506}
9507
Tim Peters8ce9f162004-08-27 01:49:32 +00009508PyObject *
9509PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009512 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009513 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009514 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009515 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9516 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009517 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009519 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009520 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009521 int use_memcpy;
9522 unsigned char *res_data = NULL, *sep_data = NULL;
9523 PyObject *last_obj;
9524 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009525
Tim Peters05eba1f2004-08-27 21:32:02 +00009526 fseq = PySequence_Fast(seq, "");
9527 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009528 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009529 }
9530
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009531 /* NOTE: the following code can't call back into Python code,
9532 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009533 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009534
Tim Peters05eba1f2004-08-27 21:32:02 +00009535 seqlen = PySequence_Fast_GET_SIZE(fseq);
9536 /* If empty sequence, return u"". */
9537 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009538 Py_DECREF(fseq);
9539 Py_INCREF(unicode_empty);
9540 res = unicode_empty;
9541 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009542 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009543
Tim Peters05eba1f2004-08-27 21:32:02 +00009544 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009545 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009546 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009547 if (seqlen == 1) {
9548 if (PyUnicode_CheckExact(items[0])) {
9549 res = items[0];
9550 Py_INCREF(res);
9551 Py_DECREF(fseq);
9552 return res;
9553 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009554 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009555 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009556 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009557 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009558 /* Set up sep and seplen */
9559 if (separator == NULL) {
9560 /* fall back to a blank space separator */
9561 sep = PyUnicode_FromOrdinal(' ');
9562 if (!sep)
9563 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009564 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009565 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009566 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009567 else {
9568 if (!PyUnicode_Check(separator)) {
9569 PyErr_Format(PyExc_TypeError,
9570 "separator: expected str instance,"
9571 " %.80s found",
9572 Py_TYPE(separator)->tp_name);
9573 goto onError;
9574 }
9575 if (PyUnicode_READY(separator))
9576 goto onError;
9577 sep = separator;
9578 seplen = PyUnicode_GET_LENGTH(separator);
9579 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9580 /* inc refcount to keep this code path symmetric with the
9581 above case of a blank separator */
9582 Py_INCREF(sep);
9583 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009584 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009585 }
9586
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009587 /* There are at least two things to join, or else we have a subclass
9588 * of str in the sequence.
9589 * Do a pre-pass to figure out the total amount of space we'll
9590 * need (sz), and see whether all argument are strings.
9591 */
9592 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009593#ifdef Py_DEBUG
9594 use_memcpy = 0;
9595#else
9596 use_memcpy = 1;
9597#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009598 for (i = 0; i < seqlen; i++) {
9599 const Py_ssize_t old_sz = sz;
9600 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009601 if (!PyUnicode_Check(item)) {
9602 PyErr_Format(PyExc_TypeError,
9603 "sequence item %zd: expected str instance,"
9604 " %.80s found",
9605 i, Py_TYPE(item)->tp_name);
9606 goto onError;
9607 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009608 if (PyUnicode_READY(item) == -1)
9609 goto onError;
9610 sz += PyUnicode_GET_LENGTH(item);
9611 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009612 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009613 if (i != 0)
9614 sz += seplen;
9615 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9616 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009617 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009618 goto onError;
9619 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009620 if (use_memcpy && last_obj != NULL) {
9621 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9622 use_memcpy = 0;
9623 }
9624 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009625 }
Tim Petersced69f82003-09-16 20:30:58 +00009626
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009627 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009628 if (res == NULL)
9629 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009630
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009631 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009632#ifdef Py_DEBUG
9633 use_memcpy = 0;
9634#else
9635 if (use_memcpy) {
9636 res_data = PyUnicode_1BYTE_DATA(res);
9637 kind = PyUnicode_KIND(res);
9638 if (seplen != 0)
9639 sep_data = PyUnicode_1BYTE_DATA(sep);
9640 }
9641#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009642 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009643 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009644 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009645 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009646 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009647 if (use_memcpy) {
9648 Py_MEMCPY(res_data,
9649 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009650 kind * seplen);
9651 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009652 }
9653 else {
9654 copy_characters(res, res_offset, sep, 0, seplen);
9655 res_offset += seplen;
9656 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009657 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009658 itemlen = PyUnicode_GET_LENGTH(item);
9659 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009660 if (use_memcpy) {
9661 Py_MEMCPY(res_data,
9662 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009663 kind * itemlen);
9664 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009665 }
9666 else {
9667 copy_characters(res, res_offset, item, 0, itemlen);
9668 res_offset += itemlen;
9669 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009670 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009671 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009672 if (use_memcpy)
9673 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009674 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009675 else
9676 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009677
Tim Peters05eba1f2004-08-27 21:32:02 +00009678 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009679 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009680 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009681 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009682
Benjamin Peterson29060642009-01-31 22:14:21 +00009683 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009684 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009685 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009686 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009687 return NULL;
9688}
9689
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009690#define FILL(kind, data, value, start, length) \
9691 do { \
9692 Py_ssize_t i_ = 0; \
9693 assert(kind != PyUnicode_WCHAR_KIND); \
9694 switch ((kind)) { \
9695 case PyUnicode_1BYTE_KIND: { \
9696 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9697 memset(to_, (unsigned char)value, length); \
9698 break; \
9699 } \
9700 case PyUnicode_2BYTE_KIND: { \
9701 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9702 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9703 break; \
9704 } \
9705 default: { \
9706 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9707 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9708 break; \
9709 } \
9710 } \
9711 } while (0)
9712
Victor Stinner9310abb2011-10-05 00:59:23 +02009713static PyObject *
9714pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009715 Py_ssize_t left,
9716 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009717 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009718{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009719 PyObject *u;
9720 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009721 int kind;
9722 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009723
9724 if (left < 0)
9725 left = 0;
9726 if (right < 0)
9727 right = 0;
9728
Tim Peters7a29bd52001-09-12 03:03:31 +00009729 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009730 Py_INCREF(self);
9731 return self;
9732 }
9733
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009734 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9735 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009736 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9737 return NULL;
9738 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009739 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9740 if (fill > maxchar)
9741 maxchar = fill;
9742 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009743 if (!u)
9744 return NULL;
9745
9746 kind = PyUnicode_KIND(u);
9747 data = PyUnicode_DATA(u);
9748 if (left)
9749 FILL(kind, data, fill, 0, left);
9750 if (right)
9751 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009752 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009753 assert(_PyUnicode_CheckConsistency(u, 1));
9754 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009755}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009756#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009757
Alexander Belopolsky40018472011-02-26 01:02:56 +00009758PyObject *
9759PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009760{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009761 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009762
9763 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009764 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009765 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009767 switch(PyUnicode_KIND(string)) {
9768 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009769 if (PyUnicode_IS_ASCII(string))
9770 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009771 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009772 PyUnicode_GET_LENGTH(string), keepends);
9773 else
9774 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009775 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009776 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009777 break;
9778 case PyUnicode_2BYTE_KIND:
9779 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009780 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009781 PyUnicode_GET_LENGTH(string), keepends);
9782 break;
9783 case PyUnicode_4BYTE_KIND:
9784 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009785 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009786 PyUnicode_GET_LENGTH(string), keepends);
9787 break;
9788 default:
9789 assert(0);
9790 list = 0;
9791 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009792 Py_DECREF(string);
9793 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009794}
9795
Alexander Belopolsky40018472011-02-26 01:02:56 +00009796static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009797split(PyObject *self,
9798 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009799 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009800{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009801 int kind1, kind2, kind;
9802 void *buf1, *buf2;
9803 Py_ssize_t len1, len2;
9804 PyObject* out;
9805
Guido van Rossumd57fd912000-03-10 22:53:23 +00009806 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009807 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009808
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009809 if (PyUnicode_READY(self) == -1)
9810 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009811
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 if (substring == NULL)
9813 switch(PyUnicode_KIND(self)) {
9814 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009815 if (PyUnicode_IS_ASCII(self))
9816 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009817 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009818 PyUnicode_GET_LENGTH(self), maxcount
9819 );
9820 else
9821 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009822 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009823 PyUnicode_GET_LENGTH(self), maxcount
9824 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009825 case PyUnicode_2BYTE_KIND:
9826 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009827 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009828 PyUnicode_GET_LENGTH(self), maxcount
9829 );
9830 case PyUnicode_4BYTE_KIND:
9831 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009832 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009833 PyUnicode_GET_LENGTH(self), maxcount
9834 );
9835 default:
9836 assert(0);
9837 return NULL;
9838 }
9839
9840 if (PyUnicode_READY(substring) == -1)
9841 return NULL;
9842
9843 kind1 = PyUnicode_KIND(self);
9844 kind2 = PyUnicode_KIND(substring);
9845 kind = kind1 > kind2 ? kind1 : kind2;
9846 buf1 = PyUnicode_DATA(self);
9847 buf2 = PyUnicode_DATA(substring);
9848 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009849 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009850 if (!buf1)
9851 return NULL;
9852 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009853 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 if (!buf2) {
9855 if (kind1 != kind) PyMem_Free(buf1);
9856 return NULL;
9857 }
9858 len1 = PyUnicode_GET_LENGTH(self);
9859 len2 = PyUnicode_GET_LENGTH(substring);
9860
9861 switch(kind) {
9862 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009863 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9864 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009865 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009866 else
9867 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009868 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009869 break;
9870 case PyUnicode_2BYTE_KIND:
9871 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009872 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009873 break;
9874 case PyUnicode_4BYTE_KIND:
9875 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009876 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009877 break;
9878 default:
9879 out = NULL;
9880 }
9881 if (kind1 != kind)
9882 PyMem_Free(buf1);
9883 if (kind2 != kind)
9884 PyMem_Free(buf2);
9885 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009886}
9887
Alexander Belopolsky40018472011-02-26 01:02:56 +00009888static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009889rsplit(PyObject *self,
9890 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009891 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009892{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009893 int kind1, kind2, kind;
9894 void *buf1, *buf2;
9895 Py_ssize_t len1, len2;
9896 PyObject* out;
9897
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009898 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009899 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009900
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009901 if (PyUnicode_READY(self) == -1)
9902 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009903
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009904 if (substring == NULL)
9905 switch(PyUnicode_KIND(self)) {
9906 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009907 if (PyUnicode_IS_ASCII(self))
9908 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009909 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009910 PyUnicode_GET_LENGTH(self), maxcount
9911 );
9912 else
9913 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009914 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009915 PyUnicode_GET_LENGTH(self), maxcount
9916 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009917 case PyUnicode_2BYTE_KIND:
9918 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009919 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009920 PyUnicode_GET_LENGTH(self), maxcount
9921 );
9922 case PyUnicode_4BYTE_KIND:
9923 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009924 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009925 PyUnicode_GET_LENGTH(self), maxcount
9926 );
9927 default:
9928 assert(0);
9929 return NULL;
9930 }
9931
9932 if (PyUnicode_READY(substring) == -1)
9933 return NULL;
9934
9935 kind1 = PyUnicode_KIND(self);
9936 kind2 = PyUnicode_KIND(substring);
9937 kind = kind1 > kind2 ? kind1 : kind2;
9938 buf1 = PyUnicode_DATA(self);
9939 buf2 = PyUnicode_DATA(substring);
9940 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009941 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009942 if (!buf1)
9943 return NULL;
9944 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009945 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 if (!buf2) {
9947 if (kind1 != kind) PyMem_Free(buf1);
9948 return NULL;
9949 }
9950 len1 = PyUnicode_GET_LENGTH(self);
9951 len2 = PyUnicode_GET_LENGTH(substring);
9952
9953 switch(kind) {
9954 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009955 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9956 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009957 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009958 else
9959 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009960 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009961 break;
9962 case PyUnicode_2BYTE_KIND:
9963 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009964 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009965 break;
9966 case PyUnicode_4BYTE_KIND:
9967 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009968 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009969 break;
9970 default:
9971 out = NULL;
9972 }
9973 if (kind1 != kind)
9974 PyMem_Free(buf1);
9975 if (kind2 != kind)
9976 PyMem_Free(buf2);
9977 return out;
9978}
9979
9980static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02009981anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
9982 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009983{
9984 switch(kind) {
9985 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009986 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
9987 return asciilib_find(buf1, len1, buf2, len2, offset);
9988 else
9989 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009990 case PyUnicode_2BYTE_KIND:
9991 return ucs2lib_find(buf1, len1, buf2, len2, offset);
9992 case PyUnicode_4BYTE_KIND:
9993 return ucs4lib_find(buf1, len1, buf2, len2, offset);
9994 }
9995 assert(0);
9996 return -1;
9997}
9998
9999static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010000anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10001 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010002{
10003 switch(kind) {
10004 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010005 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10006 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10007 else
10008 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009 case PyUnicode_2BYTE_KIND:
10010 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10011 case PyUnicode_4BYTE_KIND:
10012 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10013 }
10014 assert(0);
10015 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010016}
10017
Alexander Belopolsky40018472011-02-26 01:02:56 +000010018static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010019replace(PyObject *self, PyObject *str1,
10020 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010021{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010022 PyObject *u;
10023 char *sbuf = PyUnicode_DATA(self);
10024 char *buf1 = PyUnicode_DATA(str1);
10025 char *buf2 = PyUnicode_DATA(str2);
10026 int srelease = 0, release1 = 0, release2 = 0;
10027 int skind = PyUnicode_KIND(self);
10028 int kind1 = PyUnicode_KIND(str1);
10029 int kind2 = PyUnicode_KIND(str2);
10030 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10031 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10032 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010033 int mayshrink;
10034 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010035
10036 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010037 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010038 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010039 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010040
Victor Stinner59de0ee2011-10-07 10:01:28 +020010041 if (str1 == str2)
10042 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010043 if (skind < kind1)
10044 /* substring too wide to be present */
10045 goto nothing;
10046
Victor Stinner49a0a212011-10-12 23:46:10 +020010047 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10048 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10049 /* Replacing str1 with str2 may cause a maxchar reduction in the
10050 result string. */
10051 mayshrink = (maxchar_str2 < maxchar);
10052 maxchar = Py_MAX(maxchar, maxchar_str2);
10053
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010054 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010055 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010056 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010057 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010058 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010059 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010060 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010061 Py_UCS4 u1, u2;
10062 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010063 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010064 if (findchar(sbuf, PyUnicode_KIND(self),
10065 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010066 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010067 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010068 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010069 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010070 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010071 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010072 rkind = PyUnicode_KIND(u);
10073 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10074 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010075 if (--maxcount < 0)
10076 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010077 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010078 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010079 }
10080 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010081 int rkind = skind;
10082 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010083
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010084 if (kind1 < rkind) {
10085 /* widen substring */
10086 buf1 = _PyUnicode_AsKind(str1, rkind);
10087 if (!buf1) goto error;
10088 release1 = 1;
10089 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010090 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010091 if (i < 0)
10092 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 if (rkind > kind2) {
10094 /* widen replacement */
10095 buf2 = _PyUnicode_AsKind(str2, rkind);
10096 if (!buf2) goto error;
10097 release2 = 1;
10098 }
10099 else if (rkind < kind2) {
10100 /* widen self and buf1 */
10101 rkind = kind2;
10102 if (release1) PyMem_Free(buf1);
10103 sbuf = _PyUnicode_AsKind(self, rkind);
10104 if (!sbuf) goto error;
10105 srelease = 1;
10106 buf1 = _PyUnicode_AsKind(str1, rkind);
10107 if (!buf1) goto error;
10108 release1 = 1;
10109 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010110 u = PyUnicode_New(slen, maxchar);
10111 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010112 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010113 assert(PyUnicode_KIND(u) == rkind);
10114 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010115
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010116 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010117 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010118 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010120 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010121 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010122
10123 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010124 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010125 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010126 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010127 if (i == -1)
10128 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010129 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010130 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010131 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010132 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010133 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010134 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010135 }
10136 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010137 Py_ssize_t n, i, j, ires;
10138 Py_ssize_t product, new_size;
10139 int rkind = skind;
10140 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010141
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010142 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010143 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010144 buf1 = _PyUnicode_AsKind(str1, rkind);
10145 if (!buf1) goto error;
10146 release1 = 1;
10147 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010148 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010149 if (n == 0)
10150 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010151 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010152 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010153 buf2 = _PyUnicode_AsKind(str2, rkind);
10154 if (!buf2) goto error;
10155 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010156 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010157 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010158 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010159 rkind = kind2;
10160 sbuf = _PyUnicode_AsKind(self, rkind);
10161 if (!sbuf) goto error;
10162 srelease = 1;
10163 if (release1) PyMem_Free(buf1);
10164 buf1 = _PyUnicode_AsKind(str1, rkind);
10165 if (!buf1) goto error;
10166 release1 = 1;
10167 }
10168 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10169 PyUnicode_GET_LENGTH(str1))); */
10170 product = n * (len2-len1);
10171 if ((product / (len2-len1)) != n) {
10172 PyErr_SetString(PyExc_OverflowError,
10173 "replace string is too long");
10174 goto error;
10175 }
10176 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010177 if (new_size == 0) {
10178 Py_INCREF(unicode_empty);
10179 u = unicode_empty;
10180 goto done;
10181 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010182 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10183 PyErr_SetString(PyExc_OverflowError,
10184 "replace string is too long");
10185 goto error;
10186 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010187 u = PyUnicode_New(new_size, maxchar);
10188 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010189 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010190 assert(PyUnicode_KIND(u) == rkind);
10191 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010192 ires = i = 0;
10193 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010194 while (n-- > 0) {
10195 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010196 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010197 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010198 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010199 if (j == -1)
10200 break;
10201 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010202 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010203 memcpy(res + rkind * ires,
10204 sbuf + rkind * i,
10205 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010206 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010207 }
10208 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010209 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010210 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010211 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010212 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010213 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010214 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010216 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010217 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010218 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010219 memcpy(res + rkind * ires,
10220 sbuf + rkind * i,
10221 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010222 }
10223 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010224 /* interleave */
10225 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010226 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010227 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010228 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010229 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010230 if (--n <= 0)
10231 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010232 memcpy(res + rkind * ires,
10233 sbuf + rkind * i,
10234 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 ires++;
10236 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010237 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010238 memcpy(res + rkind * ires,
10239 sbuf + rkind * i,
10240 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010241 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010242 }
10243
10244 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010245 unicode_adjust_maxchar(&u);
10246 if (u == NULL)
10247 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010248 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010249
10250 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010251 if (srelease)
10252 PyMem_FREE(sbuf);
10253 if (release1)
10254 PyMem_FREE(buf1);
10255 if (release2)
10256 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010257 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010258 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010259
Benjamin Peterson29060642009-01-31 22:14:21 +000010260 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010262 if (srelease)
10263 PyMem_FREE(sbuf);
10264 if (release1)
10265 PyMem_FREE(buf1);
10266 if (release2)
10267 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010268 if (PyUnicode_CheckExact(self)) {
10269 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010270 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010271 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010272 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010273 error:
10274 if (srelease && sbuf)
10275 PyMem_FREE(sbuf);
10276 if (release1 && buf1)
10277 PyMem_FREE(buf1);
10278 if (release2 && buf2)
10279 PyMem_FREE(buf2);
10280 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010281}
10282
10283/* --- Unicode Object Methods --------------------------------------------- */
10284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010285PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010286 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010287\n\
10288Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010289characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010290
10291static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010292unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010293{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010294 return fixup(self, fixtitle);
10295}
10296
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010297PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010298 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010299\n\
10300Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010301have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010302
10303static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010304unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010305{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010306 return fixup(self, fixcapitalize);
10307}
10308
10309#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010310PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010311 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010312\n\
10313Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010314normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010315
10316static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010317unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010318{
10319 PyObject *list;
10320 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010321 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010322
Guido van Rossumd57fd912000-03-10 22:53:23 +000010323 /* Split into words */
10324 list = split(self, NULL, -1);
10325 if (!list)
10326 return NULL;
10327
10328 /* Capitalize each word */
10329 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010330 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010331 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010332 if (item == NULL)
10333 goto onError;
10334 Py_DECREF(PyList_GET_ITEM(list, i));
10335 PyList_SET_ITEM(list, i, item);
10336 }
10337
10338 /* Join the words to form a new string */
10339 item = PyUnicode_Join(NULL, list);
10340
Benjamin Peterson29060642009-01-31 22:14:21 +000010341 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010342 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010343 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010344}
10345#endif
10346
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010347/* Argument converter. Coerces to a single unicode character */
10348
10349static int
10350convert_uc(PyObject *obj, void *addr)
10351{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010352 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010353 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010354
Benjamin Peterson14339b62009-01-31 16:36:08 +000010355 uniobj = PyUnicode_FromObject(obj);
10356 if (uniobj == NULL) {
10357 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010358 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010359 return 0;
10360 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010361 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010362 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010363 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010364 Py_DECREF(uniobj);
10365 return 0;
10366 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010367 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010368 Py_DECREF(uniobj);
10369 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010370}
10371
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010372PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010373 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010374\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010375Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010376done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010377
10378static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010379unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010380{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010381 Py_ssize_t marg, left;
10382 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010383 Py_UCS4 fillchar = ' ';
10384
Victor Stinnere9a29352011-10-01 02:14:59 +020010385 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010386 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010387
Victor Stinnere9a29352011-10-01 02:14:59 +020010388 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010389 return NULL;
10390
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010391 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010392 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010393 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010394 }
10395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010396 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010397 left = marg / 2 + (marg & width & 1);
10398
Victor Stinner9310abb2011-10-05 00:59:23 +020010399 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400}
10401
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010402/* This function assumes that str1 and str2 are readied by the caller. */
10403
Marc-André Lemburge5034372000-08-08 08:04:29 +000010404static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010405unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010406{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010407 int kind1, kind2;
10408 void *data1, *data2;
10409 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010411 kind1 = PyUnicode_KIND(str1);
10412 kind2 = PyUnicode_KIND(str2);
10413 data1 = PyUnicode_DATA(str1);
10414 data2 = PyUnicode_DATA(str2);
10415 len1 = PyUnicode_GET_LENGTH(str1);
10416 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010417
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010418 for (i = 0; i < len1 && i < len2; ++i) {
10419 Py_UCS4 c1, c2;
10420 c1 = PyUnicode_READ(kind1, data1, i);
10421 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010422
10423 if (c1 != c2)
10424 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010425 }
10426
10427 return (len1 < len2) ? -1 : (len1 != len2);
10428}
10429
Alexander Belopolsky40018472011-02-26 01:02:56 +000010430int
10431PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010432{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10434 if (PyUnicode_READY(left) == -1 ||
10435 PyUnicode_READY(right) == -1)
10436 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010437 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010438 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010439 PyErr_Format(PyExc_TypeError,
10440 "Can't compare %.100s and %.100s",
10441 left->ob_type->tp_name,
10442 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010443 return -1;
10444}
10445
Martin v. Löwis5b222132007-06-10 09:51:05 +000010446int
10447PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10448{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010449 Py_ssize_t i;
10450 int kind;
10451 void *data;
10452 Py_UCS4 chr;
10453
Victor Stinner910337b2011-10-03 03:20:16 +020010454 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010455 if (PyUnicode_READY(uni) == -1)
10456 return -1;
10457 kind = PyUnicode_KIND(uni);
10458 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010459 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010460 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10461 if (chr != str[i])
10462 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010463 /* This check keeps Python strings that end in '\0' from comparing equal
10464 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010465 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010466 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010467 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010468 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010469 return 0;
10470}
10471
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010472
Benjamin Peterson29060642009-01-31 22:14:21 +000010473#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010474 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010475
Alexander Belopolsky40018472011-02-26 01:02:56 +000010476PyObject *
10477PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010478{
10479 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010480
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010481 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10482 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010483 if (PyUnicode_READY(left) == -1 ||
10484 PyUnicode_READY(right) == -1)
10485 return NULL;
10486 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10487 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010488 if (op == Py_EQ) {
10489 Py_INCREF(Py_False);
10490 return Py_False;
10491 }
10492 if (op == Py_NE) {
10493 Py_INCREF(Py_True);
10494 return Py_True;
10495 }
10496 }
10497 if (left == right)
10498 result = 0;
10499 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010500 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010501
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010502 /* Convert the return value to a Boolean */
10503 switch (op) {
10504 case Py_EQ:
10505 v = TEST_COND(result == 0);
10506 break;
10507 case Py_NE:
10508 v = TEST_COND(result != 0);
10509 break;
10510 case Py_LE:
10511 v = TEST_COND(result <= 0);
10512 break;
10513 case Py_GE:
10514 v = TEST_COND(result >= 0);
10515 break;
10516 case Py_LT:
10517 v = TEST_COND(result == -1);
10518 break;
10519 case Py_GT:
10520 v = TEST_COND(result == 1);
10521 break;
10522 default:
10523 PyErr_BadArgument();
10524 return NULL;
10525 }
10526 Py_INCREF(v);
10527 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010528 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010529
Brian Curtindfc80e32011-08-10 20:28:54 -050010530 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010531}
10532
Alexander Belopolsky40018472011-02-26 01:02:56 +000010533int
10534PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010535{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010536 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010537 int kind1, kind2, kind;
10538 void *buf1, *buf2;
10539 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010540 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010541
10542 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010543 sub = PyUnicode_FromObject(element);
10544 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010545 PyErr_Format(PyExc_TypeError,
10546 "'in <string>' requires string as left operand, not %s",
10547 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010548 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010549 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010550 if (PyUnicode_READY(sub) == -1)
10551 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010552
Thomas Wouters477c8d52006-05-27 19:21:47 +000010553 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010554 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010555 Py_DECREF(sub);
10556 return -1;
10557 }
10558
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010559 kind1 = PyUnicode_KIND(str);
10560 kind2 = PyUnicode_KIND(sub);
10561 kind = kind1 > kind2 ? kind1 : kind2;
10562 buf1 = PyUnicode_DATA(str);
10563 buf2 = PyUnicode_DATA(sub);
10564 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010565 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010566 if (!buf1) {
10567 Py_DECREF(sub);
10568 return -1;
10569 }
10570 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010571 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010572 if (!buf2) {
10573 Py_DECREF(sub);
10574 if (kind1 != kind) PyMem_Free(buf1);
10575 return -1;
10576 }
10577 len1 = PyUnicode_GET_LENGTH(str);
10578 len2 = PyUnicode_GET_LENGTH(sub);
10579
10580 switch(kind) {
10581 case PyUnicode_1BYTE_KIND:
10582 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10583 break;
10584 case PyUnicode_2BYTE_KIND:
10585 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10586 break;
10587 case PyUnicode_4BYTE_KIND:
10588 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10589 break;
10590 default:
10591 result = -1;
10592 assert(0);
10593 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010594
10595 Py_DECREF(str);
10596 Py_DECREF(sub);
10597
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 if (kind1 != kind)
10599 PyMem_Free(buf1);
10600 if (kind2 != kind)
10601 PyMem_Free(buf2);
10602
Guido van Rossum403d68b2000-03-13 15:55:09 +000010603 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010604}
10605
Guido van Rossumd57fd912000-03-10 22:53:23 +000010606/* Concat to string or Unicode object giving a new Unicode object. */
10607
Alexander Belopolsky40018472011-02-26 01:02:56 +000010608PyObject *
10609PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010610{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010611 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010612 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010613
10614 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010615 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010616 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010617 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010618 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010619 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010620 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010621
10622 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010623 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010624 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010625 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010626 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010627 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010628 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010629 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010630 }
10631
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010632 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010633 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10634 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010635
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 w = PyUnicode_New(
10638 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10639 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010640 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010641 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010642 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10643 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010644 Py_DECREF(u);
10645 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010646 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010647 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010648
Benjamin Peterson29060642009-01-31 22:14:21 +000010649 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010650 Py_XDECREF(u);
10651 Py_XDECREF(v);
10652 return NULL;
10653}
10654
Victor Stinnerb0923652011-10-04 01:17:31 +020010655static void
10656unicode_append_inplace(PyObject **p_left, PyObject *right)
10657{
10658 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010659
10660 assert(PyUnicode_IS_READY(*p_left));
10661 assert(PyUnicode_IS_READY(right));
10662
10663 left_len = PyUnicode_GET_LENGTH(*p_left);
10664 right_len = PyUnicode_GET_LENGTH(right);
10665 if (left_len > PY_SSIZE_T_MAX - right_len) {
10666 PyErr_SetString(PyExc_OverflowError,
10667 "strings are too large to concat");
10668 goto error;
10669 }
10670 new_len = left_len + right_len;
10671
10672 /* Now we own the last reference to 'left', so we can resize it
10673 * in-place.
10674 */
10675 if (unicode_resize(p_left, new_len) != 0) {
10676 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10677 * deallocated so it cannot be put back into
10678 * 'variable'. The MemoryError is raised when there
10679 * is no value in 'variable', which might (very
10680 * remotely) be a cause of incompatibilities.
10681 */
10682 goto error;
10683 }
10684 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010685 copy_characters(*p_left, left_len, right, 0, right_len);
10686 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010687 return;
10688
10689error:
10690 Py_DECREF(*p_left);
10691 *p_left = NULL;
10692}
10693
Walter Dörwald1ab83302007-05-18 17:15:44 +000010694void
Victor Stinner23e56682011-10-03 03:54:37 +020010695PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010696{
Victor Stinner23e56682011-10-03 03:54:37 +020010697 PyObject *left, *res;
10698
10699 if (p_left == NULL) {
10700 if (!PyErr_Occurred())
10701 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010702 return;
10703 }
Victor Stinner23e56682011-10-03 03:54:37 +020010704 left = *p_left;
10705 if (right == NULL || !PyUnicode_Check(left)) {
10706 if (!PyErr_Occurred())
10707 PyErr_BadInternalCall();
10708 goto error;
10709 }
10710
Victor Stinnere1335c72011-10-04 20:53:03 +020010711 if (PyUnicode_READY(left))
10712 goto error;
10713 if (PyUnicode_READY(right))
10714 goto error;
10715
Victor Stinner23e56682011-10-03 03:54:37 +020010716 if (PyUnicode_CheckExact(left) && left != unicode_empty
10717 && PyUnicode_CheckExact(right) && right != unicode_empty
10718 && unicode_resizable(left)
10719 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10720 || _PyUnicode_WSTR(left) != NULL))
10721 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010722 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10723 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010724 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010725 not so different than duplicating the string. */
10726 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010727 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010728 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010729 if (p_left != NULL)
10730 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010731 return;
10732 }
10733 }
10734
10735 res = PyUnicode_Concat(left, right);
10736 if (res == NULL)
10737 goto error;
10738 Py_DECREF(left);
10739 *p_left = res;
10740 return;
10741
10742error:
10743 Py_DECREF(*p_left);
10744 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010745}
10746
10747void
10748PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10749{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010750 PyUnicode_Append(pleft, right);
10751 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010752}
10753
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010754PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010755 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010756\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010757Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010758string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010759interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010760
10761static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010762unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010763{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010764 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010765 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010766 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010767 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010768 int kind1, kind2, kind;
10769 void *buf1, *buf2;
10770 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010771
Jesus Ceaac451502011-04-20 17:09:23 +020010772 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10773 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010774 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010775
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010776 kind1 = PyUnicode_KIND(self);
10777 kind2 = PyUnicode_KIND(substring);
10778 kind = kind1 > kind2 ? kind1 : kind2;
10779 buf1 = PyUnicode_DATA(self);
10780 buf2 = PyUnicode_DATA(substring);
10781 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010782 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010783 if (!buf1) {
10784 Py_DECREF(substring);
10785 return NULL;
10786 }
10787 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010788 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010789 if (!buf2) {
10790 Py_DECREF(substring);
10791 if (kind1 != kind) PyMem_Free(buf1);
10792 return NULL;
10793 }
10794 len1 = PyUnicode_GET_LENGTH(self);
10795 len2 = PyUnicode_GET_LENGTH(substring);
10796
10797 ADJUST_INDICES(start, end, len1);
10798 switch(kind) {
10799 case PyUnicode_1BYTE_KIND:
10800 iresult = ucs1lib_count(
10801 ((Py_UCS1*)buf1) + start, end - start,
10802 buf2, len2, PY_SSIZE_T_MAX
10803 );
10804 break;
10805 case PyUnicode_2BYTE_KIND:
10806 iresult = ucs2lib_count(
10807 ((Py_UCS2*)buf1) + start, end - start,
10808 buf2, len2, PY_SSIZE_T_MAX
10809 );
10810 break;
10811 case PyUnicode_4BYTE_KIND:
10812 iresult = ucs4lib_count(
10813 ((Py_UCS4*)buf1) + start, end - start,
10814 buf2, len2, PY_SSIZE_T_MAX
10815 );
10816 break;
10817 default:
10818 assert(0); iresult = 0;
10819 }
10820
10821 result = PyLong_FromSsize_t(iresult);
10822
10823 if (kind1 != kind)
10824 PyMem_Free(buf1);
10825 if (kind2 != kind)
10826 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010827
10828 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010829
Guido van Rossumd57fd912000-03-10 22:53:23 +000010830 return result;
10831}
10832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010833PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010834 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010835\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010836Encode S using the codec registered for encoding. Default encoding\n\
10837is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010838handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010839a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10840'xmlcharrefreplace' as well as any other name registered with\n\
10841codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010842
10843static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010844unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010845{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010846 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010847 char *encoding = NULL;
10848 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010849
Benjamin Peterson308d6372009-09-18 21:42:35 +000010850 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10851 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010852 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010853 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010854}
10855
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010856PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010857 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010858\n\
10859Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010860If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861
10862static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010863unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010864{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010865 Py_ssize_t i, j, line_pos, src_len, incr;
10866 Py_UCS4 ch;
10867 PyObject *u;
10868 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010869 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010870 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010871 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010872
10873 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010874 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010875
Antoine Pitrou22425222011-10-04 19:10:51 +020010876 if (PyUnicode_READY(self) == -1)
10877 return NULL;
10878
Thomas Wouters7e474022000-07-16 12:04:32 +000010879 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010880 src_len = PyUnicode_GET_LENGTH(self);
10881 i = j = line_pos = 0;
10882 kind = PyUnicode_KIND(self);
10883 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010884 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010885 for (; i < src_len; i++) {
10886 ch = PyUnicode_READ(kind, src_data, i);
10887 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010888 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010889 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010890 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010891 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010892 goto overflow;
10893 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010894 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010895 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010896 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010897 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010898 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010899 goto overflow;
10900 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010902 if (ch == '\n' || ch == '\r')
10903 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010904 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010905 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010906 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010907 Py_INCREF(self);
10908 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010909 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010910
Guido van Rossumd57fd912000-03-10 22:53:23 +000010911 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010912 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010913 if (!u)
10914 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010915 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010916
Antoine Pitroue71d5742011-10-04 15:55:09 +020010917 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010918
Antoine Pitroue71d5742011-10-04 15:55:09 +020010919 for (; i < src_len; i++) {
10920 ch = PyUnicode_READ(kind, src_data, i);
10921 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010922 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010923 incr = tabsize - (line_pos % tabsize);
10924 line_pos += incr;
10925 while (incr--) {
10926 PyUnicode_WRITE(kind, dest_data, j, ' ');
10927 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010928 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010929 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010930 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010931 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010932 line_pos++;
10933 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010934 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010935 if (ch == '\n' || ch == '\r')
10936 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010938 }
10939 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010940#ifndef DONT_MAKE_RESULT_READY
10941 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010942 Py_DECREF(u);
10943 return NULL;
10944 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010945#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010946 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010010947 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010948
Antoine Pitroue71d5742011-10-04 15:55:09 +020010949 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010950 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10951 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010952}
10953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010954PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010956\n\
10957Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010958such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010959arguments start and end are interpreted as in slice notation.\n\
10960\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010961Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010962
10963static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010964unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010965{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010966 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010967 Py_ssize_t start;
10968 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010969 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010970
Jesus Ceaac451502011-04-20 17:09:23 +020010971 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10972 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010973 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010974
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010975 if (PyUnicode_READY(self) == -1)
10976 return NULL;
10977 if (PyUnicode_READY(substring) == -1)
10978 return NULL;
10979
Victor Stinner7931d9a2011-11-04 00:22:48 +010010980 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010981
10982 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010983
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010984 if (result == -2)
10985 return NULL;
10986
Christian Heimes217cfd12007-12-02 14:31:20 +000010987 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988}
10989
10990static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010991unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010992{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020010993 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
10994 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010995 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010996 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010997}
10998
Guido van Rossumc2504932007-09-18 19:42:40 +000010999/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011000 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011001static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011002unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011003{
Guido van Rossumc2504932007-09-18 19:42:40 +000011004 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011005 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011006
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011007 if (_PyUnicode_HASH(self) != -1)
11008 return _PyUnicode_HASH(self);
11009 if (PyUnicode_READY(self) == -1)
11010 return -1;
11011 len = PyUnicode_GET_LENGTH(self);
11012
11013 /* The hash function as a macro, gets expanded three times below. */
11014#define HASH(P) \
11015 x = (Py_uhash_t)*P << 7; \
11016 while (--len >= 0) \
11017 x = (1000003*x) ^ (Py_uhash_t)*P++;
11018
11019 switch (PyUnicode_KIND(self)) {
11020 case PyUnicode_1BYTE_KIND: {
11021 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11022 HASH(c);
11023 break;
11024 }
11025 case PyUnicode_2BYTE_KIND: {
11026 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11027 HASH(s);
11028 break;
11029 }
11030 default: {
11031 Py_UCS4 *l;
11032 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11033 "Impossible switch case in unicode_hash");
11034 l = PyUnicode_4BYTE_DATA(self);
11035 HASH(l);
11036 break;
11037 }
11038 }
11039 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11040
Guido van Rossumc2504932007-09-18 19:42:40 +000011041 if (x == -1)
11042 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011043 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011044 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011045}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011046#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011047
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011048PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011049 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011050\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011051Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011052
11053static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011054unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011055{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011056 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011057 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011058 Py_ssize_t start;
11059 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011060
Jesus Ceaac451502011-04-20 17:09:23 +020011061 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11062 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011063 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011064
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011065 if (PyUnicode_READY(self) == -1)
11066 return NULL;
11067 if (PyUnicode_READY(substring) == -1)
11068 return NULL;
11069
Victor Stinner7931d9a2011-11-04 00:22:48 +010011070 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071
11072 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011074 if (result == -2)
11075 return NULL;
11076
Guido van Rossumd57fd912000-03-10 22:53:23 +000011077 if (result < 0) {
11078 PyErr_SetString(PyExc_ValueError, "substring not found");
11079 return NULL;
11080 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011081
Christian Heimes217cfd12007-12-02 14:31:20 +000011082 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011083}
11084
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011085PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011086 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011087\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011088Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011089at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090
11091static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011092unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011093{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011094 Py_ssize_t i, length;
11095 int kind;
11096 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097 int cased;
11098
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011099 if (PyUnicode_READY(self) == -1)
11100 return NULL;
11101 length = PyUnicode_GET_LENGTH(self);
11102 kind = PyUnicode_KIND(self);
11103 data = PyUnicode_DATA(self);
11104
Guido van Rossumd57fd912000-03-10 22:53:23 +000011105 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011106 if (length == 1)
11107 return PyBool_FromLong(
11108 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011110 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011111 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011112 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011113
Guido van Rossumd57fd912000-03-10 22:53:23 +000011114 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011115 for (i = 0; i < length; i++) {
11116 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011117
Benjamin Peterson29060642009-01-31 22:14:21 +000011118 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11119 return PyBool_FromLong(0);
11120 else if (!cased && Py_UNICODE_ISLOWER(ch))
11121 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011122 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011123 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011124}
11125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011126PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011127 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011128\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011129Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011130at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131
11132static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011133unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011134{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011135 Py_ssize_t i, length;
11136 int kind;
11137 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011138 int cased;
11139
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011140 if (PyUnicode_READY(self) == -1)
11141 return NULL;
11142 length = PyUnicode_GET_LENGTH(self);
11143 kind = PyUnicode_KIND(self);
11144 data = PyUnicode_DATA(self);
11145
Guido van Rossumd57fd912000-03-10 22:53:23 +000011146 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011147 if (length == 1)
11148 return PyBool_FromLong(
11149 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011151 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011152 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011153 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011154
Guido van Rossumd57fd912000-03-10 22:53:23 +000011155 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011156 for (i = 0; i < length; i++) {
11157 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011158
Benjamin Peterson29060642009-01-31 22:14:21 +000011159 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11160 return PyBool_FromLong(0);
11161 else if (!cased && Py_UNICODE_ISUPPER(ch))
11162 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011163 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011164 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011165}
11166
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011167PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011168 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011169\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011170Return True if S is a titlecased string and there is at least one\n\
11171character in S, i.e. upper- and titlecase characters may only\n\
11172follow uncased characters and lowercase characters only cased ones.\n\
11173Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011174
11175static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011176unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011177{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 Py_ssize_t i, length;
11179 int kind;
11180 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181 int cased, previous_is_cased;
11182
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011183 if (PyUnicode_READY(self) == -1)
11184 return NULL;
11185 length = PyUnicode_GET_LENGTH(self);
11186 kind = PyUnicode_KIND(self);
11187 data = PyUnicode_DATA(self);
11188
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011190 if (length == 1) {
11191 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11192 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11193 (Py_UNICODE_ISUPPER(ch) != 0));
11194 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011196 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011197 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011198 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011199
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200 cased = 0;
11201 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011202 for (i = 0; i < length; i++) {
11203 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011204
Benjamin Peterson29060642009-01-31 22:14:21 +000011205 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11206 if (previous_is_cased)
11207 return PyBool_FromLong(0);
11208 previous_is_cased = 1;
11209 cased = 1;
11210 }
11211 else if (Py_UNICODE_ISLOWER(ch)) {
11212 if (!previous_is_cased)
11213 return PyBool_FromLong(0);
11214 previous_is_cased = 1;
11215 cased = 1;
11216 }
11217 else
11218 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011219 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011220 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221}
11222
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011223PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011225\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011226Return True if all characters in S are whitespace\n\
11227and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011228
11229static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011230unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011231{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011232 Py_ssize_t i, length;
11233 int kind;
11234 void *data;
11235
11236 if (PyUnicode_READY(self) == -1)
11237 return NULL;
11238 length = PyUnicode_GET_LENGTH(self);
11239 kind = PyUnicode_KIND(self);
11240 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011241
Guido van Rossumd57fd912000-03-10 22:53:23 +000011242 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011243 if (length == 1)
11244 return PyBool_FromLong(
11245 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
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
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011251 for (i = 0; i < length; i++) {
11252 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011253 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011254 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011255 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011256 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257}
11258
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011259PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011260 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011261\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011262Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011263and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011264
11265static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011266unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011267{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011268 Py_ssize_t i, length;
11269 int kind;
11270 void *data;
11271
11272 if (PyUnicode_READY(self) == -1)
11273 return NULL;
11274 length = PyUnicode_GET_LENGTH(self);
11275 kind = PyUnicode_KIND(self);
11276 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011277
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011278 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011279 if (length == 1)
11280 return PyBool_FromLong(
11281 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011282
11283 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011284 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011285 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011286
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011287 for (i = 0; i < length; i++) {
11288 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011289 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011290 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011291 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011292}
11293
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011294PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011295 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011296\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011297Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011298and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011299
11300static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011301unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011302{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011303 int kind;
11304 void *data;
11305 Py_ssize_t len, i;
11306
11307 if (PyUnicode_READY(self) == -1)
11308 return NULL;
11309
11310 kind = PyUnicode_KIND(self);
11311 data = PyUnicode_DATA(self);
11312 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011313
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011314 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011315 if (len == 1) {
11316 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11317 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11318 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011319
11320 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011321 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011322 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011323
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011324 for (i = 0; i < len; i++) {
11325 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011326 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011327 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011329 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011330}
11331
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011332PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011333 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011334\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011335Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011336False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011337
11338static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011339unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011340{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011341 Py_ssize_t i, length;
11342 int kind;
11343 void *data;
11344
11345 if (PyUnicode_READY(self) == -1)
11346 return NULL;
11347 length = PyUnicode_GET_LENGTH(self);
11348 kind = PyUnicode_KIND(self);
11349 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011350
Guido van Rossumd57fd912000-03-10 22:53:23 +000011351 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011352 if (length == 1)
11353 return PyBool_FromLong(
11354 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011355
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011356 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011357 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011358 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011359
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011360 for (i = 0; i < length; i++) {
11361 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011362 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011364 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011365}
11366
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011367PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011368 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011369\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011370Return True if all characters in S are digits\n\
11371and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011372
11373static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011374unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011375{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011376 Py_ssize_t i, length;
11377 int kind;
11378 void *data;
11379
11380 if (PyUnicode_READY(self) == -1)
11381 return NULL;
11382 length = PyUnicode_GET_LENGTH(self);
11383 kind = PyUnicode_KIND(self);
11384 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011385
Guido van Rossumd57fd912000-03-10 22:53:23 +000011386 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011387 if (length == 1) {
11388 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11389 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11390 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011392 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011393 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011395
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011396 for (i = 0; i < length; i++) {
11397 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011398 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011399 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011400 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401}
11402
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011403PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011404 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011405\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011406Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011407False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011408
11409static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011410unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011412 Py_ssize_t i, length;
11413 int kind;
11414 void *data;
11415
11416 if (PyUnicode_READY(self) == -1)
11417 return NULL;
11418 length = PyUnicode_GET_LENGTH(self);
11419 kind = PyUnicode_KIND(self);
11420 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011421
Guido van Rossumd57fd912000-03-10 22:53:23 +000011422 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011423 if (length == 1)
11424 return PyBool_FromLong(
11425 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011426
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011427 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011428 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011429 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011430
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011431 for (i = 0; i < length; i++) {
11432 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011433 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011435 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011436}
11437
Martin v. Löwis47383402007-08-15 07:32:56 +000011438int
11439PyUnicode_IsIdentifier(PyObject *self)
11440{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011441 int kind;
11442 void *data;
11443 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011444 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011445
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011446 if (PyUnicode_READY(self) == -1) {
11447 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011448 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 }
11450
11451 /* Special case for empty strings */
11452 if (PyUnicode_GET_LENGTH(self) == 0)
11453 return 0;
11454 kind = PyUnicode_KIND(self);
11455 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011456
11457 /* PEP 3131 says that the first character must be in
11458 XID_Start and subsequent characters in XID_Continue,
11459 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011460 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011461 letters, digits, underscore). However, given the current
11462 definition of XID_Start and XID_Continue, it is sufficient
11463 to check just for these, except that _ must be allowed
11464 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011465 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011466 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011467 return 0;
11468
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011469 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011470 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011471 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011472 return 1;
11473}
11474
11475PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011476 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011477\n\
11478Return True if S is a valid identifier according\n\
11479to the language definition.");
11480
11481static PyObject*
11482unicode_isidentifier(PyObject *self)
11483{
11484 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11485}
11486
Georg Brandl559e5d72008-06-11 18:37:52 +000011487PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011488 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011489\n\
11490Return True if all characters in S are considered\n\
11491printable in repr() or S is empty, False otherwise.");
11492
11493static PyObject*
11494unicode_isprintable(PyObject *self)
11495{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 Py_ssize_t i, length;
11497 int kind;
11498 void *data;
11499
11500 if (PyUnicode_READY(self) == -1)
11501 return NULL;
11502 length = PyUnicode_GET_LENGTH(self);
11503 kind = PyUnicode_KIND(self);
11504 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011505
11506 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011507 if (length == 1)
11508 return PyBool_FromLong(
11509 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011510
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011511 for (i = 0; i < length; i++) {
11512 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011513 Py_RETURN_FALSE;
11514 }
11515 }
11516 Py_RETURN_TRUE;
11517}
11518
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011519PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011520 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011521\n\
11522Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011523iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011524
11525static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011526unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011527{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011528 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011529}
11530
Martin v. Löwis18e16552006-02-15 17:27:45 +000011531static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011532unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011533{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011534 if (PyUnicode_READY(self) == -1)
11535 return -1;
11536 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011537}
11538
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011539PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011540 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011541\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011542Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011543done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011544
11545static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011546unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011548 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011549 Py_UCS4 fillchar = ' ';
11550
11551 if (PyUnicode_READY(self) == -1)
11552 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011553
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011554 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555 return NULL;
11556
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011557 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011558 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011559 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011560 }
11561
Victor Stinner7931d9a2011-11-04 00:22:48 +010011562 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563}
11564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011565PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011568Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011569
11570static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011571unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011572{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573 return fixup(self, fixlower);
11574}
11575
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011576#define LEFTSTRIP 0
11577#define RIGHTSTRIP 1
11578#define BOTHSTRIP 2
11579
11580/* Arrays indexed by above */
11581static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11582
11583#define STRIPNAME(i) (stripformat[i]+3)
11584
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011585/* externally visible for str.strip(unicode) */
11586PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011587_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011588{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011589 void *data;
11590 int kind;
11591 Py_ssize_t i, j, len;
11592 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011593
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011594 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11595 return NULL;
11596
11597 kind = PyUnicode_KIND(self);
11598 data = PyUnicode_DATA(self);
11599 len = PyUnicode_GET_LENGTH(self);
11600 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11601 PyUnicode_DATA(sepobj),
11602 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011603
Benjamin Peterson14339b62009-01-31 16:36:08 +000011604 i = 0;
11605 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011606 while (i < len &&
11607 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011608 i++;
11609 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011610 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011611
Benjamin Peterson14339b62009-01-31 16:36:08 +000011612 j = len;
11613 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011614 do {
11615 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011616 } while (j >= i &&
11617 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011618 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011619 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011620
Victor Stinner7931d9a2011-11-04 00:22:48 +010011621 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011622}
11623
11624PyObject*
11625PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11626{
11627 unsigned char *data;
11628 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011629 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011630
Victor Stinnerde636f32011-10-01 03:55:54 +020011631 if (PyUnicode_READY(self) == -1)
11632 return NULL;
11633
11634 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11635
Victor Stinner12bab6d2011-10-01 01:53:49 +020011636 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011637 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011638 if (PyUnicode_CheckExact(self)) {
11639 Py_INCREF(self);
11640 return self;
11641 }
11642 else
11643 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011644 }
11645
Victor Stinner12bab6d2011-10-01 01:53:49 +020011646 length = end - start;
11647 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011648 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011649
Victor Stinnerde636f32011-10-01 03:55:54 +020011650 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011651 PyErr_SetString(PyExc_IndexError, "string index out of range");
11652 return NULL;
11653 }
11654
Victor Stinnerb9275c12011-10-05 14:01:42 +020011655 if (PyUnicode_IS_ASCII(self)) {
11656 kind = PyUnicode_KIND(self);
11657 data = PyUnicode_1BYTE_DATA(self);
11658 return unicode_fromascii(data + start, length);
11659 }
11660 else {
11661 kind = PyUnicode_KIND(self);
11662 data = PyUnicode_1BYTE_DATA(self);
11663 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011664 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011665 length);
11666 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011667}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011668
11669static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011670do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011671{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011672 int kind;
11673 void *data;
11674 Py_ssize_t len, i, j;
11675
11676 if (PyUnicode_READY(self) == -1)
11677 return NULL;
11678
11679 kind = PyUnicode_KIND(self);
11680 data = PyUnicode_DATA(self);
11681 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011682
Benjamin Peterson14339b62009-01-31 16:36:08 +000011683 i = 0;
11684 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011685 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011686 i++;
11687 }
11688 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011689
Benjamin Peterson14339b62009-01-31 16:36:08 +000011690 j = len;
11691 if (striptype != LEFTSTRIP) {
11692 do {
11693 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011694 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011695 j++;
11696 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011697
Victor Stinner7931d9a2011-11-04 00:22:48 +010011698 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011699}
11700
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011701
11702static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011703do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011704{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011705 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011706
Benjamin Peterson14339b62009-01-31 16:36:08 +000011707 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11708 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011709
Benjamin Peterson14339b62009-01-31 16:36:08 +000011710 if (sep != NULL && sep != Py_None) {
11711 if (PyUnicode_Check(sep))
11712 return _PyUnicode_XStrip(self, striptype, sep);
11713 else {
11714 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011715 "%s arg must be None or str",
11716 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011717 return NULL;
11718 }
11719 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011720
Benjamin Peterson14339b62009-01-31 16:36:08 +000011721 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011722}
11723
11724
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011725PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011726 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011727\n\
11728Return a copy of the string S with leading and trailing\n\
11729whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011730If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011731
11732static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011733unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011734{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011735 if (PyTuple_GET_SIZE(args) == 0)
11736 return do_strip(self, BOTHSTRIP); /* Common case */
11737 else
11738 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011739}
11740
11741
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011742PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011743 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011744\n\
11745Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011746If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011747
11748static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011749unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011750{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011751 if (PyTuple_GET_SIZE(args) == 0)
11752 return do_strip(self, LEFTSTRIP); /* Common case */
11753 else
11754 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011755}
11756
11757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011758PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011759 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760\n\
11761Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011762If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011763
11764static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011765unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011766{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011767 if (PyTuple_GET_SIZE(args) == 0)
11768 return do_strip(self, RIGHTSTRIP); /* Common case */
11769 else
11770 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011771}
11772
11773
Guido van Rossumd57fd912000-03-10 22:53:23 +000011774static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011775unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011776{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011777 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011778 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011779
Georg Brandl222de0f2009-04-12 12:01:50 +000011780 if (len < 1) {
11781 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011782 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011783 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011784
Tim Peters7a29bd52001-09-12 03:03:31 +000011785 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011786 /* no repeat, return original string */
11787 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011788 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011789 }
Tim Peters8f422462000-09-09 06:13:41 +000011790
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011791 if (PyUnicode_READY(str) == -1)
11792 return NULL;
11793
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011794 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011795 PyErr_SetString(PyExc_OverflowError,
11796 "repeated string is too long");
11797 return NULL;
11798 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011799 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011800
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011801 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802 if (!u)
11803 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011804 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011806 if (PyUnicode_GET_LENGTH(str) == 1) {
11807 const int kind = PyUnicode_KIND(str);
11808 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11809 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011810 if (kind == PyUnicode_1BYTE_KIND)
11811 memset(to, (unsigned char)fill_char, len);
11812 else {
11813 for (n = 0; n < len; ++n)
11814 PyUnicode_WRITE(kind, to, n, fill_char);
11815 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011816 }
11817 else {
11818 /* number of characters copied this far */
11819 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011820 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011821 char *to = (char *) PyUnicode_DATA(u);
11822 Py_MEMCPY(to, PyUnicode_DATA(str),
11823 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011824 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 n = (done <= nchars-done) ? done : nchars-done;
11826 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011827 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011828 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011829 }
11830
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011831 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011832 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011833}
11834
Alexander Belopolsky40018472011-02-26 01:02:56 +000011835PyObject *
11836PyUnicode_Replace(PyObject *obj,
11837 PyObject *subobj,
11838 PyObject *replobj,
11839 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011840{
11841 PyObject *self;
11842 PyObject *str1;
11843 PyObject *str2;
11844 PyObject *result;
11845
11846 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011847 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011848 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011849 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011850 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011851 Py_DECREF(self);
11852 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011853 }
11854 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011855 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011856 Py_DECREF(self);
11857 Py_DECREF(str1);
11858 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011860 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011861 Py_DECREF(self);
11862 Py_DECREF(str1);
11863 Py_DECREF(str2);
11864 return result;
11865}
11866
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011867PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011868 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011869\n\
11870Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011871old replaced by new. If the optional argument count is\n\
11872given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011873
11874static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011875unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011876{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011877 PyObject *str1;
11878 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011879 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011880 PyObject *result;
11881
Martin v. Löwis18e16552006-02-15 17:27:45 +000011882 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011883 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011884 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011885 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 str1 = PyUnicode_FromObject(str1);
11887 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11888 return NULL;
11889 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011890 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011891 Py_DECREF(str1);
11892 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011893 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011894
11895 result = replace(self, str1, str2, maxcount);
11896
11897 Py_DECREF(str1);
11898 Py_DECREF(str2);
11899 return result;
11900}
11901
Alexander Belopolsky40018472011-02-26 01:02:56 +000011902static PyObject *
11903unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011904{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011905 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011906 Py_ssize_t isize;
11907 Py_ssize_t osize, squote, dquote, i, o;
11908 Py_UCS4 max, quote;
11909 int ikind, okind;
11910 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011911
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011913 return NULL;
11914
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011915 isize = PyUnicode_GET_LENGTH(unicode);
11916 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011917
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011918 /* Compute length of output, quote characters, and
11919 maximum character */
11920 osize = 2; /* quotes */
11921 max = 127;
11922 squote = dquote = 0;
11923 ikind = PyUnicode_KIND(unicode);
11924 for (i = 0; i < isize; i++) {
11925 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11926 switch (ch) {
11927 case '\'': squote++; osize++; break;
11928 case '"': dquote++; osize++; break;
11929 case '\\': case '\t': case '\r': case '\n':
11930 osize += 2; break;
11931 default:
11932 /* Fast-path ASCII */
11933 if (ch < ' ' || ch == 0x7f)
11934 osize += 4; /* \xHH */
11935 else if (ch < 0x7f)
11936 osize++;
11937 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11938 osize++;
11939 max = ch > max ? ch : max;
11940 }
11941 else if (ch < 0x100)
11942 osize += 4; /* \xHH */
11943 else if (ch < 0x10000)
11944 osize += 6; /* \uHHHH */
11945 else
11946 osize += 10; /* \uHHHHHHHH */
11947 }
11948 }
11949
11950 quote = '\'';
11951 if (squote) {
11952 if (dquote)
11953 /* Both squote and dquote present. Use squote,
11954 and escape them */
11955 osize += squote;
11956 else
11957 quote = '"';
11958 }
11959
11960 repr = PyUnicode_New(osize, max);
11961 if (repr == NULL)
11962 return NULL;
11963 okind = PyUnicode_KIND(repr);
11964 odata = PyUnicode_DATA(repr);
11965
11966 PyUnicode_WRITE(okind, odata, 0, quote);
11967 PyUnicode_WRITE(okind, odata, osize-1, quote);
11968
11969 for (i = 0, o = 1; i < isize; i++) {
11970 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011971
11972 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011973 if ((ch == quote) || (ch == '\\')) {
11974 PyUnicode_WRITE(okind, odata, o++, '\\');
11975 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011976 continue;
11977 }
11978
Benjamin Peterson29060642009-01-31 22:14:21 +000011979 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011980 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011981 PyUnicode_WRITE(okind, odata, o++, '\\');
11982 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011983 }
11984 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011985 PyUnicode_WRITE(okind, odata, o++, '\\');
11986 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011987 }
11988 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011989 PyUnicode_WRITE(okind, odata, o++, '\\');
11990 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000011991 }
11992
11993 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000011994 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011995 PyUnicode_WRITE(okind, odata, o++, '\\');
11996 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020011997 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
11998 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011999 }
12000
Georg Brandl559e5d72008-06-11 18:37:52 +000012001 /* Copy ASCII characters as-is */
12002 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012003 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012004 }
12005
Benjamin Peterson29060642009-01-31 22:14:21 +000012006 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012007 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012008 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012009 (categories Z* and C* except ASCII space)
12010 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012012 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012013 if (ch <= 0xff) {
12014 PyUnicode_WRITE(okind, odata, o++, '\\');
12015 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012016 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12017 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012018 }
12019 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012020 else if (ch >= 0x10000) {
12021 PyUnicode_WRITE(okind, odata, o++, '\\');
12022 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012023 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12025 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12026 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12027 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12028 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12029 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12030 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012031 }
12032 /* Map 16-bit characters to '\uxxxx' */
12033 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012034 PyUnicode_WRITE(okind, odata, o++, '\\');
12035 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012036 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12037 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12038 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12039 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012040 }
12041 }
12042 /* Copy characters as-is */
12043 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012044 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012045 }
12046 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012047 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012048 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012049 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012050 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012051}
12052
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012053PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012054 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012055\n\
12056Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012057such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012058arguments start and end are interpreted as in slice notation.\n\
12059\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012060Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012061
12062static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012063unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012064{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012065 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012066 Py_ssize_t start;
12067 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012068 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012069
Jesus Ceaac451502011-04-20 17:09:23 +020012070 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12071 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012072 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012073
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 if (PyUnicode_READY(self) == -1)
12075 return NULL;
12076 if (PyUnicode_READY(substring) == -1)
12077 return NULL;
12078
Victor Stinner7931d9a2011-11-04 00:22:48 +010012079 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012080
12081 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012082
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012083 if (result == -2)
12084 return NULL;
12085
Christian Heimes217cfd12007-12-02 14:31:20 +000012086 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087}
12088
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012089PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012090 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012091\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012092Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012093
12094static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012095unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012096{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012097 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012098 Py_ssize_t start;
12099 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012100 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012101
Jesus Ceaac451502011-04-20 17:09:23 +020012102 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12103 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012104 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012105
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012106 if (PyUnicode_READY(self) == -1)
12107 return NULL;
12108 if (PyUnicode_READY(substring) == -1)
12109 return NULL;
12110
Victor Stinner7931d9a2011-11-04 00:22:48 +010012111 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012112
12113 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012115 if (result == -2)
12116 return NULL;
12117
Guido van Rossumd57fd912000-03-10 22:53:23 +000012118 if (result < 0) {
12119 PyErr_SetString(PyExc_ValueError, "substring not found");
12120 return NULL;
12121 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012122
Christian Heimes217cfd12007-12-02 14:31:20 +000012123 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012124}
12125
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012126PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012127 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012128\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012129Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012130done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
12132static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012133unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012134{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012135 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012136 Py_UCS4 fillchar = ' ';
12137
Victor Stinnere9a29352011-10-01 02:14:59 +020012138 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012139 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012140
Victor Stinnere9a29352011-10-01 02:14:59 +020012141 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012142 return NULL;
12143
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012144 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012145 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012146 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012147 }
12148
Victor Stinner7931d9a2011-11-04 00:22:48 +010012149 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150}
12151
Alexander Belopolsky40018472011-02-26 01:02:56 +000012152PyObject *
12153PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154{
12155 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012156
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157 s = PyUnicode_FromObject(s);
12158 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012159 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012160 if (sep != NULL) {
12161 sep = PyUnicode_FromObject(sep);
12162 if (sep == NULL) {
12163 Py_DECREF(s);
12164 return NULL;
12165 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012166 }
12167
Victor Stinner9310abb2011-10-05 00:59:23 +020012168 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012169
12170 Py_DECREF(s);
12171 Py_XDECREF(sep);
12172 return result;
12173}
12174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012175PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012176 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012177\n\
12178Return a list of the words in S, using sep as the\n\
12179delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012180splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012181whitespace string is a separator and empty strings are\n\
12182removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183
12184static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012185unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012186{
12187 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012188 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012189
Martin v. Löwis18e16552006-02-15 17:27:45 +000012190 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012191 return NULL;
12192
12193 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012194 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012196 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012197 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012198 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012199}
12200
Thomas Wouters477c8d52006-05-27 19:21:47 +000012201PyObject *
12202PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12203{
12204 PyObject* str_obj;
12205 PyObject* sep_obj;
12206 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012207 int kind1, kind2, kind;
12208 void *buf1 = NULL, *buf2 = NULL;
12209 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012210
12211 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012212 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012213 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012214 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012215 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012216 Py_DECREF(str_obj);
12217 return NULL;
12218 }
12219
Victor Stinner14f8f022011-10-05 20:58:25 +020012220 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012221 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012222 kind = Py_MAX(kind1, kind2);
12223 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012224 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012225 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012226 if (!buf1)
12227 goto onError;
12228 buf2 = PyUnicode_DATA(sep_obj);
12229 if (kind2 != kind)
12230 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12231 if (!buf2)
12232 goto onError;
12233 len1 = PyUnicode_GET_LENGTH(str_obj);
12234 len2 = PyUnicode_GET_LENGTH(sep_obj);
12235
Victor Stinner14f8f022011-10-05 20:58:25 +020012236 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012237 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012238 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12239 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12240 else
12241 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012242 break;
12243 case PyUnicode_2BYTE_KIND:
12244 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12245 break;
12246 case PyUnicode_4BYTE_KIND:
12247 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12248 break;
12249 default:
12250 assert(0);
12251 out = 0;
12252 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012253
12254 Py_DECREF(sep_obj);
12255 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012256 if (kind1 != kind)
12257 PyMem_Free(buf1);
12258 if (kind2 != kind)
12259 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012260
12261 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012262 onError:
12263 Py_DECREF(sep_obj);
12264 Py_DECREF(str_obj);
12265 if (kind1 != kind && buf1)
12266 PyMem_Free(buf1);
12267 if (kind2 != kind && buf2)
12268 PyMem_Free(buf2);
12269 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012270}
12271
12272
12273PyObject *
12274PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12275{
12276 PyObject* str_obj;
12277 PyObject* sep_obj;
12278 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012279 int kind1, kind2, kind;
12280 void *buf1 = NULL, *buf2 = NULL;
12281 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012282
12283 str_obj = PyUnicode_FromObject(str_in);
12284 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012285 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012286 sep_obj = PyUnicode_FromObject(sep_in);
12287 if (!sep_obj) {
12288 Py_DECREF(str_obj);
12289 return NULL;
12290 }
12291
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012292 kind1 = PyUnicode_KIND(str_in);
12293 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012294 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012295 buf1 = PyUnicode_DATA(str_in);
12296 if (kind1 != kind)
12297 buf1 = _PyUnicode_AsKind(str_in, kind);
12298 if (!buf1)
12299 goto onError;
12300 buf2 = PyUnicode_DATA(sep_obj);
12301 if (kind2 != kind)
12302 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12303 if (!buf2)
12304 goto onError;
12305 len1 = PyUnicode_GET_LENGTH(str_obj);
12306 len2 = PyUnicode_GET_LENGTH(sep_obj);
12307
12308 switch(PyUnicode_KIND(str_in)) {
12309 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012310 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12311 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12312 else
12313 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012314 break;
12315 case PyUnicode_2BYTE_KIND:
12316 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12317 break;
12318 case PyUnicode_4BYTE_KIND:
12319 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12320 break;
12321 default:
12322 assert(0);
12323 out = 0;
12324 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012325
12326 Py_DECREF(sep_obj);
12327 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012328 if (kind1 != kind)
12329 PyMem_Free(buf1);
12330 if (kind2 != kind)
12331 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012332
12333 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012334 onError:
12335 Py_DECREF(sep_obj);
12336 Py_DECREF(str_obj);
12337 if (kind1 != kind && buf1)
12338 PyMem_Free(buf1);
12339 if (kind2 != kind && buf2)
12340 PyMem_Free(buf2);
12341 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012342}
12343
12344PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012345 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012346\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012347Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012348the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012349found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012350
12351static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012352unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012353{
Victor Stinner9310abb2011-10-05 00:59:23 +020012354 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012355}
12356
12357PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012358 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012359\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012360Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012361the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012362separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012363
12364static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012365unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012366{
Victor Stinner9310abb2011-10-05 00:59:23 +020012367 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012368}
12369
Alexander Belopolsky40018472011-02-26 01:02:56 +000012370PyObject *
12371PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012372{
12373 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012374
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012375 s = PyUnicode_FromObject(s);
12376 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012377 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012378 if (sep != NULL) {
12379 sep = PyUnicode_FromObject(sep);
12380 if (sep == NULL) {
12381 Py_DECREF(s);
12382 return NULL;
12383 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012384 }
12385
Victor Stinner9310abb2011-10-05 00:59:23 +020012386 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012387
12388 Py_DECREF(s);
12389 Py_XDECREF(sep);
12390 return result;
12391}
12392
12393PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012394 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012395\n\
12396Return a list of the words in S, using sep as the\n\
12397delimiter string, starting at the end of the string and\n\
12398working to the front. If maxsplit is given, at most maxsplit\n\
12399splits are done. If sep is not specified, any whitespace string\n\
12400is a separator.");
12401
12402static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012403unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012404{
12405 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012406 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012407
Martin v. Löwis18e16552006-02-15 17:27:45 +000012408 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012409 return NULL;
12410
12411 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012412 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012413 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012414 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012415 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012416 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012417}
12418
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012419PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012420 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012421\n\
12422Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012423Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012424is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012425
12426static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012427unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012428{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012429 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012430 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012431
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012432 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12433 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012434 return NULL;
12435
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012436 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012437}
12438
12439static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012440PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012441{
Walter Dörwald346737f2007-05-31 10:44:43 +000012442 if (PyUnicode_CheckExact(self)) {
12443 Py_INCREF(self);
12444 return self;
12445 } else
12446 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012447 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012448}
12449
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012450PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012451 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012452\n\
12453Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012454and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012455
12456static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012457unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012458{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012459 return fixup(self, fixswapcase);
12460}
12461
Georg Brandlceee0772007-11-27 23:48:05 +000012462PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012463 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012464\n\
12465Return a translation table usable for str.translate().\n\
12466If there is only one argument, it must be a dictionary mapping Unicode\n\
12467ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012468Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012469If there are two arguments, they must be strings of equal length, and\n\
12470in the resulting dictionary, each character in x will be mapped to the\n\
12471character at the same position in y. If there is a third argument, it\n\
12472must be a string, whose characters will be mapped to None in the result.");
12473
12474static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012475unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012476{
12477 PyObject *x, *y = NULL, *z = NULL;
12478 PyObject *new = NULL, *key, *value;
12479 Py_ssize_t i = 0;
12480 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012481
Georg Brandlceee0772007-11-27 23:48:05 +000012482 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12483 return NULL;
12484 new = PyDict_New();
12485 if (!new)
12486 return NULL;
12487 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012488 int x_kind, y_kind, z_kind;
12489 void *x_data, *y_data, *z_data;
12490
Georg Brandlceee0772007-11-27 23:48:05 +000012491 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012492 if (!PyUnicode_Check(x)) {
12493 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12494 "be a string if there is a second argument");
12495 goto err;
12496 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012497 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012498 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12499 "arguments must have equal length");
12500 goto err;
12501 }
12502 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012503 x_kind = PyUnicode_KIND(x);
12504 y_kind = PyUnicode_KIND(y);
12505 x_data = PyUnicode_DATA(x);
12506 y_data = PyUnicode_DATA(y);
12507 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12508 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12509 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012510 if (!key || !value)
12511 goto err;
12512 res = PyDict_SetItem(new, key, value);
12513 Py_DECREF(key);
12514 Py_DECREF(value);
12515 if (res < 0)
12516 goto err;
12517 }
12518 /* create entries for deleting chars in z */
12519 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012520 z_kind = PyUnicode_KIND(z);
12521 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012522 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012523 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012524 if (!key)
12525 goto err;
12526 res = PyDict_SetItem(new, key, Py_None);
12527 Py_DECREF(key);
12528 if (res < 0)
12529 goto err;
12530 }
12531 }
12532 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012533 int kind;
12534 void *data;
12535
Georg Brandlceee0772007-11-27 23:48:05 +000012536 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012537 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012538 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12539 "to maketrans it must be a dict");
12540 goto err;
12541 }
12542 /* copy entries into the new dict, converting string keys to int keys */
12543 while (PyDict_Next(x, &i, &key, &value)) {
12544 if (PyUnicode_Check(key)) {
12545 /* convert string keys to integer keys */
12546 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012547 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012548 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12549 "table must be of length 1");
12550 goto err;
12551 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012552 kind = PyUnicode_KIND(key);
12553 data = PyUnicode_DATA(key);
12554 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012555 if (!newkey)
12556 goto err;
12557 res = PyDict_SetItem(new, newkey, value);
12558 Py_DECREF(newkey);
12559 if (res < 0)
12560 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012561 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012562 /* just keep integer keys */
12563 if (PyDict_SetItem(new, key, value) < 0)
12564 goto err;
12565 } else {
12566 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12567 "be strings or integers");
12568 goto err;
12569 }
12570 }
12571 }
12572 return new;
12573 err:
12574 Py_DECREF(new);
12575 return NULL;
12576}
12577
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012578PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012579 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012580\n\
12581Return a copy of the string S, where all characters have been mapped\n\
12582through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012583Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012584Unmapped characters are left untouched. Characters mapped to None\n\
12585are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012586
12587static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012588unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012589{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012590 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012591}
12592
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012593PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012594 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012595\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012596Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012597
12598static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012599unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012600{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012601 return fixup(self, fixupper);
12602}
12603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012604PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012605 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012607Pad a numeric string S with zeros on the left, to fill a field\n\
12608of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012609
12610static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012611unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012613 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012614 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012615 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616 int kind;
12617 void *data;
12618 Py_UCS4 chr;
12619
12620 if (PyUnicode_READY(self) == -1)
12621 return NULL;
12622
Martin v. Löwis18e16552006-02-15 17:27:45 +000012623 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012624 return NULL;
12625
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012626 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012627 if (PyUnicode_CheckExact(self)) {
12628 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012629 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012630 }
12631 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012632 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012633 }
12634
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012635 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012636
12637 u = pad(self, fill, 0, '0');
12638
Walter Dörwald068325e2002-04-15 13:36:47 +000012639 if (u == NULL)
12640 return NULL;
12641
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642 kind = PyUnicode_KIND(u);
12643 data = PyUnicode_DATA(u);
12644 chr = PyUnicode_READ(kind, data, fill);
12645
12646 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012647 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012648 PyUnicode_WRITE(kind, data, 0, chr);
12649 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650 }
12651
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012652 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012653 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012654}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012655
12656#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012657static PyObject *
12658unicode__decimal2ascii(PyObject *self)
12659{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012660 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012661}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662#endif
12663
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012664PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012665 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012666\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012667Return True if S starts with the specified prefix, False otherwise.\n\
12668With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012669With optional end, stop comparing S at that position.\n\
12670prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012671
12672static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012673unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012674 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012675{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012676 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012677 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012678 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012679 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012680 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681
Jesus Ceaac451502011-04-20 17:09:23 +020012682 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012683 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012684 if (PyTuple_Check(subobj)) {
12685 Py_ssize_t i;
12686 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012687 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012688 if (substring == NULL)
12689 return NULL;
12690 result = tailmatch(self, substring, start, end, -1);
12691 Py_DECREF(substring);
12692 if (result) {
12693 Py_RETURN_TRUE;
12694 }
12695 }
12696 /* nothing matched */
12697 Py_RETURN_FALSE;
12698 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012699 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012700 if (substring == NULL) {
12701 if (PyErr_ExceptionMatches(PyExc_TypeError))
12702 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12703 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012704 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012705 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012706 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012708 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012709}
12710
12711
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012712PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012713 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012714\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012715Return True if S ends with the specified suffix, False otherwise.\n\
12716With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012717With optional end, stop comparing S at that position.\n\
12718suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012719
12720static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012721unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012722 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012723{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012724 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012725 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012726 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012727 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012728 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012729
Jesus Ceaac451502011-04-20 17:09:23 +020012730 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012731 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012732 if (PyTuple_Check(subobj)) {
12733 Py_ssize_t i;
12734 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012735 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012736 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012737 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012738 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012739 result = tailmatch(self, substring, start, end, +1);
12740 Py_DECREF(substring);
12741 if (result) {
12742 Py_RETURN_TRUE;
12743 }
12744 }
12745 Py_RETURN_FALSE;
12746 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012747 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012748 if (substring == NULL) {
12749 if (PyErr_ExceptionMatches(PyExc_TypeError))
12750 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12751 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012752 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012753 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012754 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012756 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012757}
12758
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012759#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012760
12761PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012762 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012763\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012764Return a formatted version of S, using substitutions from args and kwargs.\n\
12765The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012766
Eric Smith27bbca62010-11-04 17:06:58 +000012767PyDoc_STRVAR(format_map__doc__,
12768 "S.format_map(mapping) -> str\n\
12769\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012770Return a formatted version of S, using substitutions from mapping.\n\
12771The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012772
Eric Smith4a7d76d2008-05-30 18:10:19 +000012773static PyObject *
12774unicode__format__(PyObject* self, PyObject* args)
12775{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012776 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012777
12778 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12779 return NULL;
12780
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012781 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012782 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012783 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012784}
12785
Eric Smith8c663262007-08-25 02:26:07 +000012786PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012787 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012788\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012789Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012790
12791static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012792unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012793{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012794 Py_ssize_t size;
12795
12796 /* If it's a compact object, account for base structure +
12797 character data. */
12798 if (PyUnicode_IS_COMPACT_ASCII(v))
12799 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12800 else if (PyUnicode_IS_COMPACT(v))
12801 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012802 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012803 else {
12804 /* If it is a two-block object, account for base object, and
12805 for character block if present. */
12806 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012807 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012809 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012810 }
12811 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012812 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012813 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012814 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012815 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012816 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012817
12818 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012819}
12820
12821PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012822 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012823
12824static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012825unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012826{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012827 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012828 if (!copy)
12829 return NULL;
12830 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012831}
12832
Guido van Rossumd57fd912000-03-10 22:53:23 +000012833static PyMethodDef unicode_methods[] = {
12834
12835 /* Order is according to common usage: often used methods should
12836 appear first, since lookup is done sequentially. */
12837
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012838 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012839 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12840 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012841 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012842 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12843 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12844 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12845 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12846 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12847 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12848 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012849 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012850 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12851 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12852 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012853 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012854 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12855 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12856 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012857 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012858 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012859 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012860 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012861 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12862 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12863 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12864 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12865 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12866 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12867 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12868 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12869 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12870 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12871 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12872 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12873 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12874 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012875 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012876 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012877 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012878 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012879 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012880 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012881 {"maketrans", (PyCFunction) unicode_maketrans,
12882 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012883 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012884#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012885 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012886#endif
12887
12888#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012889 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012890 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012891#endif
12892
Benjamin Peterson14339b62009-01-31 16:36:08 +000012893 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012894 {NULL, NULL}
12895};
12896
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012897static PyObject *
12898unicode_mod(PyObject *v, PyObject *w)
12899{
Brian Curtindfc80e32011-08-10 20:28:54 -050012900 if (!PyUnicode_Check(v))
12901 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012902 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012903}
12904
12905static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012906 0, /*nb_add*/
12907 0, /*nb_subtract*/
12908 0, /*nb_multiply*/
12909 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012910};
12911
Guido van Rossumd57fd912000-03-10 22:53:23 +000012912static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012913 (lenfunc) unicode_length, /* sq_length */
12914 PyUnicode_Concat, /* sq_concat */
12915 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12916 (ssizeargfunc) unicode_getitem, /* sq_item */
12917 0, /* sq_slice */
12918 0, /* sq_ass_item */
12919 0, /* sq_ass_slice */
12920 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012921};
12922
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012923static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012924unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012925{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012926 if (PyUnicode_READY(self) == -1)
12927 return NULL;
12928
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012929 if (PyIndex_Check(item)) {
12930 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012931 if (i == -1 && PyErr_Occurred())
12932 return NULL;
12933 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012934 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012935 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012936 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012937 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012938 PyObject *result;
12939 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012940 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012941 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012943 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012944 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012945 return NULL;
12946 }
12947
12948 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012949 return PyUnicode_New(0, 0);
12950 } else if (start == 0 && step == 1 &&
12951 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012952 PyUnicode_CheckExact(self)) {
12953 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012954 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000012955 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012956 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020012957 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012958 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012959 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012960 src_kind = PyUnicode_KIND(self);
12961 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020012962 if (!PyUnicode_IS_ASCII(self)) {
12963 kind_limit = kind_maxchar_limit(src_kind);
12964 max_char = 0;
12965 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12966 ch = PyUnicode_READ(src_kind, src_data, cur);
12967 if (ch > max_char) {
12968 max_char = ch;
12969 if (max_char >= kind_limit)
12970 break;
12971 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012972 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012973 }
Victor Stinner55c99112011-10-13 01:17:06 +020012974 else
12975 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012976 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012977 if (result == NULL)
12978 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012979 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012980 dest_data = PyUnicode_DATA(result);
12981
12982 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012983 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
12984 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012985 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012986 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012987 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012988 } else {
12989 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
12990 return NULL;
12991 }
12992}
12993
12994static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012995 (lenfunc)unicode_length, /* mp_length */
12996 (binaryfunc)unicode_subscript, /* mp_subscript */
12997 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012998};
12999
Guido van Rossumd57fd912000-03-10 22:53:23 +000013000
Guido van Rossumd57fd912000-03-10 22:53:23 +000013001/* Helpers for PyUnicode_Format() */
13002
13003static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013004getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013005{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013006 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013007 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013008 (*p_argidx)++;
13009 if (arglen < 0)
13010 return args;
13011 else
13012 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013013 }
13014 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013015 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013016 return NULL;
13017}
13018
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013019/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013020
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013021static PyObject *
13022formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013023{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013024 char *p;
13025 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013026 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013027
Guido van Rossumd57fd912000-03-10 22:53:23 +000013028 x = PyFloat_AsDouble(v);
13029 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013030 return NULL;
13031
Guido van Rossumd57fd912000-03-10 22:53:23 +000013032 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013033 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013034
Eric Smith0923d1d2009-04-16 20:16:10 +000013035 p = PyOS_double_to_string(x, type, prec,
13036 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013037 if (p == NULL)
13038 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013039 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013040 PyMem_Free(p);
13041 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042}
13043
Tim Peters38fd5b62000-09-21 05:43:11 +000013044static PyObject*
13045formatlong(PyObject *val, int flags, int prec, int type)
13046{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013047 char *buf;
13048 int len;
13049 PyObject *str; /* temporary string object. */
13050 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013051
Benjamin Peterson14339b62009-01-31 16:36:08 +000013052 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13053 if (!str)
13054 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013055 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013056 Py_DECREF(str);
13057 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013058}
13059
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013060static Py_UCS4
13061formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013062{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013063 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013064 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013065 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013066 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013067 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013068 goto onError;
13069 }
13070 else {
13071 /* Integer input truncated to a character */
13072 long x;
13073 x = PyLong_AsLong(v);
13074 if (x == -1 && PyErr_Occurred())
13075 goto onError;
13076
13077 if (x < 0 || x > 0x10ffff) {
13078 PyErr_SetString(PyExc_OverflowError,
13079 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013080 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013081 }
13082
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013083 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013084 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013085
Benjamin Peterson29060642009-01-31 22:14:21 +000013086 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013087 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013088 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013089 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013090}
13091
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013092static int
13093repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13094{
13095 int r;
13096 assert(count > 0);
13097 assert(PyUnicode_Check(obj));
13098 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013099 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013100 if (repeated == NULL)
13101 return -1;
13102 r = _PyAccu_Accumulate(acc, repeated);
13103 Py_DECREF(repeated);
13104 return r;
13105 }
13106 else {
13107 do {
13108 if (_PyAccu_Accumulate(acc, obj))
13109 return -1;
13110 } while (--count);
13111 return 0;
13112 }
13113}
13114
Alexander Belopolsky40018472011-02-26 01:02:56 +000013115PyObject *
13116PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013117{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013118 void *fmt;
13119 int fmtkind;
13120 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013121 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013122 int r;
13123 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013124 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013125 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013126 PyObject *temp = NULL;
13127 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013128 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013129 _PyAccu acc;
13130 static PyObject *plus, *minus, *blank, *zero, *percent;
13131
13132 if (!plus && !(plus = get_latin1_char('+')))
13133 return NULL;
13134 if (!minus && !(minus = get_latin1_char('-')))
13135 return NULL;
13136 if (!blank && !(blank = get_latin1_char(' ')))
13137 return NULL;
13138 if (!zero && !(zero = get_latin1_char('0')))
13139 return NULL;
13140 if (!percent && !(percent = get_latin1_char('%')))
13141 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013142
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013144 PyErr_BadInternalCall();
13145 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013146 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013147 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013148 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013149 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013150 if (_PyAccu_Init(&acc))
13151 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013152 fmt = PyUnicode_DATA(uformat);
13153 fmtkind = PyUnicode_KIND(uformat);
13154 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13155 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013156
Guido van Rossumd57fd912000-03-10 22:53:23 +000013157 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013158 arglen = PyTuple_Size(args);
13159 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013160 }
13161 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013162 arglen = -1;
13163 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013164 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013165 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013166 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013167 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013168
13169 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013170 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013171 PyObject *nonfmt;
13172 Py_ssize_t nonfmtpos;
13173 nonfmtpos = fmtpos++;
13174 while (fmtcnt >= 0 &&
13175 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13176 fmtpos++;
13177 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013178 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013179 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013180 if (nonfmt == NULL)
13181 goto onError;
13182 r = _PyAccu_Accumulate(&acc, nonfmt);
13183 Py_DECREF(nonfmt);
13184 if (r)
13185 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013186 }
13187 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013188 /* Got a format specifier */
13189 int flags = 0;
13190 Py_ssize_t width = -1;
13191 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013192 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013193 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013194 int isnumok;
13195 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013196 void *pbuf = NULL;
13197 Py_ssize_t pindex, len;
13198 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013199
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013200 fmtpos++;
13201 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13202 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013203 Py_ssize_t keylen;
13204 PyObject *key;
13205 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013206
Benjamin Peterson29060642009-01-31 22:14:21 +000013207 if (dict == NULL) {
13208 PyErr_SetString(PyExc_TypeError,
13209 "format requires a mapping");
13210 goto onError;
13211 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013212 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013213 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013214 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013215 /* Skip over balanced parentheses */
13216 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013217 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013218 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013219 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013220 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013221 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013222 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013223 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013224 if (fmtcnt < 0 || pcount > 0) {
13225 PyErr_SetString(PyExc_ValueError,
13226 "incomplete format key");
13227 goto onError;
13228 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013229 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013230 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013231 if (key == NULL)
13232 goto onError;
13233 if (args_owned) {
13234 Py_DECREF(args);
13235 args_owned = 0;
13236 }
13237 args = PyObject_GetItem(dict, key);
13238 Py_DECREF(key);
13239 if (args == NULL) {
13240 goto onError;
13241 }
13242 args_owned = 1;
13243 arglen = -1;
13244 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013245 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013247 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 case '-': flags |= F_LJUST; continue;
13249 case '+': flags |= F_SIGN; continue;
13250 case ' ': flags |= F_BLANK; continue;
13251 case '#': flags |= F_ALT; continue;
13252 case '0': flags |= F_ZERO; continue;
13253 }
13254 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013255 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013256 if (c == '*') {
13257 v = getnextarg(args, arglen, &argidx);
13258 if (v == NULL)
13259 goto onError;
13260 if (!PyLong_Check(v)) {
13261 PyErr_SetString(PyExc_TypeError,
13262 "* wants int");
13263 goto onError;
13264 }
13265 width = PyLong_AsLong(v);
13266 if (width == -1 && PyErr_Occurred())
13267 goto onError;
13268 if (width < 0) {
13269 flags |= F_LJUST;
13270 width = -width;
13271 }
13272 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 }
13275 else if (c >= '0' && c <= '9') {
13276 width = c - '0';
13277 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013278 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013279 if (c < '0' || c > '9')
13280 break;
13281 if ((width*10) / 10 != width) {
13282 PyErr_SetString(PyExc_ValueError,
13283 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013284 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013285 }
13286 width = width*10 + (c - '0');
13287 }
13288 }
13289 if (c == '.') {
13290 prec = 0;
13291 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013292 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013293 if (c == '*') {
13294 v = getnextarg(args, arglen, &argidx);
13295 if (v == NULL)
13296 goto onError;
13297 if (!PyLong_Check(v)) {
13298 PyErr_SetString(PyExc_TypeError,
13299 "* wants int");
13300 goto onError;
13301 }
13302 prec = PyLong_AsLong(v);
13303 if (prec == -1 && PyErr_Occurred())
13304 goto onError;
13305 if (prec < 0)
13306 prec = 0;
13307 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013308 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013309 }
13310 else if (c >= '0' && c <= '9') {
13311 prec = c - '0';
13312 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013313 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013314 if (c < '0' || c > '9')
13315 break;
13316 if ((prec*10) / 10 != prec) {
13317 PyErr_SetString(PyExc_ValueError,
13318 "prec too big");
13319 goto onError;
13320 }
13321 prec = prec*10 + (c - '0');
13322 }
13323 }
13324 } /* prec */
13325 if (fmtcnt >= 0) {
13326 if (c == 'h' || c == 'l' || c == 'L') {
13327 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013328 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013329 }
13330 }
13331 if (fmtcnt < 0) {
13332 PyErr_SetString(PyExc_ValueError,
13333 "incomplete format");
13334 goto onError;
13335 }
13336 if (c != '%') {
13337 v = getnextarg(args, arglen, &argidx);
13338 if (v == NULL)
13339 goto onError;
13340 }
13341 sign = 0;
13342 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013343 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013344 switch (c) {
13345
13346 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013347 _PyAccu_Accumulate(&acc, percent);
13348 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013349
13350 case 's':
13351 case 'r':
13352 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013353 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013354 temp = v;
13355 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013356 }
13357 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013358 if (c == 's')
13359 temp = PyObject_Str(v);
13360 else if (c == 'r')
13361 temp = PyObject_Repr(v);
13362 else
13363 temp = PyObject_ASCII(v);
13364 if (temp == NULL)
13365 goto onError;
13366 if (PyUnicode_Check(temp))
13367 /* nothing to do */;
13368 else {
13369 Py_DECREF(temp);
13370 PyErr_SetString(PyExc_TypeError,
13371 "%s argument has non-string str()");
13372 goto onError;
13373 }
13374 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013375 if (PyUnicode_READY(temp) == -1) {
13376 Py_CLEAR(temp);
13377 goto onError;
13378 }
13379 pbuf = PyUnicode_DATA(temp);
13380 kind = PyUnicode_KIND(temp);
13381 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013382 if (prec >= 0 && len > prec)
13383 len = prec;
13384 break;
13385
13386 case 'i':
13387 case 'd':
13388 case 'u':
13389 case 'o':
13390 case 'x':
13391 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013392 isnumok = 0;
13393 if (PyNumber_Check(v)) {
13394 PyObject *iobj=NULL;
13395
13396 if (PyLong_Check(v)) {
13397 iobj = v;
13398 Py_INCREF(iobj);
13399 }
13400 else {
13401 iobj = PyNumber_Long(v);
13402 }
13403 if (iobj!=NULL) {
13404 if (PyLong_Check(iobj)) {
13405 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013406 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013407 Py_DECREF(iobj);
13408 if (!temp)
13409 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013410 if (PyUnicode_READY(temp) == -1) {
13411 Py_CLEAR(temp);
13412 goto onError;
13413 }
13414 pbuf = PyUnicode_DATA(temp);
13415 kind = PyUnicode_KIND(temp);
13416 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013417 sign = 1;
13418 }
13419 else {
13420 Py_DECREF(iobj);
13421 }
13422 }
13423 }
13424 if (!isnumok) {
13425 PyErr_Format(PyExc_TypeError,
13426 "%%%c format: a number is required, "
13427 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13428 goto onError;
13429 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013430 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013431 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013432 fillobj = zero;
13433 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013434 break;
13435
13436 case 'e':
13437 case 'E':
13438 case 'f':
13439 case 'F':
13440 case 'g':
13441 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013442 temp = formatfloat(v, flags, prec, c);
13443 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013444 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013445 if (PyUnicode_READY(temp) == -1) {
13446 Py_CLEAR(temp);
13447 goto onError;
13448 }
13449 pbuf = PyUnicode_DATA(temp);
13450 kind = PyUnicode_KIND(temp);
13451 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013452 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013453 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013454 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013455 fillobj = zero;
13456 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 break;
13458
13459 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013460 {
13461 Py_UCS4 ch = formatchar(v);
13462 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013463 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013464 temp = _PyUnicode_FromUCS4(&ch, 1);
13465 if (temp == NULL)
13466 goto onError;
13467 pbuf = PyUnicode_DATA(temp);
13468 kind = PyUnicode_KIND(temp);
13469 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013471 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013472
13473 default:
13474 PyErr_Format(PyExc_ValueError,
13475 "unsupported format character '%c' (0x%x) "
13476 "at index %zd",
13477 (31<=c && c<=126) ? (char)c : '?',
13478 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013479 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013480 goto onError;
13481 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013482 /* pbuf is initialized here. */
13483 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013484 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013485 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13486 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013487 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013488 pindex++;
13489 }
13490 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13491 signobj = plus;
13492 len--;
13493 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013494 }
13495 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013496 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013497 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013498 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013499 else
13500 sign = 0;
13501 }
13502 if (width < len)
13503 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013504 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013505 if (fill != ' ') {
13506 assert(signobj != NULL);
13507 if (_PyAccu_Accumulate(&acc, signobj))
13508 goto onError;
13509 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013510 if (width > len)
13511 width--;
13512 }
13513 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013514 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013515 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013516 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013517 second = get_latin1_char(
13518 PyUnicode_READ(kind, pbuf, pindex + 1));
13519 pindex += 2;
13520 if (second == NULL ||
13521 _PyAccu_Accumulate(&acc, zero) ||
13522 _PyAccu_Accumulate(&acc, second))
13523 goto onError;
13524 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013526 width -= 2;
13527 if (width < 0)
13528 width = 0;
13529 len -= 2;
13530 }
13531 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013532 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013533 if (repeat_accumulate(&acc, fillobj, width - len))
13534 goto onError;
13535 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013536 }
13537 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013538 if (sign) {
13539 assert(signobj != NULL);
13540 if (_PyAccu_Accumulate(&acc, signobj))
13541 goto onError;
13542 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013543 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013544 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13545 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013546 second = get_latin1_char(
13547 PyUnicode_READ(kind, pbuf, pindex + 1));
13548 pindex += 2;
13549 if (second == NULL ||
13550 _PyAccu_Accumulate(&acc, zero) ||
13551 _PyAccu_Accumulate(&acc, second))
13552 goto onError;
13553 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013554 }
13555 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013556 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013557 if (temp != NULL) {
13558 assert(pbuf == PyUnicode_DATA(temp));
13559 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013560 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013561 else {
13562 const char *p = (const char *) pbuf;
13563 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013564 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013565 v = PyUnicode_FromKindAndData(kind, p, len);
13566 }
13567 if (v == NULL)
13568 goto onError;
13569 r = _PyAccu_Accumulate(&acc, v);
13570 Py_DECREF(v);
13571 if (r)
13572 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013573 if (width > len && repeat_accumulate(&acc, blank, width - len))
13574 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013575 if (dict && (argidx < arglen) && c != '%') {
13576 PyErr_SetString(PyExc_TypeError,
13577 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013578 goto onError;
13579 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013580 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013581 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013582 } /* until end */
13583 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013584 PyErr_SetString(PyExc_TypeError,
13585 "not all arguments converted during string formatting");
13586 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013587 }
13588
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013589 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013590 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013591 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013592 }
13593 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013594 Py_XDECREF(temp);
13595 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013596 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013597
Benjamin Peterson29060642009-01-31 22:14:21 +000013598 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013599 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013600 Py_XDECREF(temp);
13601 Py_XDECREF(second);
13602 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013603 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013605 }
13606 return NULL;
13607}
13608
Jeremy Hylton938ace62002-07-17 16:30:39 +000013609static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013610unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13611
Tim Peters6d6c1a32001-08-02 04:15:00 +000013612static PyObject *
13613unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13614{
Benjamin Peterson29060642009-01-31 22:14:21 +000013615 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013616 static char *kwlist[] = {"object", "encoding", "errors", 0};
13617 char *encoding = NULL;
13618 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013619
Benjamin Peterson14339b62009-01-31 16:36:08 +000013620 if (type != &PyUnicode_Type)
13621 return unicode_subtype_new(type, args, kwds);
13622 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013623 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013624 return NULL;
13625 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013626 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013627 if (encoding == NULL && errors == NULL)
13628 return PyObject_Str(x);
13629 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013631}
13632
Guido van Rossume023fe02001-08-30 03:12:59 +000013633static PyObject *
13634unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13635{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013636 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013637 Py_ssize_t length, char_size;
13638 int share_wstr, share_utf8;
13639 unsigned int kind;
13640 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013641
Benjamin Peterson14339b62009-01-31 16:36:08 +000013642 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013643
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013644 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013645 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013646 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013647 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013648 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013649 return NULL;
13650
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013651 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013652 if (self == NULL) {
13653 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013654 return NULL;
13655 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013656 kind = PyUnicode_KIND(unicode);
13657 length = PyUnicode_GET_LENGTH(unicode);
13658
13659 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013660#ifdef Py_DEBUG
13661 _PyUnicode_HASH(self) = -1;
13662#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013663 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013664#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013665 _PyUnicode_STATE(self).interned = 0;
13666 _PyUnicode_STATE(self).kind = kind;
13667 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013668 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013669 _PyUnicode_STATE(self).ready = 1;
13670 _PyUnicode_WSTR(self) = NULL;
13671 _PyUnicode_UTF8_LENGTH(self) = 0;
13672 _PyUnicode_UTF8(self) = NULL;
13673 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013674 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013675
13676 share_utf8 = 0;
13677 share_wstr = 0;
13678 if (kind == PyUnicode_1BYTE_KIND) {
13679 char_size = 1;
13680 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13681 share_utf8 = 1;
13682 }
13683 else if (kind == PyUnicode_2BYTE_KIND) {
13684 char_size = 2;
13685 if (sizeof(wchar_t) == 2)
13686 share_wstr = 1;
13687 }
13688 else {
13689 assert(kind == PyUnicode_4BYTE_KIND);
13690 char_size = 4;
13691 if (sizeof(wchar_t) == 4)
13692 share_wstr = 1;
13693 }
13694
13695 /* Ensure we won't overflow the length. */
13696 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13697 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013698 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013699 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013700 data = PyObject_MALLOC((length + 1) * char_size);
13701 if (data == NULL) {
13702 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013703 goto onError;
13704 }
13705
Victor Stinnerc3c74152011-10-02 20:39:55 +020013706 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013707 if (share_utf8) {
13708 _PyUnicode_UTF8_LENGTH(self) = length;
13709 _PyUnicode_UTF8(self) = data;
13710 }
13711 if (share_wstr) {
13712 _PyUnicode_WSTR_LENGTH(self) = length;
13713 _PyUnicode_WSTR(self) = (wchar_t *)data;
13714 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013715
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013716 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013717 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013718 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013719#ifdef Py_DEBUG
13720 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13721#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013722 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013723 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013724
13725onError:
13726 Py_DECREF(unicode);
13727 Py_DECREF(self);
13728 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013729}
13730
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013731PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013732 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013733\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013734Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013735encoding defaults to the current default string encoding.\n\
13736errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013737
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013738static PyObject *unicode_iter(PyObject *seq);
13739
Guido van Rossumd57fd912000-03-10 22:53:23 +000013740PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013741 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013742 "str", /* tp_name */
13743 sizeof(PyUnicodeObject), /* tp_size */
13744 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013745 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013746 (destructor)unicode_dealloc, /* tp_dealloc */
13747 0, /* tp_print */
13748 0, /* tp_getattr */
13749 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013750 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013751 unicode_repr, /* tp_repr */
13752 &unicode_as_number, /* tp_as_number */
13753 &unicode_as_sequence, /* tp_as_sequence */
13754 &unicode_as_mapping, /* tp_as_mapping */
13755 (hashfunc) unicode_hash, /* tp_hash*/
13756 0, /* tp_call*/
13757 (reprfunc) unicode_str, /* tp_str */
13758 PyObject_GenericGetAttr, /* tp_getattro */
13759 0, /* tp_setattro */
13760 0, /* tp_as_buffer */
13761 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013762 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013763 unicode_doc, /* tp_doc */
13764 0, /* tp_traverse */
13765 0, /* tp_clear */
13766 PyUnicode_RichCompare, /* tp_richcompare */
13767 0, /* tp_weaklistoffset */
13768 unicode_iter, /* tp_iter */
13769 0, /* tp_iternext */
13770 unicode_methods, /* tp_methods */
13771 0, /* tp_members */
13772 0, /* tp_getset */
13773 &PyBaseObject_Type, /* tp_base */
13774 0, /* tp_dict */
13775 0, /* tp_descr_get */
13776 0, /* tp_descr_set */
13777 0, /* tp_dictoffset */
13778 0, /* tp_init */
13779 0, /* tp_alloc */
13780 unicode_new, /* tp_new */
13781 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013782};
13783
13784/* Initialize the Unicode implementation */
13785
Victor Stinner3a50e702011-10-18 21:21:00 +020013786int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013787{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013788 int i;
13789
Thomas Wouters477c8d52006-05-27 19:21:47 +000013790 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013791 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013792 0x000A, /* LINE FEED */
13793 0x000D, /* CARRIAGE RETURN */
13794 0x001C, /* FILE SEPARATOR */
13795 0x001D, /* GROUP SEPARATOR */
13796 0x001E, /* RECORD SEPARATOR */
13797 0x0085, /* NEXT LINE */
13798 0x2028, /* LINE SEPARATOR */
13799 0x2029, /* PARAGRAPH SEPARATOR */
13800 };
13801
Fred Drakee4315f52000-05-09 19:53:39 +000013802 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013803 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013804 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013805 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013806 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013807
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013808 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013809 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013810 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013811 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013812
13813 /* initialize the linebreak bloom filter */
13814 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013815 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013816 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013817
13818 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013819
13820#ifdef HAVE_MBCS
13821 winver.dwOSVersionInfoSize = sizeof(winver);
13822 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13823 PyErr_SetFromWindowsErr(0);
13824 return -1;
13825 }
13826#endif
13827 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013828}
13829
13830/* Finalize the Unicode implementation */
13831
Christian Heimesa156e092008-02-16 07:38:31 +000013832int
13833PyUnicode_ClearFreeList(void)
13834{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013835 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013836}
13837
Guido van Rossumd57fd912000-03-10 22:53:23 +000013838void
Thomas Wouters78890102000-07-22 19:25:51 +000013839_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013840{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013841 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013842
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013843 Py_XDECREF(unicode_empty);
13844 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013845
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013846 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013847 if (unicode_latin1[i]) {
13848 Py_DECREF(unicode_latin1[i]);
13849 unicode_latin1[i] = NULL;
13850 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013851 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013852 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013853 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013855
Walter Dörwald16807132007-05-25 13:52:07 +000013856void
13857PyUnicode_InternInPlace(PyObject **p)
13858{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013859 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013860 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013861#ifdef Py_DEBUG
13862 assert(s != NULL);
13863 assert(_PyUnicode_CHECK(s));
13864#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013865 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013866 return;
13867#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013868 /* If it's a subclass, we don't really know what putting
13869 it in the interned dict might do. */
13870 if (!PyUnicode_CheckExact(s))
13871 return;
13872 if (PyUnicode_CHECK_INTERNED(s))
13873 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013874 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013875 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013876 return;
13877 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013878 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013879 if (interned == NULL) {
13880 interned = PyDict_New();
13881 if (interned == NULL) {
13882 PyErr_Clear(); /* Don't leave an exception */
13883 return;
13884 }
13885 }
13886 /* It might be that the GetItem call fails even
13887 though the key is present in the dictionary,
13888 namely when this happens during a stack overflow. */
13889 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013890 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013891 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013892
Benjamin Peterson29060642009-01-31 22:14:21 +000013893 if (t) {
13894 Py_INCREF(t);
13895 Py_DECREF(*p);
13896 *p = t;
13897 return;
13898 }
Walter Dörwald16807132007-05-25 13:52:07 +000013899
Benjamin Peterson14339b62009-01-31 16:36:08 +000013900 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013901 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013902 PyErr_Clear();
13903 PyThreadState_GET()->recursion_critical = 0;
13904 return;
13905 }
13906 PyThreadState_GET()->recursion_critical = 0;
13907 /* The two references in interned are not counted by refcnt.
13908 The deallocator will take care of this */
13909 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013910 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013911}
13912
13913void
13914PyUnicode_InternImmortal(PyObject **p)
13915{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013916 PyUnicode_InternInPlace(p);
13917 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013918 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013919 Py_INCREF(*p);
13920 }
Walter Dörwald16807132007-05-25 13:52:07 +000013921}
13922
13923PyObject *
13924PyUnicode_InternFromString(const char *cp)
13925{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013926 PyObject *s = PyUnicode_FromString(cp);
13927 if (s == NULL)
13928 return NULL;
13929 PyUnicode_InternInPlace(&s);
13930 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013931}
13932
Alexander Belopolsky40018472011-02-26 01:02:56 +000013933void
13934_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013935{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013936 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013937 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013938 Py_ssize_t i, n;
13939 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013940
Benjamin Peterson14339b62009-01-31 16:36:08 +000013941 if (interned == NULL || !PyDict_Check(interned))
13942 return;
13943 keys = PyDict_Keys(interned);
13944 if (keys == NULL || !PyList_Check(keys)) {
13945 PyErr_Clear();
13946 return;
13947 }
Walter Dörwald16807132007-05-25 13:52:07 +000013948
Benjamin Peterson14339b62009-01-31 16:36:08 +000013949 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13950 detector, interned unicode strings are not forcibly deallocated;
13951 rather, we give them their stolen references back, and then clear
13952 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013953
Benjamin Peterson14339b62009-01-31 16:36:08 +000013954 n = PyList_GET_SIZE(keys);
13955 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013956 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013957 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013958 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013959 if (PyUnicode_READY(s) == -1) {
13960 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013961 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013962 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013963 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 case SSTATE_NOT_INTERNED:
13965 /* XXX Shouldn't happen */
13966 break;
13967 case SSTATE_INTERNED_IMMORTAL:
13968 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013969 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013970 break;
13971 case SSTATE_INTERNED_MORTAL:
13972 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013973 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013974 break;
13975 default:
13976 Py_FatalError("Inconsistent interned string state.");
13977 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013978 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013979 }
13980 fprintf(stderr, "total size of all interned strings: "
13981 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
13982 "mortal/immortal\n", mortal_size, immortal_size);
13983 Py_DECREF(keys);
13984 PyDict_Clear(interned);
13985 Py_DECREF(interned);
13986 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000013987}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013988
13989
13990/********************* Unicode Iterator **************************/
13991
13992typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013993 PyObject_HEAD
13994 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013995 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013996} unicodeiterobject;
13997
13998static void
13999unicodeiter_dealloc(unicodeiterobject *it)
14000{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014001 _PyObject_GC_UNTRACK(it);
14002 Py_XDECREF(it->it_seq);
14003 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014004}
14005
14006static int
14007unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14008{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014009 Py_VISIT(it->it_seq);
14010 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014011}
14012
14013static PyObject *
14014unicodeiter_next(unicodeiterobject *it)
14015{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014016 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014017
Benjamin Peterson14339b62009-01-31 16:36:08 +000014018 assert(it != NULL);
14019 seq = it->it_seq;
14020 if (seq == NULL)
14021 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014022 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014023
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014024 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14025 int kind = PyUnicode_KIND(seq);
14026 void *data = PyUnicode_DATA(seq);
14027 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14028 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014029 if (item != NULL)
14030 ++it->it_index;
14031 return item;
14032 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014033
Benjamin Peterson14339b62009-01-31 16:36:08 +000014034 Py_DECREF(seq);
14035 it->it_seq = NULL;
14036 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014037}
14038
14039static PyObject *
14040unicodeiter_len(unicodeiterobject *it)
14041{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014042 Py_ssize_t len = 0;
14043 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014044 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014045 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014046}
14047
14048PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14049
14050static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014051 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014052 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014053 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014054};
14055
14056PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014057 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14058 "str_iterator", /* tp_name */
14059 sizeof(unicodeiterobject), /* tp_basicsize */
14060 0, /* tp_itemsize */
14061 /* methods */
14062 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14063 0, /* tp_print */
14064 0, /* tp_getattr */
14065 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014066 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014067 0, /* tp_repr */
14068 0, /* tp_as_number */
14069 0, /* tp_as_sequence */
14070 0, /* tp_as_mapping */
14071 0, /* tp_hash */
14072 0, /* tp_call */
14073 0, /* tp_str */
14074 PyObject_GenericGetAttr, /* tp_getattro */
14075 0, /* tp_setattro */
14076 0, /* tp_as_buffer */
14077 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14078 0, /* tp_doc */
14079 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14080 0, /* tp_clear */
14081 0, /* tp_richcompare */
14082 0, /* tp_weaklistoffset */
14083 PyObject_SelfIter, /* tp_iter */
14084 (iternextfunc)unicodeiter_next, /* tp_iternext */
14085 unicodeiter_methods, /* tp_methods */
14086 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014087};
14088
14089static PyObject *
14090unicode_iter(PyObject *seq)
14091{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014092 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014093
Benjamin Peterson14339b62009-01-31 16:36:08 +000014094 if (!PyUnicode_Check(seq)) {
14095 PyErr_BadInternalCall();
14096 return NULL;
14097 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014098 if (PyUnicode_READY(seq) == -1)
14099 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014100 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14101 if (it == NULL)
14102 return NULL;
14103 it->it_index = 0;
14104 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014105 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014106 _PyObject_GC_TRACK(it);
14107 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014108}
14109
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014110
14111size_t
14112Py_UNICODE_strlen(const Py_UNICODE *u)
14113{
14114 int res = 0;
14115 while(*u++)
14116 res++;
14117 return res;
14118}
14119
14120Py_UNICODE*
14121Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14122{
14123 Py_UNICODE *u = s1;
14124 while ((*u++ = *s2++));
14125 return s1;
14126}
14127
14128Py_UNICODE*
14129Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14130{
14131 Py_UNICODE *u = s1;
14132 while ((*u++ = *s2++))
14133 if (n-- == 0)
14134 break;
14135 return s1;
14136}
14137
14138Py_UNICODE*
14139Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14140{
14141 Py_UNICODE *u1 = s1;
14142 u1 += Py_UNICODE_strlen(u1);
14143 Py_UNICODE_strcpy(u1, s2);
14144 return s1;
14145}
14146
14147int
14148Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14149{
14150 while (*s1 && *s2 && *s1 == *s2)
14151 s1++, s2++;
14152 if (*s1 && *s2)
14153 return (*s1 < *s2) ? -1 : +1;
14154 if (*s1)
14155 return 1;
14156 if (*s2)
14157 return -1;
14158 return 0;
14159}
14160
14161int
14162Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14163{
14164 register Py_UNICODE u1, u2;
14165 for (; n != 0; n--) {
14166 u1 = *s1;
14167 u2 = *s2;
14168 if (u1 != u2)
14169 return (u1 < u2) ? -1 : +1;
14170 if (u1 == '\0')
14171 return 0;
14172 s1++;
14173 s2++;
14174 }
14175 return 0;
14176}
14177
14178Py_UNICODE*
14179Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14180{
14181 const Py_UNICODE *p;
14182 for (p = s; *p; p++)
14183 if (*p == c)
14184 return (Py_UNICODE*)p;
14185 return NULL;
14186}
14187
14188Py_UNICODE*
14189Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14190{
14191 const Py_UNICODE *p;
14192 p = s + Py_UNICODE_strlen(s);
14193 while (p != s) {
14194 p--;
14195 if (*p == c)
14196 return (Py_UNICODE*)p;
14197 }
14198 return NULL;
14199}
Victor Stinner331ea922010-08-10 16:37:20 +000014200
Victor Stinner71133ff2010-09-01 23:43:53 +000014201Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014202PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014203{
Victor Stinner577db2c2011-10-11 22:12:48 +020014204 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014205 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014206
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014207 if (!PyUnicode_Check(unicode)) {
14208 PyErr_BadArgument();
14209 return NULL;
14210 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014211 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014212 if (u == NULL)
14213 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014214 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014215 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014216 PyErr_NoMemory();
14217 return NULL;
14218 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014219 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014220 size *= sizeof(Py_UNICODE);
14221 copy = PyMem_Malloc(size);
14222 if (copy == NULL) {
14223 PyErr_NoMemory();
14224 return NULL;
14225 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014226 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014227 return copy;
14228}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014229
Georg Brandl66c221e2010-10-14 07:04:07 +000014230/* A _string module, to export formatter_parser and formatter_field_name_split
14231 to the string.Formatter class implemented in Python. */
14232
14233static PyMethodDef _string_methods[] = {
14234 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14235 METH_O, PyDoc_STR("split the argument as a field name")},
14236 {"formatter_parser", (PyCFunction) formatter_parser,
14237 METH_O, PyDoc_STR("parse the argument as a format string")},
14238 {NULL, NULL}
14239};
14240
14241static struct PyModuleDef _string_module = {
14242 PyModuleDef_HEAD_INIT,
14243 "_string",
14244 PyDoc_STR("string helper module"),
14245 0,
14246 _string_methods,
14247 NULL,
14248 NULL,
14249 NULL,
14250 NULL
14251};
14252
14253PyMODINIT_FUNC
14254PyInit__string(void)
14255{
14256 return PyModule_Create(&_string_module);
14257}
14258
14259
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014260#ifdef __cplusplus
14261}
14262#endif