blob: 70c75c98edff1d883e5fbb07a4df877678174987 [file] [log] [blame]
Tim Petersced69f82003-09-16 20:30:58 +00001/*
Guido van Rossumd57fd912000-03-10 22:53:23 +00002
3Unicode implementation based on original code by Fredrik Lundh,
Benjamin Peterson31616ea2011-10-01 00:11:09 -04004modified by Marc-Andre Lemburg <mal@lemburg.com>.
Guido van Rossumd57fd912000-03-10 22:53:23 +00005
Thomas Wouters477c8d52006-05-27 19:21:47 +00006Major speed upgrades to the method implementations at the Reykjavik
7NeedForSpeed sprint, by Fredrik Lundh and Andrew Dalke.
8
Guido van Rossum16b1ad92000-08-03 16:24:25 +00009Copyright (c) Corporation for National Research Initiatives.
Guido van Rossumd57fd912000-03-10 22:53:23 +000010
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000011--------------------------------------------------------------------
12The original string type implementation is:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013
Benjamin Peterson29060642009-01-31 22:14:21 +000014 Copyright (c) 1999 by Secret Labs AB
15 Copyright (c) 1999 by Fredrik Lundh
Guido van Rossumd57fd912000-03-10 22:53:23 +000016
Fredrik Lundh0fdb90c2001-01-19 09:45:02 +000017By obtaining, using, and/or copying this software and/or its
18associated documentation, you agree that you have read, understood,
19and will comply with the following terms and conditions:
20
21Permission to use, copy, modify, and distribute this software and its
22associated documentation for any purpose and without fee is hereby
23granted, provided that the above copyright notice appears in all
24copies, and that both that copyright notice and this permission notice
25appear in supporting documentation, and that the name of Secret Labs
26AB or the author not be used in advertising or publicity pertaining to
27distribution of the software without specific, written prior
28permission.
29
30SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO
31THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
32FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR
33ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
34WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
35ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
36OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
37--------------------------------------------------------------------
38
39*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000041#define PY_SSIZE_T_CLEAN
Guido van Rossumd57fd912000-03-10 22:53:23 +000042#include "Python.h"
Marc-André Lemburgd49e5b42000-06-30 14:58:20 +000043#include "ucnhash.h"
Guido van Rossumd57fd912000-03-10 22:53:23 +000044
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000045#ifdef MS_WINDOWS
Guido van Rossumb7a40ba2000-03-28 02:01:52 +000046#include <windows.h>
47#endif
Guido van Rossumfd4b9572000-04-10 13:51:10 +000048
Victor Stinnerce5faf62011-10-05 00:42:43 +020049#ifdef Py_DEBUG
50# define DONT_MAKE_RESULT_READY
51#endif
52
Guido van Rossumd57fd912000-03-10 22:53:23 +000053/* Endianness switches; defaults to little endian */
54
55#ifdef WORDS_BIGENDIAN
56# define BYTEORDER_IS_BIG_ENDIAN
57#else
58# define BYTEORDER_IS_LITTLE_ENDIAN
59#endif
60
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000061/* --- Globals ------------------------------------------------------------
62
63 The globals are initialized by the _PyUnicode_Init() API and should
64 not be used before calling that API.
65
66*/
Guido van Rossumd57fd912000-03-10 22:53:23 +000067
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000068
69#ifdef __cplusplus
70extern "C" {
71#endif
72
Victor Stinner910337b2011-10-03 03:20:16 +020073#ifdef Py_DEBUG
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020074# define _PyUnicode_CHECK(op) _PyUnicode_CheckConsistency(op, 0)
Victor Stinner910337b2011-10-03 03:20:16 +020075#else
76# define _PyUnicode_CHECK(op) PyUnicode_Check(op)
77#endif
Victor Stinnerfb5f5f22011-09-28 21:39:49 +020078
Victor Stinnere90fe6a2011-10-01 16:48:13 +020079#define _PyUnicode_UTF8(op) \
80 (((PyCompactUnicodeObject*)(op))->utf8)
81#define PyUnicode_UTF8(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020082 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020083 assert(PyUnicode_IS_READY(op)), \
84 PyUnicode_IS_COMPACT_ASCII(op) ? \
85 ((char*)((PyASCIIObject*)(op) + 1)) : \
86 _PyUnicode_UTF8(op))
Victor Stinnerbc8b81b2011-09-29 19:31:34 +020087#define _PyUnicode_UTF8_LENGTH(op) \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020088 (((PyCompactUnicodeObject*)(op))->utf8_length)
89#define PyUnicode_UTF8_LENGTH(op) \
Victor Stinner910337b2011-10-03 03:20:16 +020090 (assert(_PyUnicode_CHECK(op)), \
Victor Stinnere90fe6a2011-10-01 16:48:13 +020091 assert(PyUnicode_IS_READY(op)), \
92 PyUnicode_IS_COMPACT_ASCII(op) ? \
93 ((PyASCIIObject*)(op))->length : \
94 _PyUnicode_UTF8_LENGTH(op))
Victor Stinnera5f91632011-10-04 01:07:11 +020095#define _PyUnicode_WSTR(op) \
96 (((PyASCIIObject*)(op))->wstr)
97#define _PyUnicode_WSTR_LENGTH(op) \
98 (((PyCompactUnicodeObject*)(op))->wstr_length)
99#define _PyUnicode_LENGTH(op) \
100 (((PyASCIIObject *)(op))->length)
101#define _PyUnicode_STATE(op) \
102 (((PyASCIIObject *)(op))->state)
103#define _PyUnicode_HASH(op) \
104 (((PyASCIIObject *)(op))->hash)
Victor Stinner910337b2011-10-03 03:20:16 +0200105#define _PyUnicode_KIND(op) \
106 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200107 ((PyASCIIObject *)(op))->state.kind)
Victor Stinner910337b2011-10-03 03:20:16 +0200108#define _PyUnicode_GET_LENGTH(op) \
109 (assert(_PyUnicode_CHECK(op)), \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200110 ((PyASCIIObject *)(op))->length)
Victor Stinnera5f91632011-10-04 01:07:11 +0200111#define _PyUnicode_DATA_ANY(op) \
112 (((PyUnicodeObject*)(op))->data.any)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200113
Victor Stinner910337b2011-10-03 03:20:16 +0200114#undef PyUnicode_READY
115#define PyUnicode_READY(op) \
116 (assert(_PyUnicode_CHECK(op)), \
117 (PyUnicode_IS_READY(op) ? \
Victor Stinnera5f91632011-10-04 01:07:11 +0200118 0 : \
Victor Stinner7931d9a2011-11-04 00:22:48 +0100119 _PyUnicode_Ready(op)))
Victor Stinner910337b2011-10-03 03:20:16 +0200120
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200121#define _PyUnicode_READY_REPLACE(p_obj) \
122 (assert(_PyUnicode_CHECK(*p_obj)), \
123 (PyUnicode_IS_READY(*p_obj) ? \
124 0 : _PyUnicode_ReadyReplace((PyObject **)(p_obj))))
125
Victor Stinnerc379ead2011-10-03 12:52:27 +0200126#define _PyUnicode_SHARE_UTF8(op) \
127 (assert(_PyUnicode_CHECK(op)), \
128 assert(!PyUnicode_IS_COMPACT_ASCII(op)), \
129 (_PyUnicode_UTF8(op) == PyUnicode_DATA(op)))
130#define _PyUnicode_SHARE_WSTR(op) \
131 (assert(_PyUnicode_CHECK(op)), \
132 (_PyUnicode_WSTR(unicode) == PyUnicode_DATA(op)))
133
Victor Stinner829c0ad2011-10-03 01:08:02 +0200134/* true if the Unicode object has an allocated UTF-8 memory block
135 (not shared with other data) */
Victor Stinner910337b2011-10-03 03:20:16 +0200136#define _PyUnicode_HAS_UTF8_MEMORY(op) \
137 (assert(_PyUnicode_CHECK(op)), \
138 (!PyUnicode_IS_COMPACT_ASCII(op) \
139 && _PyUnicode_UTF8(op) \
Victor Stinner829c0ad2011-10-03 01:08:02 +0200140 && _PyUnicode_UTF8(op) != PyUnicode_DATA(op)))
141
Victor Stinner03490912011-10-03 23:45:12 +0200142/* true if the Unicode object has an allocated wstr memory block
143 (not shared with other data) */
144#define _PyUnicode_HAS_WSTR_MEMORY(op) \
145 (assert(_PyUnicode_CHECK(op)), \
146 (_PyUnicode_WSTR(op) && \
147 (!PyUnicode_IS_READY(op) || \
148 _PyUnicode_WSTR(op) != PyUnicode_DATA(op))))
149
Victor Stinner910337b2011-10-03 03:20:16 +0200150/* Generic helper macro to convert characters of different types.
151 from_type and to_type have to be valid type names, begin and end
152 are pointers to the source characters which should be of type
153 "from_type *". to is a pointer of type "to_type *" and points to the
154 buffer where the result characters are written to. */
155#define _PyUnicode_CONVERT_BYTES(from_type, to_type, begin, end, to) \
156 do { \
Antoine Pitroue459a082011-10-11 20:58:41 +0200157 to_type *_to = (to_type *) to; \
158 const from_type *_iter = (begin); \
159 const from_type *_end = (end); \
160 Py_ssize_t n = (_end) - (_iter); \
161 const from_type *_unrolled_end = \
162 _iter + (n & ~ (Py_ssize_t) 3); \
163 while (_iter < (_unrolled_end)) { \
164 _to[0] = (to_type) _iter[0]; \
165 _to[1] = (to_type) _iter[1]; \
166 _to[2] = (to_type) _iter[2]; \
167 _to[3] = (to_type) _iter[3]; \
168 _iter += 4; _to += 4; \
Victor Stinner910337b2011-10-03 03:20:16 +0200169 } \
Antoine Pitroue459a082011-10-11 20:58:41 +0200170 while (_iter < (_end)) \
171 *_to++ = (to_type) *_iter++; \
Victor Stinner910337b2011-10-03 03:20:16 +0200172 } while (0)
Victor Stinner829c0ad2011-10-03 01:08:02 +0200173
Victor Stinnerb15d4d82011-09-28 23:59:20 +0200174/* The Unicode string has been modified: reset the hash */
175#define _PyUnicode_DIRTY(op) do { _PyUnicode_HASH(op) = -1; } while (0)
176
Walter Dörwald16807132007-05-25 13:52:07 +0000177/* This dictionary holds all interned unicode strings. Note that references
178 to strings in this dictionary are *not* counted in the string's ob_refcnt.
179 When the interned string reaches a refcnt of 0 the string deallocation
180 function will delete the reference from this dictionary.
181
182 Another way to look at this is that to say that the actual reference
Guido van Rossum98297ee2007-11-06 21:34:58 +0000183 count of a string is: s->ob_refcnt + (s->state ? 2 : 0)
Walter Dörwald16807132007-05-25 13:52:07 +0000184*/
185static PyObject *interned;
186
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000187/* The empty Unicode object is shared to improve performance. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200188static PyObject *unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000189
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200190/* List of static strings. */
191static _Py_Identifier *static_strings;
192
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000193/* Single character Unicode strings in the Latin-1 range are being
194 shared as well. */
Victor Stinnera464fc12011-10-02 20:39:30 +0200195static PyObject *unicode_latin1[256];
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +0000196
Christian Heimes190d79e2008-01-30 11:58:22 +0000197/* Fast detection of the most frequent whitespace characters */
198const unsigned char _Py_ascii_whitespace[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000199 0, 0, 0, 0, 0, 0, 0, 0,
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000200/* case 0x0009: * CHARACTER TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000201/* case 0x000A: * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000202/* case 0x000B: * LINE TABULATION */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000203/* case 0x000C: * FORM FEED */
204/* case 0x000D: * CARRIAGE RETURN */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000205 0, 1, 1, 1, 1, 1, 0, 0,
206 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000207/* case 0x001C: * FILE SEPARATOR */
208/* case 0x001D: * GROUP SEPARATOR */
209/* case 0x001E: * RECORD SEPARATOR */
210/* case 0x001F: * UNIT SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000211 0, 0, 0, 0, 1, 1, 1, 1,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000212/* case 0x0020: * SPACE */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000213 1, 0, 0, 0, 0, 0, 0, 0,
214 0, 0, 0, 0, 0, 0, 0, 0,
215 0, 0, 0, 0, 0, 0, 0, 0,
216 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000217
Benjamin Peterson14339b62009-01-31 16:36:08 +0000218 0, 0, 0, 0, 0, 0, 0, 0,
219 0, 0, 0, 0, 0, 0, 0, 0,
220 0, 0, 0, 0, 0, 0, 0, 0,
221 0, 0, 0, 0, 0, 0, 0, 0,
222 0, 0, 0, 0, 0, 0, 0, 0,
223 0, 0, 0, 0, 0, 0, 0, 0,
224 0, 0, 0, 0, 0, 0, 0, 0,
225 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000226};
227
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200228/* forward */
Victor Stinnerfe226c02011-10-03 03:52:20 +0200229static PyUnicodeObject *_PyUnicode_New(Py_ssize_t length);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +0200230static PyObject* get_latin1_char(unsigned char ch);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200231static void copy_characters(
232 PyObject *to, Py_ssize_t to_start,
233 PyObject *from, Py_ssize_t from_start,
234 Py_ssize_t how_many);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200235#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200236static int unicode_is_singleton(PyObject *unicode);
Victor Stinnerc729b8e2011-10-06 02:36:59 +0200237#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +0200238
Alexander Belopolsky40018472011-02-26 01:02:56 +0000239static PyObject *
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200240unicode_fromascii(const unsigned char *s, Py_ssize_t size);
241static PyObject *
242_PyUnicode_FromUCS1(const unsigned char *s, Py_ssize_t size);
243static PyObject *
244_PyUnicode_FromUCS2(const Py_UCS2 *s, Py_ssize_t size);
245static PyObject *
246_PyUnicode_FromUCS4(const Py_UCS4 *s, Py_ssize_t size);
247
248static PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +0000249unicode_encode_call_errorhandler(const char *errors,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000250 PyObject **errorHandler,const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +0100251 PyObject *unicode, PyObject **exceptionObject,
Martin v. Löwisdb12d452009-05-02 18:52:14 +0000252 Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
253
Alexander Belopolsky40018472011-02-26 01:02:56 +0000254static void
255raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +0300256 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +0100257 PyObject *unicode,
258 Py_ssize_t startpos, Py_ssize_t endpos,
259 const char *reason);
Victor Stinner31be90b2010-04-22 19:38:16 +0000260
Christian Heimes190d79e2008-01-30 11:58:22 +0000261/* Same for linebreaks */
262static unsigned char ascii_linebreak[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +0000263 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000264/* 0x000A, * LINE FEED */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000265/* 0x000B, * LINE TABULATION */
266/* 0x000C, * FORM FEED */
Christian Heimes1a8501c2008-10-02 19:56:01 +0000267/* 0x000D, * CARRIAGE RETURN */
Florent Xicluna806d8cf2010-03-30 19:34:18 +0000268 0, 0, 1, 1, 1, 1, 0, 0,
Benjamin Peterson14339b62009-01-31 16:36:08 +0000269 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes1a8501c2008-10-02 19:56:01 +0000270/* 0x001C, * FILE SEPARATOR */
271/* 0x001D, * GROUP SEPARATOR */
272/* 0x001E, * RECORD SEPARATOR */
Benjamin Peterson14339b62009-01-31 16:36:08 +0000273 0, 0, 0, 0, 1, 1, 1, 0,
274 0, 0, 0, 0, 0, 0, 0, 0,
275 0, 0, 0, 0, 0, 0, 0, 0,
276 0, 0, 0, 0, 0, 0, 0, 0,
277 0, 0, 0, 0, 0, 0, 0, 0,
Christian Heimes190d79e2008-01-30 11:58:22 +0000278
Benjamin Peterson14339b62009-01-31 16:36:08 +0000279 0, 0, 0, 0, 0, 0, 0, 0,
280 0, 0, 0, 0, 0, 0, 0, 0,
281 0, 0, 0, 0, 0, 0, 0, 0,
282 0, 0, 0, 0, 0, 0, 0, 0,
283 0, 0, 0, 0, 0, 0, 0, 0,
284 0, 0, 0, 0, 0, 0, 0, 0,
285 0, 0, 0, 0, 0, 0, 0, 0,
286 0, 0, 0, 0, 0, 0, 0, 0
Christian Heimes190d79e2008-01-30 11:58:22 +0000287};
288
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300289/* The max unicode value is always 0x10FFFF while using the PEP-393 API.
290 This function is kept for backward compatibility with the old API. */
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000291Py_UNICODE
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +0000292PyUnicode_GetMax(void)
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000293{
Fredrik Lundh8f455852001-06-27 18:59:43 +0000294#ifdef Py_UNICODE_WIDE
Benjamin Peterson14339b62009-01-31 16:36:08 +0000295 return 0x10FFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000296#else
Benjamin Peterson14339b62009-01-31 16:36:08 +0000297 /* This is actually an illegal character, so it should
298 not be passed to unichr. */
299 return 0xFFFF;
Martin v. Löwisce9b5a52001-06-27 06:28:56 +0000300#endif
301}
302
Victor Stinner910337b2011-10-03 03:20:16 +0200303#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200304int
Victor Stinner7931d9a2011-11-04 00:22:48 +0100305_PyUnicode_CheckConsistency(PyObject *op, int check_content)
Victor Stinner910337b2011-10-03 03:20:16 +0200306{
307 PyASCIIObject *ascii;
308 unsigned int kind;
309
310 assert(PyUnicode_Check(op));
311
312 ascii = (PyASCIIObject *)op;
313 kind = ascii->state.kind;
314
Victor Stinnera3b334d2011-10-03 13:53:37 +0200315 if (ascii->state.ascii == 1 && ascii->state.compact == 1) {
Victor Stinner910337b2011-10-03 03:20:16 +0200316 assert(kind == PyUnicode_1BYTE_KIND);
Victor Stinner910337b2011-10-03 03:20:16 +0200317 assert(ascii->state.ready == 1);
318 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200319 else {
Victor Stinner85041a52011-10-03 14:42:39 +0200320 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
Victor Stinner7f11ad42011-10-04 00:00:20 +0200321 void *data;
Victor Stinner910337b2011-10-03 03:20:16 +0200322
Victor Stinnera41463c2011-10-04 01:05:08 +0200323 if (ascii->state.compact == 1) {
324 data = compact + 1;
Victor Stinner910337b2011-10-03 03:20:16 +0200325 assert(kind == PyUnicode_1BYTE_KIND
326 || kind == PyUnicode_2BYTE_KIND
327 || kind == PyUnicode_4BYTE_KIND);
Victor Stinnera41463c2011-10-04 01:05:08 +0200328 assert(ascii->state.ascii == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200329 assert(ascii->state.ready == 1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200330 assert (compact->utf8 != data);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100331 }
332 else {
Victor Stinnera41463c2011-10-04 01:05:08 +0200333 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
334
335 data = unicode->data.any;
336 if (kind == PyUnicode_WCHAR_KIND) {
Victor Stinnere30c0a12011-11-04 20:54:05 +0100337 assert(ascii->length == 0);
338 assert(ascii->hash == -1);
Victor Stinnera41463c2011-10-04 01:05:08 +0200339 assert(ascii->state.compact == 0);
340 assert(ascii->state.ascii == 0);
341 assert(ascii->state.ready == 0);
Victor Stinnere30c0a12011-11-04 20:54:05 +0100342 assert(ascii->state.interned == SSTATE_NOT_INTERNED);
Victor Stinnera41463c2011-10-04 01:05:08 +0200343 assert(ascii->wstr != NULL);
344 assert(data == NULL);
345 assert(compact->utf8 == NULL);
Victor Stinnera41463c2011-10-04 01:05:08 +0200346 }
347 else {
348 assert(kind == PyUnicode_1BYTE_KIND
349 || kind == PyUnicode_2BYTE_KIND
350 || kind == PyUnicode_4BYTE_KIND);
351 assert(ascii->state.compact == 0);
352 assert(ascii->state.ready == 1);
353 assert(data != NULL);
354 if (ascii->state.ascii) {
355 assert (compact->utf8 == data);
356 assert (compact->utf8_length == ascii->length);
357 }
358 else
359 assert (compact->utf8 != data);
360 }
361 }
362 if (kind != PyUnicode_WCHAR_KIND) {
Victor Stinner7f11ad42011-10-04 00:00:20 +0200363 if (
364#if SIZEOF_WCHAR_T == 2
365 kind == PyUnicode_2BYTE_KIND
366#else
367 kind == PyUnicode_4BYTE_KIND
368#endif
369 )
Victor Stinnera41463c2011-10-04 01:05:08 +0200370 {
371 assert(ascii->wstr == data);
372 assert(compact->wstr_length == ascii->length);
373 } else
374 assert(ascii->wstr != data);
Victor Stinner910337b2011-10-03 03:20:16 +0200375 }
Victor Stinnera41463c2011-10-04 01:05:08 +0200376
377 if (compact->utf8 == NULL)
378 assert(compact->utf8_length == 0);
379 if (ascii->wstr == NULL)
380 assert(compact->wstr_length == 0);
Victor Stinner910337b2011-10-03 03:20:16 +0200381 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200382 /* check that the best kind is used */
383 if (check_content && kind != PyUnicode_WCHAR_KIND)
384 {
385 Py_ssize_t i;
386 Py_UCS4 maxchar = 0;
387 void *data = PyUnicode_DATA(ascii);
388 for (i=0; i < ascii->length; i++)
389 {
390 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
391 if (ch > maxchar)
392 maxchar = ch;
393 }
394 if (kind == PyUnicode_1BYTE_KIND) {
395 if (ascii->state.ascii == 0)
396 assert(maxchar >= 128);
397 else
398 assert(maxchar < 128);
399 }
400 else if (kind == PyUnicode_2BYTE_KIND)
401 assert(maxchar >= 0x100);
402 else
403 assert(maxchar >= 0x10000);
404 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100405 if (check_content && !unicode_is_singleton(op))
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200406 assert(ascii->hash == -1);
Benjamin Petersonccc51c12011-10-03 19:34:12 -0400407 return 1;
408}
Victor Stinner910337b2011-10-03 03:20:16 +0200409#endif
410
Victor Stinner3a50e702011-10-18 21:21:00 +0200411#ifdef HAVE_MBCS
412static OSVERSIONINFOEX winver;
413#endif
414
Thomas Wouters477c8d52006-05-27 19:21:47 +0000415/* --- Bloom Filters ----------------------------------------------------- */
416
417/* stuff to implement simple "bloom filters" for Unicode characters.
418 to keep things simple, we use a single bitmask, using the least 5
419 bits from each unicode characters as the bit index. */
420
421/* the linebreak mask is set up by Unicode_Init below */
422
Antoine Pitrouf068f942010-01-13 14:19:12 +0000423#if LONG_BIT >= 128
424#define BLOOM_WIDTH 128
425#elif LONG_BIT >= 64
426#define BLOOM_WIDTH 64
427#elif LONG_BIT >= 32
428#define BLOOM_WIDTH 32
429#else
430#error "LONG_BIT is smaller than 32"
431#endif
432
Thomas Wouters477c8d52006-05-27 19:21:47 +0000433#define BLOOM_MASK unsigned long
434
435static BLOOM_MASK bloom_linebreak;
436
Antoine Pitrouf068f942010-01-13 14:19:12 +0000437#define BLOOM_ADD(mask, ch) ((mask |= (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
438#define BLOOM(mask, ch) ((mask & (1UL << ((ch) & (BLOOM_WIDTH - 1)))))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000439
Benjamin Peterson29060642009-01-31 22:14:21 +0000440#define BLOOM_LINEBREAK(ch) \
441 ((ch) < 128U ? ascii_linebreak[(ch)] : \
442 (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000443
Alexander Belopolsky40018472011-02-26 01:02:56 +0000444Py_LOCAL_INLINE(BLOOM_MASK)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200445make_bloom_mask(int kind, void* ptr, Py_ssize_t len)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000446{
447 /* calculate simple bloom-style bitmask for a given unicode string */
448
Antoine Pitrouf068f942010-01-13 14:19:12 +0000449 BLOOM_MASK mask;
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 Py_ssize_t i;
451
452 mask = 0;
453 for (i = 0; i < len; i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200454 BLOOM_ADD(mask, PyUnicode_READ(kind, ptr, i));
Thomas Wouters477c8d52006-05-27 19:21:47 +0000455
456 return mask;
457}
458
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200459#define BLOOM_MEMBER(mask, chr, str) \
460 (BLOOM(mask, chr) \
461 && (PyUnicode_FindChar(str, chr, 0, PyUnicode_GET_LENGTH(str), 1) >= 0))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000462
Antoine Pitroudd4e2f02011-10-13 00:02:27 +0200463/* Compilation of templated routines */
464
465#include "stringlib/asciilib.h"
466#include "stringlib/fastsearch.h"
467#include "stringlib/partition.h"
468#include "stringlib/split.h"
469#include "stringlib/count.h"
470#include "stringlib/find.h"
471#include "stringlib/find_max_char.h"
472#include "stringlib/localeutil.h"
473#include "stringlib/undef.h"
474
475#include "stringlib/ucs1lib.h"
476#include "stringlib/fastsearch.h"
477#include "stringlib/partition.h"
478#include "stringlib/split.h"
479#include "stringlib/count.h"
480#include "stringlib/find.h"
481#include "stringlib/find_max_char.h"
482#include "stringlib/localeutil.h"
483#include "stringlib/undef.h"
484
485#include "stringlib/ucs2lib.h"
486#include "stringlib/fastsearch.h"
487#include "stringlib/partition.h"
488#include "stringlib/split.h"
489#include "stringlib/count.h"
490#include "stringlib/find.h"
491#include "stringlib/find_max_char.h"
492#include "stringlib/localeutil.h"
493#include "stringlib/undef.h"
494
495#include "stringlib/ucs4lib.h"
496#include "stringlib/fastsearch.h"
497#include "stringlib/partition.h"
498#include "stringlib/split.h"
499#include "stringlib/count.h"
500#include "stringlib/find.h"
501#include "stringlib/find_max_char.h"
502#include "stringlib/localeutil.h"
503#include "stringlib/undef.h"
504
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200505#include "stringlib/unicodedefs.h"
506#include "stringlib/fastsearch.h"
507#include "stringlib/count.h"
508#include "stringlib/find.h"
509
Guido van Rossumd57fd912000-03-10 22:53:23 +0000510/* --- Unicode Object ----------------------------------------------------- */
511
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200512static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +0200513fixup(PyObject *self, Py_UCS4 (*fixfct)(PyObject *s));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200514
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200515Py_LOCAL_INLINE(Py_ssize_t) findchar(void *s, int kind,
516 Py_ssize_t size, Py_UCS4 ch,
517 int direction)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200518{
Antoine Pitrouf0b934b2011-10-13 18:55:09 +0200519 int mode = (direction == 1) ? FAST_SEARCH : FAST_RSEARCH;
520
521 switch (kind) {
522 case PyUnicode_1BYTE_KIND:
523 {
524 Py_UCS1 ch1 = (Py_UCS1) ch;
525 if (ch1 == ch)
526 return ucs1lib_fastsearch((Py_UCS1 *) s, size, &ch1, 1, 0, mode);
527 else
528 return -1;
529 }
530 case PyUnicode_2BYTE_KIND:
531 {
532 Py_UCS2 ch2 = (Py_UCS2) ch;
533 if (ch2 == ch)
534 return ucs2lib_fastsearch((Py_UCS2 *) s, size, &ch2, 1, 0, mode);
535 else
536 return -1;
537 }
538 case PyUnicode_4BYTE_KIND:
539 return ucs4lib_fastsearch((Py_UCS4 *) s, size, &ch, 1, 0, mode);
540 default:
541 assert(0);
542 return -1;
Victor Stinner9e7a1bc2011-10-13 00:18:12 +0200543 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200544}
545
Victor Stinnerfe226c02011-10-03 03:52:20 +0200546static PyObject*
547resize_compact(PyObject *unicode, Py_ssize_t length)
548{
549 Py_ssize_t char_size;
550 Py_ssize_t struct_size;
551 Py_ssize_t new_size;
552 int share_wstr;
553
554 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200555 char_size = PyUnicode_KIND(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200556 if (PyUnicode_IS_COMPACT_ASCII(unicode))
557 struct_size = sizeof(PyASCIIObject);
558 else
559 struct_size = sizeof(PyCompactUnicodeObject);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200560 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200561
562 _Py_DEC_REFTOTAL;
563 _Py_ForgetReference(unicode);
564
565 if (length > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1)) {
566 PyErr_NoMemory();
567 return NULL;
568 }
569 new_size = (struct_size + (length + 1) * char_size);
570
571 unicode = (PyObject *)PyObject_REALLOC((char *)unicode, new_size);
572 if (unicode == NULL) {
573 PyObject_Del(unicode);
574 PyErr_NoMemory();
575 return NULL;
576 }
577 _Py_NewReference(unicode);
578 _PyUnicode_LENGTH(unicode) = length;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200579 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200580 _PyUnicode_WSTR(unicode) = PyUnicode_DATA(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200581 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
582 _PyUnicode_WSTR_LENGTH(unicode) = length;
583 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200584 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
585 length, 0);
586 return unicode;
587}
588
Alexander Belopolsky40018472011-02-26 01:02:56 +0000589static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200590resize_inplace(PyObject *unicode, Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000591{
Victor Stinner95663112011-10-04 01:03:50 +0200592 wchar_t *wstr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200593 assert(!PyUnicode_IS_COMPACT(unicode));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200594 assert(Py_REFCNT(unicode) == 1);
Tim Petersced69f82003-09-16 20:30:58 +0000595
Victor Stinner95663112011-10-04 01:03:50 +0200596 _PyUnicode_DIRTY(unicode);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200597
598 if (PyUnicode_IS_READY(unicode)) {
599 Py_ssize_t char_size;
600 Py_ssize_t new_size;
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200601 int share_wstr, share_utf8;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200602 void *data;
603
604 data = _PyUnicode_DATA_ANY(unicode);
605 assert(data != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +0200606 char_size = PyUnicode_KIND(unicode);
Victor Stinnerc379ead2011-10-03 12:52:27 +0200607 share_wstr = _PyUnicode_SHARE_WSTR(unicode);
608 share_utf8 = _PyUnicode_SHARE_UTF8(unicode);
Victor Stinner95663112011-10-04 01:03:50 +0200609 if (!share_utf8 && _PyUnicode_HAS_UTF8_MEMORY(unicode))
610 {
611 PyObject_DEL(_PyUnicode_UTF8(unicode));
612 _PyUnicode_UTF8(unicode) = NULL;
613 _PyUnicode_UTF8_LENGTH(unicode) = 0;
614 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200615
616 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
617 PyErr_NoMemory();
618 return -1;
619 }
620 new_size = (length + 1) * char_size;
621
622 data = (PyObject *)PyObject_REALLOC(data, new_size);
623 if (data == NULL) {
624 PyErr_NoMemory();
625 return -1;
626 }
627 _PyUnicode_DATA_ANY(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200628 if (share_wstr) {
Victor Stinnerfe226c02011-10-03 03:52:20 +0200629 _PyUnicode_WSTR(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200630 _PyUnicode_WSTR_LENGTH(unicode) = length;
631 }
632 if (share_utf8) {
Victor Stinner1c8d0c72011-10-03 12:11:00 +0200633 _PyUnicode_UTF8(unicode) = data;
Victor Stinnerc379ead2011-10-03 12:52:27 +0200634 _PyUnicode_UTF8_LENGTH(unicode) = length;
635 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200636 _PyUnicode_LENGTH(unicode) = length;
637 PyUnicode_WRITE(PyUnicode_KIND(unicode), data, length, 0);
Victor Stinner95663112011-10-04 01:03:50 +0200638 if (share_wstr || _PyUnicode_WSTR(unicode) == NULL) {
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200639 assert(_PyUnicode_CheckConsistency(unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +0200640 return 0;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200641 }
Victor Stinnerfe226c02011-10-03 03:52:20 +0200642 }
Victor Stinner95663112011-10-04 01:03:50 +0200643 assert(_PyUnicode_WSTR(unicode) != NULL);
644
645 /* check for integer overflow */
646 if (length > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
647 PyErr_NoMemory();
648 return -1;
649 }
650 wstr = _PyUnicode_WSTR(unicode);
651 wstr = PyObject_REALLOC(wstr, sizeof(wchar_t) * (length + 1));
652 if (!wstr) {
653 PyErr_NoMemory();
654 return -1;
655 }
656 _PyUnicode_WSTR(unicode) = wstr;
657 _PyUnicode_WSTR(unicode)[length] = 0;
658 _PyUnicode_WSTR_LENGTH(unicode) = length;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +0200659 assert(_PyUnicode_CheckConsistency(unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000660 return 0;
661}
662
Victor Stinnerfe226c02011-10-03 03:52:20 +0200663static PyObject*
664resize_copy(PyObject *unicode, Py_ssize_t length)
665{
666 Py_ssize_t copy_length;
667 if (PyUnicode_IS_COMPACT(unicode)) {
668 PyObject *copy;
669 assert(PyUnicode_IS_READY(unicode));
670
671 copy = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(unicode));
672 if (copy == NULL)
673 return NULL;
674
675 copy_length = Py_MIN(length, PyUnicode_GET_LENGTH(unicode));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +0200676 copy_characters(copy, 0, unicode, 0, copy_length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200677 return copy;
Victor Stinner8cfcbed2011-10-03 23:19:21 +0200678 }
679 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200680 PyObject *w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200681 assert(_PyUnicode_WSTR(unicode) != NULL);
682 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200683 w = (PyObject*)_PyUnicode_New(length);
Victor Stinnerfe226c02011-10-03 03:52:20 +0200684 if (w == NULL)
685 return NULL;
686 copy_length = _PyUnicode_WSTR_LENGTH(unicode);
687 copy_length = Py_MIN(copy_length, length);
688 Py_UNICODE_COPY(_PyUnicode_WSTR(w), _PyUnicode_WSTR(unicode),
689 copy_length);
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200690 return w;
Victor Stinnerfe226c02011-10-03 03:52:20 +0200691 }
692}
693
Guido van Rossumd57fd912000-03-10 22:53:23 +0000694/* We allocate one more byte to make sure the string is
Martin v. Löwis47383402007-08-15 07:32:56 +0000695 Ux0000 terminated; some code (e.g. new_identifier)
696 relies on that.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000697
698 XXX This allocator could further be enhanced by assuring that the
Benjamin Peterson29060642009-01-31 22:14:21 +0000699 free list never reduces its size below 1.
Guido van Rossumd57fd912000-03-10 22:53:23 +0000700
701*/
702
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200703#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200704static int unicode_old_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200705#endif
706
Alexander Belopolsky40018472011-02-26 01:02:56 +0000707static PyUnicodeObject *
708_PyUnicode_New(Py_ssize_t length)
Guido van Rossumd57fd912000-03-10 22:53:23 +0000709{
710 register PyUnicodeObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200711 size_t new_size;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000712
Thomas Wouters477c8d52006-05-27 19:21:47 +0000713 /* Optimization for empty strings */
Guido van Rossumd57fd912000-03-10 22:53:23 +0000714 if (length == 0 && unicode_empty != NULL) {
715 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200716 return (PyUnicodeObject*)unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000717 }
718
Neal Norwitz3ce5d922008-08-24 07:08:55 +0000719 /* Ensure we won't overflow the size. */
720 if (length > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
721 return (PyUnicodeObject *)PyErr_NoMemory();
722 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200723 if (length < 0) {
724 PyErr_SetString(PyExc_SystemError,
725 "Negative size passed to _PyUnicode_New");
726 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000727 }
728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200729#ifdef Py_DEBUG
730 ++unicode_old_new_calls;
731#endif
732
733 unicode = PyObject_New(PyUnicodeObject, &PyUnicode_Type);
734 if (unicode == NULL)
735 return NULL;
736 new_size = sizeof(Py_UNICODE) * ((size_t)length + 1);
737 _PyUnicode_WSTR(unicode) = (Py_UNICODE*) PyObject_MALLOC(new_size);
738 if (!_PyUnicode_WSTR(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +0000739 PyErr_NoMemory();
740 goto onError;
Guido van Rossum3c1bb802000-04-27 20:13:50 +0000741 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200742
Jeremy Hyltond8082792003-09-16 19:41:39 +0000743 /* Initialize the first element to guard against cases where
Tim Petersced69f82003-09-16 20:30:58 +0000744 * the caller fails before initializing str -- unicode_resize()
745 * reads str[0], and the Keep-Alive optimization can keep memory
746 * allocated for str alive across a call to unicode_dealloc(unicode).
747 * We don't want unicode_resize to read uninitialized memory in
748 * that case.
749 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200750 _PyUnicode_WSTR(unicode)[0] = 0;
751 _PyUnicode_WSTR(unicode)[length] = 0;
752 _PyUnicode_WSTR_LENGTH(unicode) = length;
753 _PyUnicode_HASH(unicode) = -1;
754 _PyUnicode_STATE(unicode).interned = 0;
755 _PyUnicode_STATE(unicode).kind = 0;
756 _PyUnicode_STATE(unicode).compact = 0;
757 _PyUnicode_STATE(unicode).ready = 0;
758 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +0200759 _PyUnicode_DATA_ANY(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200760 _PyUnicode_LENGTH(unicode) = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200761 _PyUnicode_UTF8(unicode) = NULL;
762 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +0100763 assert(_PyUnicode_CheckConsistency((PyObject *)unicode, 0));
Guido van Rossumd57fd912000-03-10 22:53:23 +0000764 return unicode;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000765
Benjamin Peterson29060642009-01-31 22:14:21 +0000766 onError:
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +0000767 /* XXX UNREF/NEWREF interface should be more symmetrical */
768 _Py_DEC_REFTOTAL;
Barry Warsaw51ac5802000-03-20 16:36:48 +0000769 _Py_ForgetReference((PyObject *)unicode);
Neil Schemenauer58aa8612002-04-12 03:07:20 +0000770 PyObject_Del(unicode);
Barry Warsaw51ac5802000-03-20 16:36:48 +0000771 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +0000772}
773
Victor Stinnerf42dc442011-10-02 23:33:16 +0200774static const char*
775unicode_kind_name(PyObject *unicode)
776{
Victor Stinner42dfd712011-10-03 14:41:45 +0200777 /* don't check consistency: unicode_kind_name() is called from
778 _PyUnicode_Dump() */
Victor Stinnerf42dc442011-10-02 23:33:16 +0200779 if (!PyUnicode_IS_COMPACT(unicode))
780 {
781 if (!PyUnicode_IS_READY(unicode))
782 return "wstr";
783 switch(PyUnicode_KIND(unicode))
784 {
785 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200786 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200787 return "legacy ascii";
788 else
789 return "legacy latin1";
790 case PyUnicode_2BYTE_KIND:
791 return "legacy UCS2";
792 case PyUnicode_4BYTE_KIND:
793 return "legacy UCS4";
794 default:
795 return "<legacy invalid kind>";
796 }
797 }
798 assert(PyUnicode_IS_READY(unicode));
799 switch(PyUnicode_KIND(unicode))
800 {
801 case PyUnicode_1BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200802 if (PyUnicode_IS_ASCII(unicode))
Victor Stinnerf42dc442011-10-02 23:33:16 +0200803 return "ascii";
804 else
Victor Stinnera3b334d2011-10-03 13:53:37 +0200805 return "latin1";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200806 case PyUnicode_2BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200807 return "UCS2";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200808 case PyUnicode_4BYTE_KIND:
Victor Stinnera3b334d2011-10-03 13:53:37 +0200809 return "UCS4";
Victor Stinnerf42dc442011-10-02 23:33:16 +0200810 default:
811 return "<invalid compact kind>";
812 }
813}
814
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200815#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +0200816static int unicode_new_new_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200817
818/* Functions wrapping macros for use in debugger */
819char *_PyUnicode_utf8(void *unicode){
Victor Stinnere90fe6a2011-10-01 16:48:13 +0200820 return PyUnicode_UTF8(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200821}
822
823void *_PyUnicode_compact_data(void *unicode) {
824 return _PyUnicode_COMPACT_DATA(unicode);
825}
826void *_PyUnicode_data(void *unicode){
827 printf("obj %p\n", unicode);
828 printf("compact %d\n", PyUnicode_IS_COMPACT(unicode));
829 printf("compact ascii %d\n", PyUnicode_IS_COMPACT_ASCII(unicode));
830 printf("ascii op %p\n", ((void*)((PyASCIIObject*)(unicode) + 1)));
831 printf("compact op %p\n", ((void*)((PyCompactUnicodeObject*)(unicode) + 1)));
832 printf("compact data %p\n", _PyUnicode_COMPACT_DATA(unicode));
833 return PyUnicode_DATA(unicode);
834}
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200835
836void
837_PyUnicode_Dump(PyObject *op)
838{
839 PyASCIIObject *ascii = (PyASCIIObject *)op;
Victor Stinnera849a4b2011-10-03 12:12:11 +0200840 PyCompactUnicodeObject *compact = (PyCompactUnicodeObject *)op;
841 PyUnicodeObject *unicode = (PyUnicodeObject *)op;
842 void *data;
Victor Stinner0d60e872011-10-23 19:47:19 +0200843
Victor Stinnera849a4b2011-10-03 12:12:11 +0200844 if (ascii->state.compact)
Victor Stinner0d60e872011-10-23 19:47:19 +0200845 {
846 if (ascii->state.ascii)
847 data = (ascii + 1);
848 else
849 data = (compact + 1);
850 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200851 else
852 data = unicode->data.any;
Victor Stinner0d60e872011-10-23 19:47:19 +0200853 printf("%s: len=%zu, ",unicode_kind_name(op), ascii->length);
854
Victor Stinnera849a4b2011-10-03 12:12:11 +0200855 if (ascii->wstr == data)
856 printf("shared ");
857 printf("wstr=%p", ascii->wstr);
Victor Stinner0d60e872011-10-23 19:47:19 +0200858
Victor Stinnera3b334d2011-10-03 13:53:37 +0200859 if (!(ascii->state.ascii == 1 && ascii->state.compact == 1)) {
Victor Stinnera849a4b2011-10-03 12:12:11 +0200860 printf(" (%zu), ", compact->wstr_length);
861 if (!ascii->state.compact && compact->utf8 == unicode->data.any)
862 printf("shared ");
863 printf("utf8=%p (%zu)", compact->utf8, compact->utf8_length);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200864 }
Victor Stinnera849a4b2011-10-03 12:12:11 +0200865 printf(", data=%p\n", data);
Victor Stinnerfe0c1552011-10-03 02:59:31 +0200866}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200867#endif
868
869PyObject *
870PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar)
871{
872 PyObject *obj;
873 PyCompactUnicodeObject *unicode;
874 void *data;
875 int kind_state;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200876 int is_sharing, is_ascii;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200877 Py_ssize_t char_size;
878 Py_ssize_t struct_size;
879
880 /* Optimization for empty strings */
881 if (size == 0 && unicode_empty != NULL) {
882 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +0200883 return unicode_empty;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200884 }
885
886#ifdef Py_DEBUG
887 ++unicode_new_new_calls;
888#endif
889
Victor Stinner9e9d6892011-10-04 01:02:02 +0200890 is_ascii = 0;
891 is_sharing = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200892 struct_size = sizeof(PyCompactUnicodeObject);
893 if (maxchar < 128) {
894 kind_state = PyUnicode_1BYTE_KIND;
895 char_size = 1;
896 is_ascii = 1;
897 struct_size = sizeof(PyASCIIObject);
898 }
899 else if (maxchar < 256) {
900 kind_state = PyUnicode_1BYTE_KIND;
901 char_size = 1;
902 }
903 else if (maxchar < 65536) {
904 kind_state = PyUnicode_2BYTE_KIND;
905 char_size = 2;
906 if (sizeof(wchar_t) == 2)
907 is_sharing = 1;
908 }
909 else {
910 kind_state = PyUnicode_4BYTE_KIND;
911 char_size = 4;
912 if (sizeof(wchar_t) == 4)
913 is_sharing = 1;
914 }
915
916 /* Ensure we won't overflow the size. */
917 if (size < 0) {
918 PyErr_SetString(PyExc_SystemError,
919 "Negative size passed to PyUnicode_New");
920 return NULL;
921 }
922 if (size > ((PY_SSIZE_T_MAX - struct_size) / char_size - 1))
923 return PyErr_NoMemory();
924
925 /* Duplicated allocation code from _PyObject_New() instead of a call to
926 * PyObject_New() so we are able to allocate space for the object and
927 * it's data buffer.
928 */
929 obj = (PyObject *) PyObject_MALLOC(struct_size + (size + 1) * char_size);
930 if (obj == NULL)
931 return PyErr_NoMemory();
932 obj = PyObject_INIT(obj, &PyUnicode_Type);
933 if (obj == NULL)
934 return NULL;
935
936 unicode = (PyCompactUnicodeObject *)obj;
937 if (is_ascii)
938 data = ((PyASCIIObject*)obj) + 1;
939 else
940 data = unicode + 1;
941 _PyUnicode_LENGTH(unicode) = size;
942 _PyUnicode_HASH(unicode) = -1;
943 _PyUnicode_STATE(unicode).interned = 0;
944 _PyUnicode_STATE(unicode).kind = kind_state;
945 _PyUnicode_STATE(unicode).compact = 1;
946 _PyUnicode_STATE(unicode).ready = 1;
947 _PyUnicode_STATE(unicode).ascii = is_ascii;
948 if (is_ascii) {
949 ((char*)data)[size] = 0;
950 _PyUnicode_WSTR(unicode) = NULL;
951 }
952 else if (kind_state == PyUnicode_1BYTE_KIND) {
953 ((char*)data)[size] = 0;
954 _PyUnicode_WSTR(unicode) = NULL;
955 _PyUnicode_WSTR_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200956 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200957 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200958 }
959 else {
960 unicode->utf8 = NULL;
Victor Stinner9e9d6892011-10-04 01:02:02 +0200961 unicode->utf8_length = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200962 if (kind_state == PyUnicode_2BYTE_KIND)
963 ((Py_UCS2*)data)[size] = 0;
964 else /* kind_state == PyUnicode_4BYTE_KIND */
965 ((Py_UCS4*)data)[size] = 0;
966 if (is_sharing) {
967 _PyUnicode_WSTR_LENGTH(unicode) = size;
968 _PyUnicode_WSTR(unicode) = (wchar_t *)data;
969 }
970 else {
971 _PyUnicode_WSTR_LENGTH(unicode) = 0;
972 _PyUnicode_WSTR(unicode) = NULL;
973 }
974 }
Victor Stinner7931d9a2011-11-04 00:22:48 +0100975 assert(_PyUnicode_CheckConsistency((PyObject*)unicode, 0));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200976 return obj;
977}
978
979#if SIZEOF_WCHAR_T == 2
980/* Helper function to convert a 16-bits wchar_t representation to UCS4, this
981 will decode surrogate pairs, the other conversions are implemented as macros
Georg Brandl7597add2011-10-05 16:36:47 +0200982 for efficiency.
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200983
984 This function assumes that unicode can hold one more code point than wstr
985 characters for a terminating null character. */
Victor Stinnerc53be962011-10-02 21:33:54 +0200986static void
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200987unicode_convert_wchar_to_ucs4(const wchar_t *begin, const wchar_t *end,
Victor Stinner9db1a8b2011-10-23 20:04:37 +0200988 PyObject *unicode)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200989{
990 const wchar_t *iter;
991 Py_UCS4 *ucs4_out;
992
Victor Stinner910337b2011-10-03 03:20:16 +0200993 assert(unicode != NULL);
994 assert(_PyUnicode_CHECK(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +0200995 assert(_PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);
996 ucs4_out = PyUnicode_4BYTE_DATA(unicode);
997
998 for (iter = begin; iter < end; ) {
999 assert(ucs4_out < (PyUnicode_4BYTE_DATA(unicode) +
1000 _PyUnicode_GET_LENGTH(unicode)));
1001 if (*iter >= 0xD800 && *iter <= 0xDBFF
1002 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1003 {
1004 *ucs4_out++ = (((iter[0] & 0x3FF)<<10) | (iter[1] & 0x3FF)) + 0x10000;
1005 iter += 2;
1006 }
1007 else {
1008 *ucs4_out++ = *iter;
1009 iter++;
1010 }
1011 }
1012 assert(ucs4_out == (PyUnicode_4BYTE_DATA(unicode) +
1013 _PyUnicode_GET_LENGTH(unicode)));
1014
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001015}
1016#endif
1017
Victor Stinnercd9950f2011-10-02 00:34:53 +02001018static int
1019_PyUnicode_Dirty(PyObject *unicode)
1020{
Victor Stinner910337b2011-10-03 03:20:16 +02001021 assert(_PyUnicode_CHECK(unicode));
Victor Stinnercd9950f2011-10-02 00:34:53 +02001022 if (Py_REFCNT(unicode) != 1) {
Victor Stinner01698042011-10-04 00:04:26 +02001023 PyErr_SetString(PyExc_SystemError,
Victor Stinnercd9950f2011-10-02 00:34:53 +02001024 "Cannot modify a string having more than 1 reference");
1025 return -1;
1026 }
1027 _PyUnicode_DIRTY(unicode);
1028 return 0;
1029}
1030
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001031static int
1032_copy_characters(PyObject *to, Py_ssize_t to_start,
1033 PyObject *from, Py_ssize_t from_start,
1034 Py_ssize_t how_many, int check_maxchar)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001035{
Victor Stinnera0702ab2011-09-29 14:14:38 +02001036 unsigned int from_kind, to_kind;
1037 void *from_data, *to_data;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001038 int fast;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001039
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001040 assert(PyUnicode_Check(from));
1041 assert(PyUnicode_Check(to));
1042 assert(PyUnicode_IS_READY(from));
1043 assert(PyUnicode_IS_READY(to));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001044
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001045 assert(PyUnicode_GET_LENGTH(from) >= how_many);
1046 assert(to_start + how_many <= PyUnicode_GET_LENGTH(to));
1047 assert(0 <= how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001048
Victor Stinnerf5ca1a22011-09-28 23:54:59 +02001049 if (how_many == 0)
1050 return 0;
1051
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001052 from_kind = PyUnicode_KIND(from);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001053 from_data = PyUnicode_DATA(from);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001054 to_kind = PyUnicode_KIND(to);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001055 to_data = PyUnicode_DATA(to);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001056
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001057#ifdef Py_DEBUG
1058 if (!check_maxchar
1059 && (from_kind > to_kind
1060 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to))))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001061 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001062 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
1063 Py_UCS4 ch;
1064 Py_ssize_t i;
1065 for (i=0; i < how_many; i++) {
1066 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1067 assert(ch <= to_maxchar);
1068 }
1069 }
1070#endif
1071 fast = (from_kind == to_kind);
1072 if (check_maxchar
1073 && (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
1074 {
1075 /* deny latin1 => ascii */
1076 fast = 0;
1077 }
1078
1079 if (fast) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +02001080 Py_MEMCPY((char*)to_data + to_kind * to_start,
1081 (char*)from_data + from_kind * from_start,
1082 to_kind * how_many);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001083 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001084 else if (from_kind == PyUnicode_1BYTE_KIND
1085 && to_kind == PyUnicode_2BYTE_KIND)
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001086 {
1087 _PyUnicode_CONVERT_BYTES(
1088 Py_UCS1, Py_UCS2,
1089 PyUnicode_1BYTE_DATA(from) + from_start,
1090 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1091 PyUnicode_2BYTE_DATA(to) + to_start
1092 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001093 }
Victor Stinner157f83f2011-09-28 21:41:31 +02001094 else if (from_kind == PyUnicode_1BYTE_KIND
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001095 && to_kind == PyUnicode_4BYTE_KIND)
1096 {
1097 _PyUnicode_CONVERT_BYTES(
1098 Py_UCS1, Py_UCS4,
1099 PyUnicode_1BYTE_DATA(from) + from_start,
1100 PyUnicode_1BYTE_DATA(from) + from_start + how_many,
1101 PyUnicode_4BYTE_DATA(to) + to_start
1102 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001103 }
1104 else if (from_kind == PyUnicode_2BYTE_KIND
1105 && to_kind == PyUnicode_4BYTE_KIND)
1106 {
1107 _PyUnicode_CONVERT_BYTES(
1108 Py_UCS2, Py_UCS4,
1109 PyUnicode_2BYTE_DATA(from) + from_start,
1110 PyUnicode_2BYTE_DATA(from) + from_start + how_many,
1111 PyUnicode_4BYTE_DATA(to) + to_start
1112 );
Victor Stinnerbe78eaf2011-09-28 21:37:03 +02001113 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001114 else {
Victor Stinnerf42dc442011-10-02 23:33:16 +02001115 /* check if max_char(from substring) <= max_char(to) */
1116 if (from_kind > to_kind
1117 /* latin1 => ascii */
Victor Stinnerb9275c12011-10-05 14:01:42 +02001118 || (!PyUnicode_IS_ASCII(from) && PyUnicode_IS_ASCII(to)))
Victor Stinnerf42dc442011-10-02 23:33:16 +02001119 {
Victor Stinnera0702ab2011-09-29 14:14:38 +02001120 /* slow path to check for character overflow */
1121 const Py_UCS4 to_maxchar = PyUnicode_MAX_CHAR_VALUE(to);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001122 Py_UCS4 ch;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001123 Py_ssize_t i;
1124
Victor Stinner56c161a2011-10-06 02:47:11 +02001125#ifdef Py_DEBUG
Victor Stinnera0702ab2011-09-29 14:14:38 +02001126 for (i=0; i < how_many; i++) {
1127 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
Victor Stinner56c161a2011-10-06 02:47:11 +02001128 assert(ch <= to_maxchar);
Victor Stinnera0702ab2011-09-29 14:14:38 +02001129 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1130 }
Victor Stinner56c161a2011-10-06 02:47:11 +02001131#else
1132 if (!check_maxchar) {
1133 for (i=0; i < how_many; i++) {
1134 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1135 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1136 }
1137 }
1138 else {
1139 for (i=0; i < how_many; i++) {
1140 ch = PyUnicode_READ(from_kind, from_data, from_start + i);
1141 if (ch > to_maxchar)
1142 return 1;
1143 PyUnicode_WRITE(to_kind, to_data, to_start + i, ch);
1144 }
1145 }
1146#endif
Victor Stinnera0702ab2011-09-29 14:14:38 +02001147 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001148 else {
Victor Stinner56c161a2011-10-06 02:47:11 +02001149 assert(0 && "inconsistent state");
1150 return 1;
Victor Stinnera0702ab2011-09-29 14:14:38 +02001151 }
1152 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001153 return 0;
1154}
1155
1156static void
1157copy_characters(PyObject *to, Py_ssize_t to_start,
1158 PyObject *from, Py_ssize_t from_start,
1159 Py_ssize_t how_many)
1160{
1161 (void)_copy_characters(to, to_start, from, from_start, how_many, 0);
1162}
1163
1164Py_ssize_t
1165PyUnicode_CopyCharacters(PyObject *to, Py_ssize_t to_start,
1166 PyObject *from, Py_ssize_t from_start,
1167 Py_ssize_t how_many)
1168{
1169 int err;
1170
1171 if (!PyUnicode_Check(from) || !PyUnicode_Check(to)) {
1172 PyErr_BadInternalCall();
1173 return -1;
1174 }
1175
1176 if (PyUnicode_READY(from))
1177 return -1;
1178 if (PyUnicode_READY(to))
1179 return -1;
1180
1181 how_many = Py_MIN(PyUnicode_GET_LENGTH(from), how_many);
1182 if (to_start + how_many > PyUnicode_GET_LENGTH(to)) {
1183 PyErr_Format(PyExc_SystemError,
1184 "Cannot write %zi characters at %zi "
1185 "in a string of %zi characters",
1186 how_many, to_start, PyUnicode_GET_LENGTH(to));
1187 return -1;
1188 }
1189
1190 if (how_many == 0)
1191 return 0;
1192
1193 if (_PyUnicode_Dirty(to))
1194 return -1;
1195
1196 err = _copy_characters(to, to_start, from, from_start, how_many, 1);
1197 if (err) {
1198 PyErr_Format(PyExc_SystemError,
1199 "Cannot copy %s characters "
1200 "into a string of %s characters",
1201 unicode_kind_name(from),
1202 unicode_kind_name(to));
1203 return -1;
1204 }
Victor Stinnera0702ab2011-09-29 14:14:38 +02001205 return how_many;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001206}
1207
Victor Stinner17222162011-09-28 22:15:37 +02001208/* Find the maximum code point and count the number of surrogate pairs so a
1209 correct string length can be computed before converting a string to UCS4.
1210 This function counts single surrogates as a character and not as a pair.
1211
1212 Return 0 on success, or -1 on error. */
1213static int
1214find_maxchar_surrogates(const wchar_t *begin, const wchar_t *end,
1215 Py_UCS4 *maxchar, Py_ssize_t *num_surrogates)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001216{
1217 const wchar_t *iter;
1218
Victor Stinnerc53be962011-10-02 21:33:54 +02001219 assert(num_surrogates != NULL && maxchar != NULL);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001220 *num_surrogates = 0;
1221 *maxchar = 0;
1222
1223 for (iter = begin; iter < end; ) {
Victor Stinnerae864852011-10-05 14:02:44 +02001224 if (*iter > *maxchar) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001225 *maxchar = *iter;
Victor Stinnerae864852011-10-05 14:02:44 +02001226#if SIZEOF_WCHAR_T != 2
1227 if (*maxchar >= 0x10000)
1228 return 0;
1229#endif
1230 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001231#if SIZEOF_WCHAR_T == 2
1232 if (*iter >= 0xD800 && *iter <= 0xDBFF
1233 && (iter+1) < end && iter[1] >= 0xDC00 && iter[1] <= 0xDFFF)
1234 {
1235 Py_UCS4 surrogate_val;
1236 surrogate_val = (((iter[0] & 0x3FF)<<10)
1237 | (iter[1] & 0x3FF)) + 0x10000;
1238 ++(*num_surrogates);
1239 if (surrogate_val > *maxchar)
1240 *maxchar = surrogate_val;
1241 iter += 2;
1242 }
1243 else
1244 iter++;
1245#else
1246 iter++;
1247#endif
1248 }
1249 return 0;
1250}
1251
1252#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001253static int unicode_ready_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001254#endif
1255
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001256static int
1257unicode_ready(PyObject **p_obj, int replace)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001258{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001259 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001260 wchar_t *end;
1261 Py_UCS4 maxchar = 0;
1262 Py_ssize_t num_surrogates;
1263#if SIZEOF_WCHAR_T == 2
1264 Py_ssize_t length_wo_surrogates;
1265#endif
1266
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001267 assert(p_obj != NULL);
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001268 unicode = *p_obj;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001269
Georg Brandl7597add2011-10-05 16:36:47 +02001270 /* _PyUnicode_Ready() is only intended for old-style API usage where
Victor Stinnerd8f65102011-09-29 19:43:17 +02001271 strings were created using _PyObject_New() and where no canonical
1272 representation (the str field) has been set yet aka strings
1273 which are not yet ready. */
Victor Stinner910337b2011-10-03 03:20:16 +02001274 assert(_PyUnicode_CHECK(unicode));
1275 assert(_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001276 assert(_PyUnicode_WSTR(unicode) != NULL);
Victor Stinnerc3c74152011-10-02 20:39:55 +02001277 assert(_PyUnicode_DATA_ANY(unicode) == NULL);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001278 assert(_PyUnicode_UTF8(unicode) == NULL);
Victor Stinnerd8f65102011-09-29 19:43:17 +02001279 /* Actually, it should neither be interned nor be anything else: */
1280 assert(_PyUnicode_STATE(unicode).interned == SSTATE_NOT_INTERNED);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001281
1282#ifdef Py_DEBUG
1283 ++unicode_ready_calls;
1284#endif
1285
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001286#ifdef Py_DEBUG
1287 assert(!replace || Py_REFCNT(unicode) == 1);
1288#else
1289 if (replace && Py_REFCNT(unicode) != 1)
1290 replace = 0;
1291#endif
1292 if (replace) {
1293 Py_ssize_t len = _PyUnicode_WSTR_LENGTH(unicode);
1294 wchar_t *wstr = _PyUnicode_WSTR(unicode);
1295 /* Optimization for empty strings */
1296 if (len == 0) {
1297 Py_INCREF(unicode_empty);
1298 Py_DECREF(*p_obj);
1299 *p_obj = unicode_empty;
1300 return 0;
1301 }
1302 if (len == 1 && wstr[0] < 256) {
1303 PyObject *latin1_char = get_latin1_char((unsigned char)wstr[0]);
1304 if (latin1_char == NULL)
1305 return -1;
1306 Py_DECREF(*p_obj);
1307 *p_obj = latin1_char;
1308 return 0;
1309 }
1310 }
1311
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001312 end = _PyUnicode_WSTR(unicode) + _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinner17222162011-09-28 22:15:37 +02001313 if (find_maxchar_surrogates(_PyUnicode_WSTR(unicode), end,
Victor Stinnerd8f65102011-09-29 19:43:17 +02001314 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001315 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001316
1317 if (maxchar < 256) {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001318 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(_PyUnicode_WSTR_LENGTH(unicode) + 1);
1319 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001320 PyErr_NoMemory();
1321 return -1;
1322 }
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001323 _PyUnicode_CONVERT_BYTES(wchar_t, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001324 _PyUnicode_WSTR(unicode), end,
1325 PyUnicode_1BYTE_DATA(unicode));
1326 PyUnicode_1BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1327 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1328 _PyUnicode_STATE(unicode).kind = PyUnicode_1BYTE_KIND;
1329 if (maxchar < 128) {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001330 _PyUnicode_STATE(unicode).ascii = 1;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001331 _PyUnicode_UTF8(unicode) = _PyUnicode_DATA_ANY(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001332 _PyUnicode_UTF8_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001333 }
1334 else {
Victor Stinnera3b334d2011-10-03 13:53:37 +02001335 _PyUnicode_STATE(unicode).ascii = 0;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001336 _PyUnicode_UTF8(unicode) = NULL;
1337 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001338 }
1339 PyObject_FREE(_PyUnicode_WSTR(unicode));
1340 _PyUnicode_WSTR(unicode) = NULL;
1341 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1342 }
1343 /* In this case we might have to convert down from 4-byte native
1344 wchar_t to 2-byte unicode. */
1345 else if (maxchar < 65536) {
1346 assert(num_surrogates == 0 &&
1347 "FindMaxCharAndNumSurrogatePairs() messed up");
1348
Victor Stinner506f5922011-09-28 22:34:18 +02001349#if SIZEOF_WCHAR_T == 2
1350 /* We can share representations and are done. */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001351 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Victor Stinner506f5922011-09-28 22:34:18 +02001352 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1353 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1354 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001355 _PyUnicode_UTF8(unicode) = NULL;
1356 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001357#else
1358 /* sizeof(wchar_t) == 4 */
Victor Stinnerc3c74152011-10-02 20:39:55 +02001359 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(
Victor Stinner506f5922011-09-28 22:34:18 +02001360 2 * (_PyUnicode_WSTR_LENGTH(unicode) + 1));
Victor Stinnerc3c74152011-10-02 20:39:55 +02001361 if (!_PyUnicode_DATA_ANY(unicode)) {
Victor Stinner506f5922011-09-28 22:34:18 +02001362 PyErr_NoMemory();
1363 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001364 }
Victor Stinner506f5922011-09-28 22:34:18 +02001365 _PyUnicode_CONVERT_BYTES(wchar_t, Py_UCS2,
1366 _PyUnicode_WSTR(unicode), end,
1367 PyUnicode_2BYTE_DATA(unicode));
1368 PyUnicode_2BYTE_DATA(unicode)[_PyUnicode_WSTR_LENGTH(unicode)] = '\0';
1369 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
1370 _PyUnicode_STATE(unicode).kind = PyUnicode_2BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001371 _PyUnicode_UTF8(unicode) = NULL;
1372 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner506f5922011-09-28 22:34:18 +02001373 PyObject_FREE(_PyUnicode_WSTR(unicode));
1374 _PyUnicode_WSTR(unicode) = NULL;
1375 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1376#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001377 }
1378 /* maxchar exeeds 16 bit, wee need 4 bytes for unicode characters */
1379 else {
1380#if SIZEOF_WCHAR_T == 2
1381 /* in case the native representation is 2-bytes, we need to allocate a
1382 new normalized 4-byte version. */
1383 length_wo_surrogates = _PyUnicode_WSTR_LENGTH(unicode) - num_surrogates;
Victor Stinnerc3c74152011-10-02 20:39:55 +02001384 _PyUnicode_DATA_ANY(unicode) = PyObject_MALLOC(4 * (length_wo_surrogates + 1));
1385 if (!_PyUnicode_DATA_ANY(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001386 PyErr_NoMemory();
1387 return -1;
1388 }
1389 _PyUnicode_LENGTH(unicode) = length_wo_surrogates;
1390 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001391 _PyUnicode_UTF8(unicode) = NULL;
1392 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Victor Stinner126c5592011-10-03 04:17:10 +02001393 /* unicode_convert_wchar_to_ucs4() requires a ready string */
1394 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerc53be962011-10-02 21:33:54 +02001395 unicode_convert_wchar_to_ucs4(_PyUnicode_WSTR(unicode), end, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001396 PyObject_FREE(_PyUnicode_WSTR(unicode));
1397 _PyUnicode_WSTR(unicode) = NULL;
1398 _PyUnicode_WSTR_LENGTH(unicode) = 0;
1399#else
1400 assert(num_surrogates == 0);
1401
Victor Stinnerc3c74152011-10-02 20:39:55 +02001402 _PyUnicode_DATA_ANY(unicode) = _PyUnicode_WSTR(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001403 _PyUnicode_LENGTH(unicode) = _PyUnicode_WSTR_LENGTH(unicode);
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001404 _PyUnicode_UTF8(unicode) = NULL;
1405 _PyUnicode_UTF8_LENGTH(unicode) = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001406 _PyUnicode_STATE(unicode).kind = PyUnicode_4BYTE_KIND;
1407#endif
1408 PyUnicode_4BYTE_DATA(unicode)[_PyUnicode_LENGTH(unicode)] = '\0';
1409 }
1410 _PyUnicode_STATE(unicode).ready = 1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001411 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001412 return 0;
1413}
1414
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02001415int
1416_PyUnicode_ReadyReplace(PyObject **op)
1417{
1418 return unicode_ready(op, 1);
1419}
1420
1421int
1422_PyUnicode_Ready(PyObject *op)
1423{
1424 return unicode_ready(&op, 0);
1425}
1426
Alexander Belopolsky40018472011-02-26 01:02:56 +00001427static void
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001428unicode_dealloc(register PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001429{
Walter Dörwald16807132007-05-25 13:52:07 +00001430 switch (PyUnicode_CHECK_INTERNED(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00001431 case SSTATE_NOT_INTERNED:
1432 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001433
Benjamin Peterson29060642009-01-31 22:14:21 +00001434 case SSTATE_INTERNED_MORTAL:
1435 /* revive dead object temporarily for DelItem */
1436 Py_REFCNT(unicode) = 3;
Victor Stinner7931d9a2011-11-04 00:22:48 +01001437 if (PyDict_DelItem(interned, unicode) != 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00001438 Py_FatalError(
1439 "deletion of interned string failed");
1440 break;
Walter Dörwald16807132007-05-25 13:52:07 +00001441
Benjamin Peterson29060642009-01-31 22:14:21 +00001442 case SSTATE_INTERNED_IMMORTAL:
1443 Py_FatalError("Immortal interned string died.");
Walter Dörwald16807132007-05-25 13:52:07 +00001444
Benjamin Peterson29060642009-01-31 22:14:21 +00001445 default:
1446 Py_FatalError("Inconsistent interned string state.");
Walter Dörwald16807132007-05-25 13:52:07 +00001447 }
1448
Victor Stinner03490912011-10-03 23:45:12 +02001449 if (_PyUnicode_HAS_WSTR_MEMORY(unicode))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001450 PyObject_DEL(_PyUnicode_WSTR(unicode));
Victor Stinner829c0ad2011-10-03 01:08:02 +02001451 if (_PyUnicode_HAS_UTF8_MEMORY(unicode))
Victor Stinnere90fe6a2011-10-01 16:48:13 +02001452 PyObject_DEL(_PyUnicode_UTF8(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001453
1454 if (PyUnicode_IS_COMPACT(unicode)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01001455 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001456 }
1457 else {
Victor Stinnerc3c74152011-10-02 20:39:55 +02001458 if (_PyUnicode_DATA_ANY(unicode))
1459 PyObject_DEL(_PyUnicode_DATA_ANY(unicode));
Victor Stinner7931d9a2011-11-04 00:22:48 +01001460 Py_TYPE(unicode)->tp_free(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001461 }
1462}
1463
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001464#ifdef Py_DEBUG
1465static int
1466unicode_is_singleton(PyObject *unicode)
1467{
1468 PyASCIIObject *ascii = (PyASCIIObject *)unicode;
1469 if (unicode == unicode_empty)
1470 return 1;
1471 if (ascii->state.kind != PyUnicode_WCHAR_KIND && ascii->length == 1)
1472 {
1473 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, 0);
1474 if (ch < 256 && unicode_latin1[ch] == unicode)
1475 return 1;
1476 }
1477 return 0;
1478}
1479#endif
1480
Alexander Belopolsky40018472011-02-26 01:02:56 +00001481static int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001482unicode_resizable(PyObject *unicode)
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001483{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001484 if (Py_REFCNT(unicode) != 1)
1485 return 0;
1486 if (PyUnicode_CHECK_INTERNED(unicode))
1487 return 0;
Victor Stinner77bb47b2011-10-03 20:06:05 +02001488#ifdef Py_DEBUG
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02001489 /* singleton refcount is greater than 1 */
1490 assert(!unicode_is_singleton(unicode));
Victor Stinner77bb47b2011-10-03 20:06:05 +02001491#endif
Victor Stinnerfe226c02011-10-03 03:52:20 +02001492 return 1;
1493}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001494
Victor Stinnerfe226c02011-10-03 03:52:20 +02001495static int
1496unicode_resize(PyObject **p_unicode, Py_ssize_t length)
1497{
1498 PyObject *unicode;
1499 Py_ssize_t old_length;
1500
1501 assert(p_unicode != NULL);
1502 unicode = *p_unicode;
1503
1504 assert(unicode != NULL);
1505 assert(PyUnicode_Check(unicode));
1506 assert(0 <= length);
1507
Victor Stinner910337b2011-10-03 03:20:16 +02001508 if (_PyUnicode_KIND(unicode) == PyUnicode_WCHAR_KIND)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001509 old_length = PyUnicode_WSTR_LENGTH(unicode);
1510 else
1511 old_length = PyUnicode_GET_LENGTH(unicode);
1512 if (old_length == length)
1513 return 0;
1514
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001515 if (length == 0) {
1516 Py_DECREF(*p_unicode);
1517 *p_unicode = unicode_empty;
1518 Py_INCREF(*p_unicode);
1519 return 0;
1520 }
1521
Victor Stinnerfe226c02011-10-03 03:52:20 +02001522 if (!unicode_resizable(unicode)) {
1523 PyObject *copy = resize_copy(unicode, length);
1524 if (copy == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00001525 return -1;
Victor Stinnerfe226c02011-10-03 03:52:20 +02001526 Py_DECREF(*p_unicode);
1527 *p_unicode = copy;
Benjamin Peterson29060642009-01-31 22:14:21 +00001528 return 0;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001529 }
1530
Victor Stinnerfe226c02011-10-03 03:52:20 +02001531 if (PyUnicode_IS_COMPACT(unicode)) {
1532 *p_unicode = resize_compact(unicode, length);
1533 if (*p_unicode == NULL)
1534 return -1;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001535 assert(_PyUnicode_CheckConsistency(*p_unicode, 0));
Victor Stinnerfe226c02011-10-03 03:52:20 +02001536 return 0;
Benjamin Peterson4bfce8f2011-10-03 19:35:07 -04001537 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001538 return resize_inplace(unicode, length);
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001539}
1540
Alexander Belopolsky40018472011-02-26 01:02:56 +00001541int
Victor Stinnerfe226c02011-10-03 03:52:20 +02001542PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length)
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001543{
Victor Stinnerfe226c02011-10-03 03:52:20 +02001544 PyObject *unicode;
1545 if (p_unicode == NULL) {
1546 PyErr_BadInternalCall();
1547 return -1;
1548 }
1549 unicode = *p_unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001550 if (unicode == NULL || !PyUnicode_Check(unicode) || length < 0)
Victor Stinnerfe226c02011-10-03 03:52:20 +02001551 {
1552 PyErr_BadInternalCall();
1553 return -1;
1554 }
1555 return unicode_resize(p_unicode, length);
Alexandre Vassalottiaa0e5312008-12-27 06:43:58 +00001556}
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001557
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001558static int
Victor Stinner0a045ef2011-11-09 00:02:42 +01001559unicode_widen(PyObject **p_unicode, unsigned int maxchar)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01001560{
1561 PyObject *result;
1562 assert(PyUnicode_IS_READY(*p_unicode));
1563 if (maxchar <= PyUnicode_MAX_CHAR_VALUE(*p_unicode))
1564 return 0;
1565 result = PyUnicode_New(PyUnicode_GET_LENGTH(*p_unicode),
1566 maxchar);
1567 if (result == NULL)
1568 return -1;
1569 PyUnicode_CopyCharacters(result, 0, *p_unicode, 0,
1570 PyUnicode_GET_LENGTH(*p_unicode));
1571 Py_DECREF(*p_unicode);
1572 *p_unicode = result;
1573 return 0;
1574}
1575
1576static int
1577unicode_putchar(PyObject **p_unicode, Py_ssize_t *pos,
1578 Py_UCS4 ch)
1579{
1580 if (unicode_widen(p_unicode, ch) < 0)
1581 return -1;
1582 PyUnicode_WRITE(PyUnicode_KIND(*p_unicode),
1583 PyUnicode_DATA(*p_unicode),
1584 (*pos)++, ch);
1585 return 0;
1586}
1587
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001588static PyObject*
1589get_latin1_char(unsigned char ch)
1590{
Victor Stinnera464fc12011-10-02 20:39:30 +02001591 PyObject *unicode = unicode_latin1[ch];
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001592 if (!unicode) {
Victor Stinnera464fc12011-10-02 20:39:30 +02001593 unicode = PyUnicode_New(1, ch);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001594 if (!unicode)
1595 return NULL;
1596 PyUnicode_1BYTE_DATA(unicode)[0] = ch;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001597 assert(_PyUnicode_CheckConsistency(unicode, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001598 unicode_latin1[ch] = unicode;
1599 }
1600 Py_INCREF(unicode);
Victor Stinnera464fc12011-10-02 20:39:30 +02001601 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001602}
1603
Alexander Belopolsky40018472011-02-26 01:02:56 +00001604PyObject *
1605PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00001606{
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001607 PyObject *unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001608 Py_UCS4 maxchar = 0;
1609 Py_ssize_t num_surrogates;
1610
1611 if (u == NULL)
1612 return (PyObject*)_PyUnicode_New(size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001613
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001614 /* If the Unicode data is known at construction time, we can apply
1615 some optimizations which share commonly used objects. */
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001616
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001617 /* Optimization for empty strings */
1618 if (size == 0 && unicode_empty != NULL) {
1619 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001620 return unicode_empty;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00001621 }
Tim Petersced69f82003-09-16 20:30:58 +00001622
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001623 /* Single character Unicode objects in the Latin-1 range are
1624 shared when using this constructor */
1625 if (size == 1 && *u < 256)
1626 return get_latin1_char((unsigned char)*u);
1627
1628 /* If not empty and not single character, copy the Unicode data
1629 into the new object */
Victor Stinnerd8f65102011-09-29 19:43:17 +02001630 if (find_maxchar_surrogates(u, u + size,
1631 &maxchar, &num_surrogates) == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001632 return NULL;
1633
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001634 unicode = PyUnicode_New(size - num_surrogates,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001635 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +00001636 if (!unicode)
1637 return NULL;
1638
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001639 switch (PyUnicode_KIND(unicode)) {
1640 case PyUnicode_1BYTE_KIND:
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001641 _PyUnicode_CONVERT_BYTES(Py_UNICODE, unsigned char,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001642 u, u + size, PyUnicode_1BYTE_DATA(unicode));
1643 break;
1644 case PyUnicode_2BYTE_KIND:
1645#if Py_UNICODE_SIZE == 2
1646 Py_MEMCPY(PyUnicode_2BYTE_DATA(unicode), u, size * 2);
1647#else
Victor Stinnerfb5f5f22011-09-28 21:39:49 +02001648 _PyUnicode_CONVERT_BYTES(Py_UNICODE, Py_UCS2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001649 u, u + size, PyUnicode_2BYTE_DATA(unicode));
1650#endif
1651 break;
1652 case PyUnicode_4BYTE_KIND:
1653#if SIZEOF_WCHAR_T == 2
1654 /* This is the only case which has to process surrogates, thus
1655 a simple copy loop is not enough and we need a function. */
Victor Stinnerc53be962011-10-02 21:33:54 +02001656 unicode_convert_wchar_to_ucs4(u, u + size, unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001657#else
1658 assert(num_surrogates == 0);
1659 Py_MEMCPY(PyUnicode_4BYTE_DATA(unicode), u, size * 4);
1660#endif
1661 break;
1662 default:
1663 assert(0 && "Impossible state");
1664 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00001665
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001666 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001667 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00001668}
1669
Alexander Belopolsky40018472011-02-26 01:02:56 +00001670PyObject *
1671PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001672{
Benjamin Peterson14339b62009-01-31 16:36:08 +00001673 if (size < 0) {
1674 PyErr_SetString(PyExc_SystemError,
Benjamin Peterson29060642009-01-31 22:14:21 +00001675 "Negative size passed to PyUnicode_FromStringAndSize");
Benjamin Peterson14339b62009-01-31 16:36:08 +00001676 return NULL;
1677 }
Christian Heimes33fe8092008-04-13 13:53:33 +00001678
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001679 /* If the Unicode data is known at construction time, we can apply
Martin v. Löwis9c121062007-08-05 20:26:11 +00001680 some optimizations which share commonly used objects.
1681 Also, this means the input must be UTF-8, so fall back to the
1682 UTF-8 decoder at the end. */
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001683 if (u != NULL) {
1684
Benjamin Peterson29060642009-01-31 22:14:21 +00001685 /* Optimization for empty strings */
1686 if (size == 0 && unicode_empty != NULL) {
1687 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02001688 return unicode_empty;
Benjamin Peterson14339b62009-01-31 16:36:08 +00001689 }
Benjamin Peterson29060642009-01-31 22:14:21 +00001690
1691 /* Single characters are shared when using this constructor.
1692 Restrict to ASCII, since the input must be UTF-8. */
Victor Stinner9faa3842011-10-23 20:06:00 +02001693 if (size == 1 && (unsigned char)*u < 128)
1694 return get_latin1_char((unsigned char)*u);
Martin v. Löwis9c121062007-08-05 20:26:11 +00001695
1696 return PyUnicode_DecodeUTF8(u, size, NULL);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001697 }
1698
Victor Stinner9db1a8b2011-10-23 20:04:37 +02001699 return (PyObject *)_PyUnicode_New(size);
Walter Dörwaldacaa5a12007-05-05 12:00:46 +00001700}
1701
Alexander Belopolsky40018472011-02-26 01:02:56 +00001702PyObject *
1703PyUnicode_FromString(const char *u)
Walter Dörwaldd2034312007-05-18 16:29:38 +00001704{
1705 size_t size = strlen(u);
1706 if (size > PY_SSIZE_T_MAX) {
1707 PyErr_SetString(PyExc_OverflowError, "input too long");
1708 return NULL;
1709 }
1710
1711 return PyUnicode_FromStringAndSize(u, size);
1712}
1713
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001714PyObject *
1715_PyUnicode_FromId(_Py_Identifier *id)
1716{
1717 if (!id->object) {
1718 id->object = PyUnicode_FromString(id->string);
1719 if (!id->object)
1720 return NULL;
1721 PyUnicode_InternInPlace(&id->object);
1722 assert(!id->next);
1723 id->next = static_strings;
1724 static_strings = id;
1725 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001726 return id->object;
1727}
1728
1729void
1730_PyUnicode_ClearStaticStrings()
1731{
1732 _Py_Identifier *i;
1733 for (i = static_strings; i; i = i->next) {
1734 Py_DECREF(i->object);
1735 i->object = NULL;
1736 i->next = NULL;
1737 }
1738}
1739
Victor Stinnere57b1c02011-09-28 22:20:48 +02001740static PyObject*
Victor Stinner0617b6e2011-10-05 23:26:01 +02001741unicode_fromascii(const unsigned char* s, Py_ssize_t size)
Victor Stinner702c7342011-10-05 13:50:52 +02001742{
Victor Stinner0617b6e2011-10-05 23:26:01 +02001743 PyObject *res;
1744#ifdef Py_DEBUG
1745 const unsigned char *p;
1746 const unsigned char *end = s + size;
1747 for (p=s; p < end; p++) {
1748 assert(*p < 128);
1749 }
1750#endif
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001751 if (size == 1)
1752 return get_latin1_char(s[0]);
Victor Stinner0617b6e2011-10-05 23:26:01 +02001753 res = PyUnicode_New(size, 127);
Victor Stinner702c7342011-10-05 13:50:52 +02001754 if (!res)
1755 return NULL;
Victor Stinner0617b6e2011-10-05 23:26:01 +02001756 memcpy(PyUnicode_1BYTE_DATA(res), s, size);
Victor Stinner702c7342011-10-05 13:50:52 +02001757 return res;
1758}
1759
Victor Stinnerc80d6d22011-10-05 14:13:28 +02001760static Py_UCS4
1761kind_maxchar_limit(unsigned int kind)
1762{
1763 switch(kind) {
1764 case PyUnicode_1BYTE_KIND:
1765 return 0x80;
1766 case PyUnicode_2BYTE_KIND:
1767 return 0x100;
1768 case PyUnicode_4BYTE_KIND:
1769 return 0x10000;
1770 default:
1771 assert(0 && "invalid kind");
1772 return 0x10ffff;
1773 }
1774}
1775
Victor Stinner702c7342011-10-05 13:50:52 +02001776static PyObject*
Victor Stinnere57b1c02011-09-28 22:20:48 +02001777_PyUnicode_FromUCS1(const unsigned char* u, Py_ssize_t size)
Mark Dickinson081dfee2009-03-18 14:47:41 +00001778{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001779 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001780 unsigned char max_char = 127;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001781
1782 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001783 if (size == 1)
1784 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001785 max_char = ucs1lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001786 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001787 if (!res)
1788 return NULL;
1789 memcpy(PyUnicode_1BYTE_DATA(res), u, size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001790 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001791 return res;
Mark Dickinson081dfee2009-03-18 14:47:41 +00001792}
1793
Victor Stinnere57b1c02011-09-28 22:20:48 +02001794static PyObject*
1795_PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001796{
1797 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001798 Py_UCS2 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001799
1800 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001801 if (size == 1 && u[0] < 256)
Victor Stinner4e101002011-10-11 23:27:52 +02001802 return get_latin1_char((unsigned char)u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001803 max_char = ucs2lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001804 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001805 if (!res)
1806 return NULL;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001807 if (max_char >= 256)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001808 memcpy(PyUnicode_2BYTE_DATA(res), u, sizeof(Py_UCS2)*size);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001809 else {
1810 _PyUnicode_CONVERT_BYTES(
1811 Py_UCS2, Py_UCS1, u, u + size, PyUnicode_1BYTE_DATA(res));
1812 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001813 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001814 return res;
1815}
1816
Victor Stinnere57b1c02011-09-28 22:20:48 +02001817static PyObject*
1818_PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001819{
1820 PyObject *res;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001821 Py_UCS4 max_char = 0;
Victor Stinnerb9275c12011-10-05 14:01:42 +02001822
1823 assert(size >= 0);
Antoine Pitrou7c46da72011-10-06 22:07:51 +02001824 if (size == 1 && u[0] < 256)
1825 return get_latin1_char(u[0]);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001826 max_char = ucs4lib_find_max_char(u, u + size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001827 res = PyUnicode_New(size, max_char);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001828 if (!res)
1829 return NULL;
Antoine Pitrou950468e2011-10-11 22:45:48 +02001830 if (max_char < 256)
1831 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS1, u, u + size,
1832 PyUnicode_1BYTE_DATA(res));
1833 else if (max_char < 0x10000)
1834 _PyUnicode_CONVERT_BYTES(Py_UCS4, Py_UCS2, u, u + size,
1835 PyUnicode_2BYTE_DATA(res));
1836 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001837 memcpy(PyUnicode_4BYTE_DATA(res), u, sizeof(Py_UCS4)*size);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001838 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001839 return res;
1840}
1841
1842PyObject*
1843PyUnicode_FromKindAndData(int kind, const void *buffer, Py_ssize_t size)
1844{
1845 switch(kind) {
1846 case PyUnicode_1BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001847 return _PyUnicode_FromUCS1(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001848 case PyUnicode_2BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001849 return _PyUnicode_FromUCS2(buffer, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001850 case PyUnicode_4BYTE_KIND:
Victor Stinnere57b1c02011-09-28 22:20:48 +02001851 return _PyUnicode_FromUCS4(buffer, size);
Victor Stinnerb9275c12011-10-05 14:01:42 +02001852 default:
1853 assert(0 && "invalid kind");
1854 PyErr_SetString(PyExc_SystemError, "invalid kind");
1855 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001856 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001857}
1858
Victor Stinner25a4b292011-10-06 12:31:55 +02001859/* Ensure that a string uses the most efficient storage, if it is not the
1860 case: create a new string with of the right kind. Write NULL into *p_unicode
1861 on error. */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02001862static void
Victor Stinner25a4b292011-10-06 12:31:55 +02001863unicode_adjust_maxchar(PyObject **p_unicode)
1864{
1865 PyObject *unicode, *copy;
1866 Py_UCS4 max_char;
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001867 Py_ssize_t len;
Victor Stinner25a4b292011-10-06 12:31:55 +02001868 unsigned int kind;
1869
1870 assert(p_unicode != NULL);
1871 unicode = *p_unicode;
1872 assert(PyUnicode_IS_READY(unicode));
1873 if (PyUnicode_IS_ASCII(unicode))
1874 return;
1875
1876 len = PyUnicode_GET_LENGTH(unicode);
1877 kind = PyUnicode_KIND(unicode);
1878 if (kind == PyUnicode_1BYTE_KIND) {
1879 const Py_UCS1 *u = PyUnicode_1BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001880 max_char = ucs1lib_find_max_char(u, u + len);
1881 if (max_char >= 128)
1882 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001883 }
1884 else if (kind == PyUnicode_2BYTE_KIND) {
1885 const Py_UCS2 *u = PyUnicode_2BYTE_DATA(unicode);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001886 max_char = ucs2lib_find_max_char(u, u + len);
1887 if (max_char >= 256)
1888 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001889 }
1890 else {
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001891 const Py_UCS4 *u = PyUnicode_4BYTE_DATA(unicode);
Victor Stinner25a4b292011-10-06 12:31:55 +02001892 assert(kind == PyUnicode_4BYTE_KIND);
Antoine Pitroudd4e2f02011-10-13 00:02:27 +02001893 max_char = ucs4lib_find_max_char(u, u + len);
1894 if (max_char >= 0x10000)
1895 return;
Victor Stinner25a4b292011-10-06 12:31:55 +02001896 }
Victor Stinner25a4b292011-10-06 12:31:55 +02001897 copy = PyUnicode_New(len, max_char);
1898 copy_characters(copy, 0, unicode, 0, len);
1899 Py_DECREF(unicode);
1900 *p_unicode = copy;
1901}
1902
Victor Stinner034f6cf2011-09-30 02:26:44 +02001903PyObject*
1904PyUnicode_Copy(PyObject *unicode)
1905{
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001906 Py_ssize_t size;
1907 PyObject *copy;
1908 void *data;
1909
Victor Stinner034f6cf2011-09-30 02:26:44 +02001910 if (!PyUnicode_Check(unicode)) {
1911 PyErr_BadInternalCall();
1912 return NULL;
1913 }
1914 if (PyUnicode_READY(unicode))
1915 return NULL;
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001916
1917 size = PyUnicode_GET_LENGTH(unicode);
1918 copy = PyUnicode_New(size, PyUnicode_MAX_CHAR_VALUE(unicode));
1919 if (!copy)
1920 return NULL;
1921 assert(PyUnicode_KIND(copy) == PyUnicode_KIND(unicode));
1922
1923 data = PyUnicode_DATA(unicode);
1924 switch (PyUnicode_KIND(unicode))
1925 {
1926 case PyUnicode_1BYTE_KIND:
1927 memcpy(PyUnicode_1BYTE_DATA(copy), data, size);
1928 break;
1929 case PyUnicode_2BYTE_KIND:
1930 memcpy(PyUnicode_2BYTE_DATA(copy), data, sizeof(Py_UCS2) * size);
1931 break;
1932 case PyUnicode_4BYTE_KIND:
1933 memcpy(PyUnicode_4BYTE_DATA(copy), data, sizeof(Py_UCS4) * size);
1934 break;
1935 default:
1936 assert(0);
1937 break;
1938 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02001939 assert(_PyUnicode_CheckConsistency(copy, 1));
Victor Stinnerc841e7d2011-10-01 01:34:32 +02001940 return copy;
Victor Stinner034f6cf2011-09-30 02:26:44 +02001941}
1942
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001943
Victor Stinnerbc603d12011-10-02 01:00:40 +02001944/* Widen Unicode objects to larger buffers. Don't write terminating null
1945 character. Return NULL on error. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001946
1947void*
1948_PyUnicode_AsKind(PyObject *s, unsigned int kind)
1949{
Victor Stinnerbc603d12011-10-02 01:00:40 +02001950 Py_ssize_t len;
1951 void *result;
1952 unsigned int skind;
1953
1954 if (PyUnicode_READY(s))
1955 return NULL;
1956
1957 len = PyUnicode_GET_LENGTH(s);
1958 skind = PyUnicode_KIND(s);
1959 if (skind >= kind) {
Victor Stinner01698042011-10-04 00:04:26 +02001960 PyErr_SetString(PyExc_SystemError, "invalid widening attempt");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001961 return NULL;
1962 }
1963 switch(kind) {
Victor Stinnerbc603d12011-10-02 01:00:40 +02001964 case PyUnicode_2BYTE_KIND:
1965 result = PyMem_Malloc(len * sizeof(Py_UCS2));
1966 if (!result)
1967 return PyErr_NoMemory();
1968 assert(skind == PyUnicode_1BYTE_KIND);
1969 _PyUnicode_CONVERT_BYTES(
1970 Py_UCS1, Py_UCS2,
1971 PyUnicode_1BYTE_DATA(s),
1972 PyUnicode_1BYTE_DATA(s) + len,
1973 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001974 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001975 case PyUnicode_4BYTE_KIND:
1976 result = PyMem_Malloc(len * sizeof(Py_UCS4));
1977 if (!result)
1978 return PyErr_NoMemory();
1979 if (skind == PyUnicode_2BYTE_KIND) {
1980 _PyUnicode_CONVERT_BYTES(
1981 Py_UCS2, Py_UCS4,
1982 PyUnicode_2BYTE_DATA(s),
1983 PyUnicode_2BYTE_DATA(s) + len,
1984 result);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001985 }
Victor Stinnerbc603d12011-10-02 01:00:40 +02001986 else {
1987 assert(skind == PyUnicode_1BYTE_KIND);
1988 _PyUnicode_CONVERT_BYTES(
1989 Py_UCS1, Py_UCS4,
1990 PyUnicode_1BYTE_DATA(s),
1991 PyUnicode_1BYTE_DATA(s) + len,
1992 result);
1993 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001994 return result;
Victor Stinnerbc603d12011-10-02 01:00:40 +02001995 default:
1996 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001997 }
Victor Stinner01698042011-10-04 00:04:26 +02001998 PyErr_SetString(PyExc_SystemError, "invalid kind");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001999 return NULL;
2000}
2001
2002static Py_UCS4*
2003as_ucs4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2004 int copy_null)
2005{
2006 int kind;
2007 void *data;
2008 Py_ssize_t len, targetlen;
2009 if (PyUnicode_READY(string) == -1)
2010 return NULL;
2011 kind = PyUnicode_KIND(string);
2012 data = PyUnicode_DATA(string);
2013 len = PyUnicode_GET_LENGTH(string);
2014 targetlen = len;
2015 if (copy_null)
2016 targetlen++;
2017 if (!target) {
2018 if (PY_SSIZE_T_MAX / sizeof(Py_UCS4) < targetlen) {
2019 PyErr_NoMemory();
2020 return NULL;
2021 }
2022 target = PyMem_Malloc(targetlen * sizeof(Py_UCS4));
2023 if (!target) {
2024 PyErr_NoMemory();
2025 return NULL;
2026 }
2027 }
2028 else {
2029 if (targetsize < targetlen) {
2030 PyErr_Format(PyExc_SystemError,
2031 "string is longer than the buffer");
2032 if (copy_null && 0 < targetsize)
2033 target[0] = 0;
2034 return NULL;
2035 }
2036 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002037 if (kind == PyUnicode_1BYTE_KIND) {
2038 Py_UCS1 *start = (Py_UCS1 *) data;
2039 _PyUnicode_CONVERT_BYTES(Py_UCS1, Py_UCS4, start, start + len, target);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002040 }
Antoine Pitrou950468e2011-10-11 22:45:48 +02002041 else if (kind == PyUnicode_2BYTE_KIND) {
2042 Py_UCS2 *start = (Py_UCS2 *) data;
2043 _PyUnicode_CONVERT_BYTES(Py_UCS2, Py_UCS4, start, start + len, target);
2044 }
2045 else {
2046 assert(kind == PyUnicode_4BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002047 Py_MEMCPY(target, data, len * sizeof(Py_UCS4));
Antoine Pitrou950468e2011-10-11 22:45:48 +02002048 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002049 if (copy_null)
2050 target[len] = 0;
2051 return target;
2052}
2053
2054Py_UCS4*
2055PyUnicode_AsUCS4(PyObject *string, Py_UCS4 *target, Py_ssize_t targetsize,
2056 int copy_null)
2057{
2058 if (target == NULL || targetsize < 1) {
2059 PyErr_BadInternalCall();
2060 return NULL;
2061 }
2062 return as_ucs4(string, target, targetsize, copy_null);
2063}
2064
2065Py_UCS4*
2066PyUnicode_AsUCS4Copy(PyObject *string)
2067{
2068 return as_ucs4(string, NULL, 0, 1);
2069}
2070
2071#ifdef HAVE_WCHAR_H
Mark Dickinson081dfee2009-03-18 14:47:41 +00002072
Alexander Belopolsky40018472011-02-26 01:02:56 +00002073PyObject *
2074PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002075{
Guido van Rossumd57fd912000-03-10 22:53:23 +00002076 if (w == NULL) {
Martin v. Löwis790465f2008-04-05 20:41:37 +00002077 if (size == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 return PyUnicode_New(0, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00002079 PyErr_BadInternalCall();
2080 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002081 }
2082
Martin v. Löwis790465f2008-04-05 20:41:37 +00002083 if (size == -1) {
2084 size = wcslen(w);
2085 }
2086
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002087 return PyUnicode_FromUnicode(w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002088}
2089
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002090#endif /* HAVE_WCHAR_H */
Mark Dickinson081dfee2009-03-18 14:47:41 +00002091
Walter Dörwald346737f2007-05-31 10:44:43 +00002092static void
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002093makefmt(char *fmt, int longflag, int longlongflag, int size_tflag,
2094 int zeropad, int width, int precision, char c)
Walter Dörwald346737f2007-05-31 10:44:43 +00002095{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002096 *fmt++ = '%';
2097 if (width) {
2098 if (zeropad)
2099 *fmt++ = '0';
2100 fmt += sprintf(fmt, "%d", width);
2101 }
2102 if (precision)
2103 fmt += sprintf(fmt, ".%d", precision);
2104 if (longflag)
2105 *fmt++ = 'l';
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002106 else if (longlongflag) {
2107 /* longlongflag should only ever be nonzero on machines with
2108 HAVE_LONG_LONG defined */
2109#ifdef HAVE_LONG_LONG
2110 char *f = PY_FORMAT_LONG_LONG;
2111 while (*f)
2112 *fmt++ = *f++;
2113#else
2114 /* we shouldn't ever get here */
2115 assert(0);
2116 *fmt++ = 'l';
2117#endif
2118 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002119 else if (size_tflag) {
2120 char *f = PY_FORMAT_SIZE_T;
2121 while (*f)
2122 *fmt++ = *f++;
2123 }
2124 *fmt++ = c;
2125 *fmt = '\0';
Walter Dörwald346737f2007-05-31 10:44:43 +00002126}
2127
Victor Stinner96865452011-03-01 23:44:09 +00002128/* helper for PyUnicode_FromFormatV() */
2129
2130static const char*
2131parse_format_flags(const char *f,
2132 int *p_width, int *p_precision,
2133 int *p_longflag, int *p_longlongflag, int *p_size_tflag)
2134{
2135 int width, precision, longflag, longlongflag, size_tflag;
2136
2137 /* parse the width.precision part, e.g. "%2.5s" => width=2, precision=5 */
2138 f++;
2139 width = 0;
2140 while (Py_ISDIGIT((unsigned)*f))
2141 width = (width*10) + *f++ - '0';
2142 precision = 0;
2143 if (*f == '.') {
2144 f++;
2145 while (Py_ISDIGIT((unsigned)*f))
2146 precision = (precision*10) + *f++ - '0';
2147 if (*f == '%') {
2148 /* "%.3%s" => f points to "3" */
2149 f--;
2150 }
2151 }
2152 if (*f == '\0') {
2153 /* bogus format "%.1" => go backward, f points to "1" */
2154 f--;
2155 }
2156 if (p_width != NULL)
2157 *p_width = width;
2158 if (p_precision != NULL)
2159 *p_precision = precision;
2160
2161 /* Handle %ld, %lu, %lld and %llu. */
2162 longflag = 0;
2163 longlongflag = 0;
Victor Stinnere7faec12011-03-02 00:01:53 +00002164 size_tflag = 0;
Victor Stinner96865452011-03-01 23:44:09 +00002165
2166 if (*f == 'l') {
Victor Stinner6d970f42011-03-02 00:04:25 +00002167 if (f[1] == 'd' || f[1] == 'u' || f[1] == 'i') {
Victor Stinner96865452011-03-01 23:44:09 +00002168 longflag = 1;
2169 ++f;
2170 }
2171#ifdef HAVE_LONG_LONG
2172 else if (f[1] == 'l' &&
Victor Stinner6d970f42011-03-02 00:04:25 +00002173 (f[2] == 'd' || f[2] == 'u' || f[2] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002174 longlongflag = 1;
2175 f += 2;
2176 }
2177#endif
2178 }
2179 /* handle the size_t flag. */
Victor Stinner6d970f42011-03-02 00:04:25 +00002180 else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u' || f[1] == 'i')) {
Victor Stinner96865452011-03-01 23:44:09 +00002181 size_tflag = 1;
2182 ++f;
2183 }
2184 if (p_longflag != NULL)
2185 *p_longflag = longflag;
2186 if (p_longlongflag != NULL)
2187 *p_longlongflag = longlongflag;
2188 if (p_size_tflag != NULL)
2189 *p_size_tflag = size_tflag;
2190 return f;
2191}
2192
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002193/* maximum number of characters required for output of %ld. 21 characters
2194 allows for 64-bit integers (in decimal) and an optional sign. */
2195#define MAX_LONG_CHARS 21
2196/* maximum number of characters required for output of %lld.
2197 We need at most ceil(log10(256)*SIZEOF_LONG_LONG) digits,
2198 plus 1 for the sign. 53/22 is an upper bound for log10(256). */
2199#define MAX_LONG_LONG_CHARS (2 + (SIZEOF_LONG_LONG*53-1) / 22)
2200
Walter Dörwaldd2034312007-05-18 16:29:38 +00002201PyObject *
2202PyUnicode_FromFormatV(const char *format, va_list vargs)
2203{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002204 va_list count;
2205 Py_ssize_t callcount = 0;
2206 PyObject **callresults = NULL;
2207 PyObject **callresult = NULL;
2208 Py_ssize_t n = 0;
2209 int width = 0;
2210 int precision = 0;
2211 int zeropad;
2212 const char* f;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002213 PyObject *string;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002214 /* used by sprintf */
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002215 char fmt[61]; /* should be enough for %0width.precisionlld */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002216 Py_UCS4 maxchar = 127; /* result is ASCII by default */
2217 Py_UCS4 argmaxchar;
2218 Py_ssize_t numbersize = 0;
2219 char *numberresults = NULL;
2220 char *numberresult = NULL;
2221 Py_ssize_t i;
2222 int kind;
2223 void *data;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002224
Victor Stinner4a2b7a12010-08-13 14:03:48 +00002225 Py_VA_COPY(count, vargs);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002226 /* step 1: count the number of %S/%R/%A/%s format specifications
2227 * (we call PyObject_Str()/PyObject_Repr()/PyObject_ASCII()/
2228 * PyUnicode_DecodeUTF8() for these objects once during step 3 and put the
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002229 * result in an array)
Georg Brandl7597add2011-10-05 16:36:47 +02002230 * also estimate a upper bound for all the number formats in the string,
2231 * numbers will be formatted in step 3 and be kept in a '\0'-separated
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002232 * buffer before putting everything together. */
Benjamin Peterson14339b62009-01-31 16:36:08 +00002233 for (f = format; *f; f++) {
2234 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002235 int longlongflag;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002236 /* skip width or width.precision (eg. "1.2" of "%1.2f") */
2237 f = parse_format_flags(f, &width, NULL, NULL, &longlongflag, NULL);
2238 if (*f == 's' || *f=='S' || *f=='R' || *f=='A' || *f=='V')
2239 ++callcount;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002240
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002241 else if (*f == 'd' || *f=='u' || *f=='i' || *f=='x' || *f=='p') {
Mark Dickinson6ce4a9a2009-11-16 17:00:11 +00002242#ifdef HAVE_LONG_LONG
2243 if (longlongflag) {
2244 if (width < MAX_LONG_LONG_CHARS)
2245 width = MAX_LONG_LONG_CHARS;
2246 }
2247 else
2248#endif
2249 /* MAX_LONG_CHARS is enough to hold a 64-bit integer,
2250 including sign. Decimal takes the most space. This
2251 isn't enough for octal. If a width is specified we
2252 need more (which we allocate later). */
2253 if (width < MAX_LONG_CHARS)
2254 width = MAX_LONG_CHARS;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002255
2256 /* account for the size + '\0' to separate numbers
2257 inside of the numberresults buffer */
2258 numbersize += (width + 1);
2259 }
2260 }
2261 else if ((unsigned char)*f > 127) {
2262 PyErr_Format(PyExc_ValueError,
2263 "PyUnicode_FromFormatV() expects an ASCII-encoded format "
2264 "string, got a non-ASCII byte: 0x%02x",
2265 (unsigned char)*f);
2266 return NULL;
2267 }
2268 }
2269 /* step 2: allocate memory for the results of
2270 * PyObject_Str()/PyObject_Repr()/PyUnicode_DecodeUTF8() calls */
2271 if (callcount) {
2272 callresults = PyObject_Malloc(sizeof(PyObject *) * callcount);
2273 if (!callresults) {
2274 PyErr_NoMemory();
2275 return NULL;
2276 }
2277 callresult = callresults;
2278 }
2279 /* step 2.5: allocate memory for the results of formating numbers */
2280 if (numbersize) {
2281 numberresults = PyObject_Malloc(numbersize);
2282 if (!numberresults) {
2283 PyErr_NoMemory();
2284 goto fail;
2285 }
2286 numberresult = numberresults;
2287 }
2288
2289 /* step 3: format numbers and figure out how large a buffer we need */
2290 for (f = format; *f; f++) {
2291 if (*f == '%') {
2292 const char* p;
2293 int longflag;
2294 int longlongflag;
2295 int size_tflag;
2296 int numprinted;
2297
2298 p = f;
2299 zeropad = (f[1] == '0');
2300 f = parse_format_flags(f, &width, &precision,
2301 &longflag, &longlongflag, &size_tflag);
2302 switch (*f) {
2303 case 'c':
2304 {
2305 Py_UCS4 ordinal = va_arg(count, int);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002306 maxchar = Py_MAX(maxchar, ordinal);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002307 n++;
2308 break;
2309 }
2310 case '%':
2311 n++;
2312 break;
2313 case 'i':
2314 case 'd':
2315 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2316 width, precision, *f);
2317 if (longflag)
2318 numprinted = sprintf(numberresult, fmt,
2319 va_arg(count, long));
2320#ifdef HAVE_LONG_LONG
2321 else if (longlongflag)
2322 numprinted = sprintf(numberresult, fmt,
2323 va_arg(count, PY_LONG_LONG));
2324#endif
2325 else if (size_tflag)
2326 numprinted = sprintf(numberresult, fmt,
2327 va_arg(count, Py_ssize_t));
2328 else
2329 numprinted = sprintf(numberresult, fmt,
2330 va_arg(count, int));
2331 n += numprinted;
2332 /* advance by +1 to skip over the '\0' */
2333 numberresult += (numprinted + 1);
2334 assert(*(numberresult - 1) == '\0');
2335 assert(*(numberresult - 2) != '\0');
2336 assert(numprinted >= 0);
2337 assert(numberresult <= numberresults + numbersize);
2338 break;
2339 case 'u':
2340 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
2341 width, precision, 'u');
2342 if (longflag)
2343 numprinted = sprintf(numberresult, fmt,
2344 va_arg(count, unsigned long));
2345#ifdef HAVE_LONG_LONG
2346 else if (longlongflag)
2347 numprinted = sprintf(numberresult, fmt,
2348 va_arg(count, unsigned PY_LONG_LONG));
2349#endif
2350 else if (size_tflag)
2351 numprinted = sprintf(numberresult, fmt,
2352 va_arg(count, size_t));
2353 else
2354 numprinted = sprintf(numberresult, fmt,
2355 va_arg(count, unsigned int));
2356 n += numprinted;
2357 numberresult += (numprinted + 1);
2358 assert(*(numberresult - 1) == '\0');
2359 assert(*(numberresult - 2) != '\0');
2360 assert(numprinted >= 0);
2361 assert(numberresult <= numberresults + numbersize);
2362 break;
2363 case 'x':
2364 makefmt(fmt, 0, 0, 0, zeropad, width, precision, 'x');
2365 numprinted = sprintf(numberresult, fmt, va_arg(count, int));
2366 n += numprinted;
2367 numberresult += (numprinted + 1);
2368 assert(*(numberresult - 1) == '\0');
2369 assert(*(numberresult - 2) != '\0');
2370 assert(numprinted >= 0);
2371 assert(numberresult <= numberresults + numbersize);
2372 break;
2373 case 'p':
2374 numprinted = sprintf(numberresult, "%p", va_arg(count, void*));
2375 /* %p is ill-defined: ensure leading 0x. */
2376 if (numberresult[1] == 'X')
2377 numberresult[1] = 'x';
2378 else if (numberresult[1] != 'x') {
2379 memmove(numberresult + 2, numberresult,
2380 strlen(numberresult) + 1);
2381 numberresult[0] = '0';
2382 numberresult[1] = 'x';
2383 numprinted += 2;
2384 }
2385 n += numprinted;
2386 numberresult += (numprinted + 1);
2387 assert(*(numberresult - 1) == '\0');
2388 assert(*(numberresult - 2) != '\0');
2389 assert(numprinted >= 0);
2390 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002391 break;
2392 case 's':
2393 {
2394 /* UTF-8 */
Georg Brandl780b2a62009-05-05 09:19:59 +00002395 const char *s = va_arg(count, const char*);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002396 PyObject *str = PyUnicode_DecodeUTF8(s, strlen(s), "replace");
2397 if (!str)
2398 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002399 /* since PyUnicode_DecodeUTF8 returns already flexible
2400 unicode objects, there is no need to call ready on them */
2401 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002402 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002403 n += PyUnicode_GET_LENGTH(str);
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002404 /* Remember the str and switch to the next slot */
2405 *callresult++ = str;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002406 break;
2407 }
2408 case 'U':
2409 {
2410 PyObject *obj = va_arg(count, PyObject *);
Victor Stinner910337b2011-10-03 03:20:16 +02002411 assert(obj && _PyUnicode_CHECK(obj));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002412 if (PyUnicode_READY(obj) == -1)
2413 goto fail;
2414 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002415 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002416 n += PyUnicode_GET_LENGTH(obj);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002417 break;
2418 }
2419 case 'V':
2420 {
2421 PyObject *obj = va_arg(count, PyObject *);
2422 const char *str = va_arg(count, const char *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002423 PyObject *str_obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002424 assert(obj || str);
Victor Stinner910337b2011-10-03 03:20:16 +02002425 assert(!obj || _PyUnicode_CHECK(obj));
Victor Stinner2512a8b2011-03-01 22:46:52 +00002426 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002427 if (PyUnicode_READY(obj) == -1)
2428 goto fail;
2429 argmaxchar = PyUnicode_MAX_CHAR_VALUE(obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002430 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002431 n += PyUnicode_GET_LENGTH(obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002432 *callresult++ = NULL;
2433 }
2434 else {
2435 str_obj = PyUnicode_DecodeUTF8(str, strlen(str), "replace");
2436 if (!str_obj)
2437 goto fail;
Victor Stinnere1335c72011-10-04 20:53:03 +02002438 if (PyUnicode_READY(str_obj)) {
2439 Py_DECREF(str_obj);
2440 goto fail;
2441 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002442 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002443 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002444 n += PyUnicode_GET_LENGTH(str_obj);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002445 *callresult++ = str_obj;
2446 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002447 break;
2448 }
2449 case 'S':
2450 {
2451 PyObject *obj = va_arg(count, PyObject *);
2452 PyObject *str;
2453 assert(obj);
2454 str = PyObject_Str(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002455 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002456 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002457 argmaxchar = PyUnicode_MAX_CHAR_VALUE(str);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002458 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002459 n += PyUnicode_GET_LENGTH(str);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002460 /* Remember the str and switch to the next slot */
2461 *callresult++ = str;
2462 break;
2463 }
2464 case 'R':
2465 {
2466 PyObject *obj = va_arg(count, PyObject *);
2467 PyObject *repr;
2468 assert(obj);
2469 repr = PyObject_Repr(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002470 if (!repr || PyUnicode_READY(repr) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002471 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002472 argmaxchar = PyUnicode_MAX_CHAR_VALUE(repr);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002473 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002474 n += PyUnicode_GET_LENGTH(repr);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002475 /* Remember the repr and switch to the next slot */
2476 *callresult++ = repr;
2477 break;
2478 }
2479 case 'A':
2480 {
2481 PyObject *obj = va_arg(count, PyObject *);
2482 PyObject *ascii;
2483 assert(obj);
2484 ascii = PyObject_ASCII(obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002485 if (!ascii || PyUnicode_READY(ascii) == -1)
Benjamin Peterson14339b62009-01-31 16:36:08 +00002486 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002487 argmaxchar = PyUnicode_MAX_CHAR_VALUE(ascii);
Georg Brandl4cb0de22011-09-28 21:49:49 +02002488 maxchar = Py_MAX(maxchar, argmaxchar);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002489 n += PyUnicode_GET_LENGTH(ascii);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002490 /* Remember the repr and switch to the next slot */
2491 *callresult++ = ascii;
2492 break;
2493 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002494 default:
2495 /* if we stumble upon an unknown
2496 formatting code, copy the rest of
2497 the format string to the output
2498 string. (we cannot just skip the
2499 code, since there's no way to know
2500 what's in the argument list) */
2501 n += strlen(p);
2502 goto expand;
2503 }
2504 } else
2505 n++;
2506 }
Benjamin Peterson29060642009-01-31 22:14:21 +00002507 expand:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002508 /* step 4: fill the buffer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002509 /* Since we've analyzed how much space we need,
Benjamin Peterson14339b62009-01-31 16:36:08 +00002510 we don't have to resize the string.
2511 There can be no errors beyond this point. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002512 string = PyUnicode_New(n, maxchar);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002513 if (!string)
2514 goto fail;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 kind = PyUnicode_KIND(string);
2516 data = PyUnicode_DATA(string);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002517 callresult = callresults;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002518 numberresult = numberresults;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002519
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002520 for (i = 0, f = format; *f; f++) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00002521 if (*f == '%') {
Victor Stinner96865452011-03-01 23:44:09 +00002522 const char* p;
Victor Stinner96865452011-03-01 23:44:09 +00002523
2524 p = f;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002525 f = parse_format_flags(f, NULL, NULL, NULL, NULL, NULL);
2526 /* checking for == because the last argument could be a empty
2527 string, which causes i to point to end, the assert at the end of
2528 the loop */
2529 assert(i <= PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002530
Benjamin Peterson14339b62009-01-31 16:36:08 +00002531 switch (*f) {
2532 case 'c':
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002533 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002534 const int ordinal = va_arg(vargs, int);
2535 PyUnicode_WRITE(kind, data, i++, ordinal);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002536 break;
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002537 }
Victor Stinner6d970f42011-03-02 00:04:25 +00002538 case 'i':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002539 case 'd':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002540 case 'u':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002541 case 'x':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002542 case 'p':
2543 /* unused, since we already have the result */
2544 if (*f == 'p')
2545 (void) va_arg(vargs, void *);
2546 else
2547 (void) va_arg(vargs, int);
2548 /* extract the result from numberresults and append. */
2549 for (; *numberresult; ++i, ++numberresult)
2550 PyUnicode_WRITE(kind, data, i, *numberresult);
2551 /* skip over the separating '\0' */
2552 assert(*numberresult == '\0');
2553 numberresult++;
2554 assert(numberresult <= numberresults + numbersize);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002555 break;
2556 case 's':
2557 {
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002558 /* unused, since we already have the result */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002559 Py_ssize_t size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002560 (void) va_arg(vargs, char *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002561 size = PyUnicode_GET_LENGTH(*callresult);
2562 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002563 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002564 i += size;
Walter Dörwaldc1651a02009-05-03 22:55:55 +00002565 /* We're done with the unicode()/repr() => forget it */
2566 Py_DECREF(*callresult);
2567 /* switch to next unicode()/repr() result */
2568 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002569 break;
2570 }
2571 case 'U':
2572 {
2573 PyObject *obj = va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002574 Py_ssize_t size;
2575 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
2576 size = PyUnicode_GET_LENGTH(obj);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002577 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002578 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002579 break;
2580 }
2581 case 'V':
2582 {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002583 Py_ssize_t size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002584 PyObject *obj = va_arg(vargs, PyObject *);
Victor Stinner2512a8b2011-03-01 22:46:52 +00002585 va_arg(vargs, const char *);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002586 if (obj) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002587 size = PyUnicode_GET_LENGTH(obj);
2588 assert(PyUnicode_KIND(obj) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002589 copy_characters(string, i, obj, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002590 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002591 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002592 size = PyUnicode_GET_LENGTH(*callresult);
2593 assert(PyUnicode_KIND(*callresult) <=
2594 PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002595 copy_characters(string, i, *callresult, 0, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002596 i += size;
Victor Stinner2512a8b2011-03-01 22:46:52 +00002597 Py_DECREF(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002598 }
Victor Stinner2512a8b2011-03-01 22:46:52 +00002599 ++callresult;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002600 break;
2601 }
2602 case 'S':
2603 case 'R':
Victor Stinner9a909002010-10-18 20:59:24 +00002604 case 'A':
Benjamin Peterson14339b62009-01-31 16:36:08 +00002605 {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002606 Py_ssize_t size = PyUnicode_GET_LENGTH(*callresult);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002607 /* unused, since we already have the result */
2608 (void) va_arg(vargs, PyObject *);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002609 assert(PyUnicode_KIND(*callresult) <= PyUnicode_KIND(string));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02002610 copy_characters(string, i, *callresult, 0, size);
2611 i += size;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002612 /* We're done with the unicode()/repr() => forget it */
2613 Py_DECREF(*callresult);
2614 /* switch to next unicode()/repr() result */
2615 ++callresult;
2616 break;
2617 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002618 case '%':
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002619 PyUnicode_WRITE(kind, data, i++, '%');
Benjamin Peterson14339b62009-01-31 16:36:08 +00002620 break;
2621 default:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002622 for (; *p; ++p, ++i)
2623 PyUnicode_WRITE(kind, data, i, *p);
2624 assert(i == PyUnicode_GET_LENGTH(string));
Benjamin Peterson14339b62009-01-31 16:36:08 +00002625 goto end;
2626 }
Victor Stinner1205f272010-09-11 00:54:47 +00002627 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002628 else {
2629 assert(i < PyUnicode_GET_LENGTH(string));
2630 PyUnicode_WRITE(kind, data, i++, *f);
2631 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00002632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002633 assert(i == PyUnicode_GET_LENGTH(string));
Walter Dörwaldd2034312007-05-18 16:29:38 +00002634
Benjamin Peterson29060642009-01-31 22:14:21 +00002635 end:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002636 if (callresults)
2637 PyObject_Free(callresults);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002638 if (numberresults)
2639 PyObject_Free(numberresults);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002640 assert(_PyUnicode_CheckConsistency(string, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01002641 return string;
Benjamin Peterson29060642009-01-31 22:14:21 +00002642 fail:
Benjamin Peterson14339b62009-01-31 16:36:08 +00002643 if (callresults) {
2644 PyObject **callresult2 = callresults;
2645 while (callresult2 < callresult) {
Victor Stinner2512a8b2011-03-01 22:46:52 +00002646 Py_XDECREF(*callresult2);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002647 ++callresult2;
2648 }
2649 PyObject_Free(callresults);
2650 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002651 if (numberresults)
2652 PyObject_Free(numberresults);
Benjamin Peterson14339b62009-01-31 16:36:08 +00002653 return NULL;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002654}
2655
Walter Dörwaldd2034312007-05-18 16:29:38 +00002656PyObject *
2657PyUnicode_FromFormat(const char *format, ...)
2658{
Benjamin Peterson14339b62009-01-31 16:36:08 +00002659 PyObject* ret;
2660 va_list vargs;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002661
2662#ifdef HAVE_STDARG_PROTOTYPES
Benjamin Peterson14339b62009-01-31 16:36:08 +00002663 va_start(vargs, format);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002664#else
Benjamin Peterson14339b62009-01-31 16:36:08 +00002665 va_start(vargs);
Walter Dörwaldd2034312007-05-18 16:29:38 +00002666#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +00002667 ret = PyUnicode_FromFormatV(format, vargs);
2668 va_end(vargs);
2669 return ret;
Walter Dörwaldd2034312007-05-18 16:29:38 +00002670}
2671
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002672#ifdef HAVE_WCHAR_H
2673
Victor Stinner5593d8a2010-10-02 11:11:27 +00002674/* Helper function for PyUnicode_AsWideChar() and PyUnicode_AsWideCharString():
2675 convert a Unicode object to a wide character string.
2676
Victor Stinnerd88d9832011-09-06 02:00:05 +02002677 - If w is NULL: return the number of wide characters (including the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002678 character) required to convert the unicode object. Ignore size argument.
2679
Victor Stinnerd88d9832011-09-06 02:00:05 +02002680 - Otherwise: return the number of wide characters (excluding the null
Victor Stinner5593d8a2010-10-02 11:11:27 +00002681 character) written into w. Write at most size wide characters (including
Victor Stinnerd88d9832011-09-06 02:00:05 +02002682 the null character). */
Victor Stinner5593d8a2010-10-02 11:11:27 +00002683static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002684unicode_aswidechar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002685 wchar_t *w,
2686 Py_ssize_t size)
2687{
Victor Stinner5593d8a2010-10-02 11:11:27 +00002688 Py_ssize_t res;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002689 const wchar_t *wstr;
2690
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002691 wstr = PyUnicode_AsUnicodeAndSize(unicode, &res);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002692 if (wstr == NULL)
2693 return -1;
2694
Victor Stinner5593d8a2010-10-02 11:11:27 +00002695 if (w != NULL) {
Victor Stinner5593d8a2010-10-02 11:11:27 +00002696 if (size > res)
2697 size = res + 1;
2698 else
2699 res = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002700 Py_MEMCPY(w, wstr, size * sizeof(wchar_t));
Victor Stinner5593d8a2010-10-02 11:11:27 +00002701 return res;
2702 }
2703 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002704 return res + 1;
Victor Stinner137c34c2010-09-29 10:25:54 +00002705}
2706
2707Py_ssize_t
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00002708PyUnicode_AsWideChar(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002709 wchar_t *w,
2710 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002711{
2712 if (unicode == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002713 PyErr_BadInternalCall();
2714 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002715 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002716 return unicode_aswidechar(unicode, w, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002717}
2718
Victor Stinner137c34c2010-09-29 10:25:54 +00002719wchar_t*
Victor Stinnerbeb4135b2010-10-07 01:02:42 +00002720PyUnicode_AsWideCharString(PyObject *unicode,
Victor Stinner137c34c2010-09-29 10:25:54 +00002721 Py_ssize_t *size)
2722{
2723 wchar_t* buffer;
2724 Py_ssize_t buflen;
2725
2726 if (unicode == NULL) {
2727 PyErr_BadInternalCall();
2728 return NULL;
2729 }
2730
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002731 buflen = unicode_aswidechar(unicode, NULL, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002732 if (buflen == -1)
2733 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002734 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < buflen) {
Victor Stinner137c34c2010-09-29 10:25:54 +00002735 PyErr_NoMemory();
2736 return NULL;
2737 }
2738
Victor Stinner137c34c2010-09-29 10:25:54 +00002739 buffer = PyMem_MALLOC(buflen * sizeof(wchar_t));
2740 if (buffer == NULL) {
2741 PyErr_NoMemory();
2742 return NULL;
2743 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02002744 buflen = unicode_aswidechar(unicode, buffer, buflen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002745 if (buflen == -1)
2746 return NULL;
Victor Stinner5593d8a2010-10-02 11:11:27 +00002747 if (size != NULL)
2748 *size = buflen;
Victor Stinner137c34c2010-09-29 10:25:54 +00002749 return buffer;
2750}
2751
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002752#endif /* HAVE_WCHAR_H */
Guido van Rossumd57fd912000-03-10 22:53:23 +00002753
Alexander Belopolsky40018472011-02-26 01:02:56 +00002754PyObject *
2755PyUnicode_FromOrdinal(int ordinal)
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002756{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002757 PyObject *v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002758 if (ordinal < 0 || ordinal > 0x10ffff) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002759 PyErr_SetString(PyExc_ValueError,
2760 "chr() arg not in range(0x110000)");
2761 return NULL;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002762 }
Guido van Rossum8ac004e2007-07-15 13:00:05 +00002763
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002764 if (ordinal < 256)
2765 return get_latin1_char(ordinal);
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002766
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002767 v = PyUnicode_New(1, ordinal);
2768 if (v == NULL)
2769 return NULL;
2770 PyUnicode_WRITE(PyUnicode_KIND(v), PyUnicode_DATA(v), 0, ordinal);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002771 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002772 return v;
Marc-André Lemburgcc8764c2002-08-11 12:23:04 +00002773}
2774
Alexander Belopolsky40018472011-02-26 01:02:56 +00002775PyObject *
2776PyUnicode_FromObject(register PyObject *obj)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002777{
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002778 /* XXX Perhaps we should make this API an alias of
Benjamin Peterson29060642009-01-31 22:14:21 +00002779 PyObject_Str() instead ?! */
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002780 if (PyUnicode_CheckExact(obj)) {
Victor Stinnerd3a83d52011-10-01 03:09:33 +02002781 if (PyUnicode_READY(obj))
2782 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +00002783 Py_INCREF(obj);
2784 return obj;
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002785 }
2786 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002787 /* For a Unicode subtype that's not a Unicode object,
2788 return a true Unicode object with the same data. */
Victor Stinner2219e0a2011-10-01 01:16:59 +02002789 return PyUnicode_Copy(obj);
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002790 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00002791 PyErr_Format(PyExc_TypeError,
2792 "Can't convert '%.100s' object to str implicitly",
Christian Heimes90aa7642007-12-19 02:45:37 +00002793 Py_TYPE(obj)->tp_name);
Guido van Rossum98297ee2007-11-06 21:34:58 +00002794 return NULL;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002795}
2796
Alexander Belopolsky40018472011-02-26 01:02:56 +00002797PyObject *
2798PyUnicode_FromEncodedObject(register PyObject *obj,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002799 const char *encoding,
2800 const char *errors)
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002801{
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002802 Py_buffer buffer;
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002803 PyObject *v;
Tim Petersced69f82003-09-16 20:30:58 +00002804
Guido van Rossumd57fd912000-03-10 22:53:23 +00002805 if (obj == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002806 PyErr_BadInternalCall();
2807 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002808 }
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002809
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002810 /* Decoding bytes objects is the most common case and should be fast */
2811 if (PyBytes_Check(obj)) {
2812 if (PyBytes_GET_SIZE(obj) == 0) {
2813 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002814 v = unicode_empty;
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002815 }
2816 else {
2817 v = PyUnicode_Decode(
2818 PyBytes_AS_STRING(obj), PyBytes_GET_SIZE(obj),
2819 encoding, errors);
2820 }
2821 return v;
2822 }
2823
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002824 if (PyUnicode_Check(obj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002825 PyErr_SetString(PyExc_TypeError,
2826 "decoding str is not supported");
2827 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +00002828 }
Guido van Rossumb8c65bc2001-10-19 02:01:31 +00002829
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002830 /* Retrieve a bytes buffer view through the PEP 3118 buffer interface */
2831 if (PyObject_GetBuffer(obj, &buffer, PyBUF_SIMPLE) < 0) {
2832 PyErr_Format(PyExc_TypeError,
2833 "coercing to str: need bytes, bytearray "
2834 "or buffer-like object, %.80s found",
2835 Py_TYPE(obj)->tp_name);
2836 return NULL;
Marc-André Lemburg6871f6a2001-09-20 12:53:16 +00002837 }
Tim Petersced69f82003-09-16 20:30:58 +00002838
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002839 if (buffer.len == 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00002840 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +02002841 v = unicode_empty;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002842 }
Tim Petersced69f82003-09-16 20:30:58 +00002843 else
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002844 v = PyUnicode_Decode((char*) buffer.buf, buffer.len, encoding, errors);
Marc-André Lemburgad7c98e2001-01-17 17:09:53 +00002845
Antoine Pitroub0fa8312010-09-01 15:10:12 +00002846 PyBuffer_Release(&buffer);
Marc-André Lemburg5a5c81a2000-07-07 13:46:42 +00002847 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00002848}
2849
Victor Stinner600d3be2010-06-10 12:00:55 +00002850/* Convert encoding to lower case and replace '_' with '-' in order to
Victor Stinner37296e82010-06-10 13:36:23 +00002851 catch e.g. UTF_8. Return 0 on error (encoding is longer than lower_len-1),
2852 1 on success. */
2853static int
2854normalize_encoding(const char *encoding,
2855 char *lower,
2856 size_t lower_len)
Guido van Rossumd57fd912000-03-10 22:53:23 +00002857{
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002858 const char *e;
Victor Stinner600d3be2010-06-10 12:00:55 +00002859 char *l;
2860 char *l_end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00002861
Benjamin Peterson7a6debe2011-10-15 09:25:28 -04002862 if (encoding == NULL) {
2863 strcpy(lower, "utf-8");
2864 return 1;
2865 }
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002866 e = encoding;
2867 l = lower;
Victor Stinner600d3be2010-06-10 12:00:55 +00002868 l_end = &lower[lower_len - 1];
Victor Stinner37296e82010-06-10 13:36:23 +00002869 while (*e) {
2870 if (l == l_end)
2871 return 0;
David Malcolm96960882010-11-05 17:23:41 +00002872 if (Py_ISUPPER(*e)) {
2873 *l++ = Py_TOLOWER(*e++);
Guido van Rossumdaa251c2007-10-25 23:47:33 +00002874 }
2875 else if (*e == '_') {
2876 *l++ = '-';
2877 e++;
2878 }
2879 else {
2880 *l++ = *e++;
2881 }
2882 }
2883 *l = '\0';
Victor Stinner37296e82010-06-10 13:36:23 +00002884 return 1;
Victor Stinner600d3be2010-06-10 12:00:55 +00002885}
2886
Alexander Belopolsky40018472011-02-26 01:02:56 +00002887PyObject *
2888PyUnicode_Decode(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002889 Py_ssize_t size,
2890 const char *encoding,
2891 const char *errors)
Victor Stinner600d3be2010-06-10 12:00:55 +00002892{
2893 PyObject *buffer = NULL, *unicode;
2894 Py_buffer info;
2895 char lower[11]; /* Enough for any encoding shortcut */
2896
Fred Drakee4315f52000-05-09 19:53:39 +00002897 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00002898 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002899 if ((strcmp(lower, "utf-8") == 0) ||
2900 (strcmp(lower, "utf8") == 0))
Victor Stinner37296e82010-06-10 13:36:23 +00002901 return PyUnicode_DecodeUTF8(s, size, errors);
2902 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00002903 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00002904 (strcmp(lower, "iso-8859-1") == 0))
2905 return PyUnicode_DecodeLatin1(s, size, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02002906#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00002907 else if (strcmp(lower, "mbcs") == 0)
2908 return PyUnicode_DecodeMBCS(s, size, errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00002909#endif
Victor Stinner37296e82010-06-10 13:36:23 +00002910 else if (strcmp(lower, "ascii") == 0)
2911 return PyUnicode_DecodeASCII(s, size, errors);
2912 else if (strcmp(lower, "utf-16") == 0)
2913 return PyUnicode_DecodeUTF16(s, size, errors, 0);
2914 else if (strcmp(lower, "utf-32") == 0)
2915 return PyUnicode_DecodeUTF32(s, size, errors, 0);
2916 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00002917
2918 /* Decode via the codec registry */
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002919 buffer = NULL;
Antoine Pitrouc3b39242009-01-03 16:59:18 +00002920 if (PyBuffer_FillInfo(&info, NULL, (void *)s, size, 1, PyBUF_FULL_RO) < 0)
Guido van Rossumbe801ac2007-10-08 03:32:34 +00002921 goto onError;
Antoine Pitrouee58fa42008-08-19 18:22:14 +00002922 buffer = PyMemoryView_FromBuffer(&info);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002923 if (buffer == NULL)
2924 goto onError;
2925 unicode = PyCodec_Decode(buffer, encoding, errors);
2926 if (unicode == NULL)
2927 goto onError;
2928 if (!PyUnicode_Check(unicode)) {
2929 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002930 "decoder did not return a str object (type=%.400s)",
Christian Heimes90aa7642007-12-19 02:45:37 +00002931 Py_TYPE(unicode)->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +00002932 Py_DECREF(unicode);
2933 goto onError;
2934 }
2935 Py_DECREF(buffer);
Victor Stinner17efeed2011-10-04 20:05:46 +02002936#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02002937 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002938 Py_DECREF(unicode);
2939 return NULL;
2940 }
Victor Stinner17efeed2011-10-04 20:05:46 +02002941#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002942 assert(_PyUnicode_CheckConsistency(unicode, 1));
Guido van Rossumd57fd912000-03-10 22:53:23 +00002943 return unicode;
Tim Petersced69f82003-09-16 20:30:58 +00002944
Benjamin Peterson29060642009-01-31 22:14:21 +00002945 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00002946 Py_XDECREF(buffer);
2947 return NULL;
2948}
2949
Alexander Belopolsky40018472011-02-26 01:02:56 +00002950PyObject *
2951PyUnicode_AsDecodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002952 const char *encoding,
2953 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002954{
2955 PyObject *v;
2956
2957 if (!PyUnicode_Check(unicode)) {
2958 PyErr_BadArgument();
2959 goto onError;
2960 }
2961
2962 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002963 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002964
2965 /* Decode via the codec registry */
2966 v = PyCodec_Decode(unicode, encoding, errors);
2967 if (v == NULL)
2968 goto onError;
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02002969 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002970 return v;
2971
Benjamin Peterson29060642009-01-31 22:14:21 +00002972 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00002973 return NULL;
2974}
2975
Alexander Belopolsky40018472011-02-26 01:02:56 +00002976PyObject *
2977PyUnicode_AsDecodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03002978 const char *encoding,
2979 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002980{
2981 PyObject *v;
2982
2983 if (!PyUnicode_Check(unicode)) {
2984 PyErr_BadArgument();
2985 goto onError;
2986 }
2987
2988 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00002989 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002990
2991 /* Decode via the codec registry */
2992 v = PyCodec_Decode(unicode, encoding, errors);
2993 if (v == NULL)
2994 goto onError;
2995 if (!PyUnicode_Check(v)) {
2996 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00002997 "decoder did not return a str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00002998 Py_TYPE(v)->tp_name);
2999 Py_DECREF(v);
3000 goto onError;
3001 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02003002 assert(_PyUnicode_CheckConsistency(v, 1));
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003003 return v;
3004
Benjamin Peterson29060642009-01-31 22:14:21 +00003005 onError:
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003006 return NULL;
3007}
3008
Alexander Belopolsky40018472011-02-26 01:02:56 +00003009PyObject *
3010PyUnicode_Encode(const Py_UNICODE *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003011 Py_ssize_t size,
3012 const char *encoding,
3013 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003014{
3015 PyObject *v, *unicode;
Tim Petersced69f82003-09-16 20:30:58 +00003016
Guido van Rossumd57fd912000-03-10 22:53:23 +00003017 unicode = PyUnicode_FromUnicode(s, size);
3018 if (unicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003019 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003020 v = PyUnicode_AsEncodedString(unicode, encoding, errors);
3021 Py_DECREF(unicode);
3022 return v;
3023}
3024
Alexander Belopolsky40018472011-02-26 01:02:56 +00003025PyObject *
3026PyUnicode_AsEncodedObject(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003027 const char *encoding,
3028 const char *errors)
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003029{
3030 PyObject *v;
3031
3032 if (!PyUnicode_Check(unicode)) {
3033 PyErr_BadArgument();
3034 goto onError;
3035 }
3036
3037 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003038 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003039
3040 /* Encode via the codec registry */
3041 v = PyCodec_Encode(unicode, encoding, errors);
3042 if (v == NULL)
3043 goto onError;
3044 return v;
3045
Benjamin Peterson29060642009-01-31 22:14:21 +00003046 onError:
Marc-André Lemburgd2d45982004-07-08 17:57:32 +00003047 return NULL;
3048}
3049
Victor Stinnerad158722010-10-27 00:25:46 +00003050PyObject *
3051PyUnicode_EncodeFSDefault(PyObject *unicode)
Victor Stinnerae6265f2010-05-15 16:27:27 +00003052{
Victor Stinner99b95382011-07-04 14:23:54 +02003053#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003054 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3055 PyUnicode_GET_SIZE(unicode),
3056 NULL);
3057#elif defined(__APPLE__)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003058 return _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Victor Stinnerad158722010-10-27 00:25:46 +00003059#else
Victor Stinner793b5312011-04-27 00:24:21 +02003060 PyInterpreterState *interp = PyThreadState_GET()->interp;
3061 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3062 cannot use it to encode and decode filenames before it is loaded. Load
3063 the Python codec requires to encode at least its own filename. Use the C
3064 version of the locale codec until the codec registry is initialized and
3065 the Python codec is loaded.
3066
3067 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3068 cannot only rely on it: check also interp->fscodec_initialized for
3069 subinterpreters. */
3070 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Victor Stinnerae6265f2010-05-15 16:27:27 +00003071 return PyUnicode_AsEncodedString(unicode,
3072 Py_FileSystemDefaultEncoding,
3073 "surrogateescape");
Victor Stinnerc39211f2010-09-29 16:35:47 +00003074 }
3075 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003076 /* locale encoding with surrogateescape */
3077 wchar_t *wchar;
3078 char *bytes;
3079 PyObject *bytes_obj;
Victor Stinner2f02a512010-11-08 22:43:46 +00003080 size_t error_pos;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003081
3082 wchar = PyUnicode_AsWideCharString(unicode, NULL);
3083 if (wchar == NULL)
3084 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003085 bytes = _Py_wchar2char(wchar, &error_pos);
3086 if (bytes == NULL) {
3087 if (error_pos != (size_t)-1) {
3088 char *errmsg = strerror(errno);
3089 PyObject *exc = NULL;
3090 if (errmsg == NULL)
3091 errmsg = "Py_wchar2char() failed";
3092 raise_encode_exception(&exc,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01003093 "filesystemencoding", unicode,
Victor Stinner2f02a512010-11-08 22:43:46 +00003094 error_pos, error_pos+1,
3095 errmsg);
3096 Py_XDECREF(exc);
3097 }
3098 else
3099 PyErr_NoMemory();
3100 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003101 return NULL;
Victor Stinner2f02a512010-11-08 22:43:46 +00003102 }
3103 PyMem_Free(wchar);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003104
3105 bytes_obj = PyBytes_FromString(bytes);
3106 PyMem_Free(bytes);
3107 return bytes_obj;
Victor Stinnerc39211f2010-09-29 16:35:47 +00003108 }
Victor Stinnerad158722010-10-27 00:25:46 +00003109#endif
Victor Stinnerae6265f2010-05-15 16:27:27 +00003110}
3111
Alexander Belopolsky40018472011-02-26 01:02:56 +00003112PyObject *
3113PyUnicode_AsEncodedString(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003114 const char *encoding,
3115 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003116{
3117 PyObject *v;
Victor Stinner600d3be2010-06-10 12:00:55 +00003118 char lower[11]; /* Enough for any encoding shortcut */
Tim Petersced69f82003-09-16 20:30:58 +00003119
Guido van Rossumd57fd912000-03-10 22:53:23 +00003120 if (!PyUnicode_Check(unicode)) {
3121 PyErr_BadArgument();
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003122 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00003123 }
Fred Drakee4315f52000-05-09 19:53:39 +00003124
Fred Drakee4315f52000-05-09 19:53:39 +00003125 /* Shortcuts for common default encodings */
Victor Stinner37296e82010-06-10 13:36:23 +00003126 if (normalize_encoding(encoding, lower, sizeof(lower))) {
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003127 if ((strcmp(lower, "utf-8") == 0) ||
3128 (strcmp(lower, "utf8") == 0))
Victor Stinnera5c68c32011-03-02 01:03:14 +00003129 {
Victor Stinner2f283c22011-03-02 01:21:46 +00003130 if (errors == NULL || strcmp(errors, "strict") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003131 return _PyUnicode_AsUTF8String(unicode, NULL);
Victor Stinner2f283c22011-03-02 01:21:46 +00003132 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003133 return _PyUnicode_AsUTF8String(unicode, errors);
Victor Stinnera5c68c32011-03-02 01:03:14 +00003134 }
Victor Stinner37296e82010-06-10 13:36:23 +00003135 else if ((strcmp(lower, "latin-1") == 0) ||
Alexander Belopolsky1d521462011-02-25 19:19:57 +00003136 (strcmp(lower, "latin1") == 0) ||
Victor Stinner37296e82010-06-10 13:36:23 +00003137 (strcmp(lower, "iso-8859-1") == 0))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003138 return _PyUnicode_AsLatin1String(unicode, errors);
Victor Stinner99b95382011-07-04 14:23:54 +02003139#ifdef HAVE_MBCS
Victor Stinner37296e82010-06-10 13:36:23 +00003140 else if (strcmp(lower, "mbcs") == 0)
3141 return PyUnicode_EncodeMBCS(PyUnicode_AS_UNICODE(unicode),
3142 PyUnicode_GET_SIZE(unicode),
3143 errors);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00003144#endif
Victor Stinner37296e82010-06-10 13:36:23 +00003145 else if (strcmp(lower, "ascii") == 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003146 return _PyUnicode_AsASCIIString(unicode, errors);
Victor Stinner37296e82010-06-10 13:36:23 +00003147 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003148
3149 /* Encode via the codec registry */
3150 v = PyCodec_Encode(unicode, encoding, errors);
3151 if (v == NULL)
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003152 return NULL;
3153
3154 /* The normal path */
3155 if (PyBytes_Check(v))
3156 return v;
3157
3158 /* If the codec returns a buffer, raise a warning and convert to bytes */
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003159 if (PyByteArray_Check(v)) {
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003160 int error;
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003161 PyObject *b;
Victor Stinner4a2b7a12010-08-13 14:03:48 +00003162
3163 error = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
3164 "encoder %s returned bytearray instead of bytes",
3165 encoding);
3166 if (error) {
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003167 Py_DECREF(v);
3168 return NULL;
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003169 }
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003170
Amaury Forgeot d'Arcf0481112008-09-05 20:48:47 +00003171 b = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(v), Py_SIZE(v));
3172 Py_DECREF(v);
3173 return b;
3174 }
3175
3176 PyErr_Format(PyExc_TypeError,
3177 "encoder did not return a bytes object (type=%.400s)",
3178 Py_TYPE(v)->tp_name);
3179 Py_DECREF(v);
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003180 return NULL;
3181}
3182
Alexander Belopolsky40018472011-02-26 01:02:56 +00003183PyObject *
3184PyUnicode_AsEncodedUnicode(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003185 const char *encoding,
3186 const char *errors)
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003187{
3188 PyObject *v;
3189
3190 if (!PyUnicode_Check(unicode)) {
3191 PyErr_BadArgument();
3192 goto onError;
3193 }
3194
3195 if (encoding == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003196 encoding = PyUnicode_GetDefaultEncoding();
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003197
3198 /* Encode via the codec registry */
3199 v = PyCodec_Encode(unicode, encoding, errors);
3200 if (v == NULL)
3201 goto onError;
3202 if (!PyUnicode_Check(v)) {
3203 PyErr_Format(PyExc_TypeError,
Benjamin Peterson142957c2008-07-04 19:55:29 +00003204 "encoder did not return an str object (type=%.400s)",
Marc-André Lemburgb2750b52008-06-06 12:18:17 +00003205 Py_TYPE(v)->tp_name);
3206 Py_DECREF(v);
3207 goto onError;
3208 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00003209 return v;
Tim Petersced69f82003-09-16 20:30:58 +00003210
Benjamin Peterson29060642009-01-31 22:14:21 +00003211 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003212 return NULL;
3213}
3214
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003215PyObject*
Christian Heimes5894ba72007-11-04 11:43:14 +00003216PyUnicode_DecodeFSDefault(const char *s) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003217 Py_ssize_t size = (Py_ssize_t)strlen(s);
Christian Heimes5894ba72007-11-04 11:43:14 +00003218 return PyUnicode_DecodeFSDefaultAndSize(s, size);
3219}
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003220
Christian Heimes5894ba72007-11-04 11:43:14 +00003221PyObject*
3222PyUnicode_DecodeFSDefaultAndSize(const char *s, Py_ssize_t size)
3223{
Victor Stinner99b95382011-07-04 14:23:54 +02003224#ifdef HAVE_MBCS
Victor Stinnerad158722010-10-27 00:25:46 +00003225 return PyUnicode_DecodeMBCS(s, size, NULL);
3226#elif defined(__APPLE__)
3227 return PyUnicode_DecodeUTF8(s, size, "surrogateescape");
3228#else
Victor Stinner793b5312011-04-27 00:24:21 +02003229 PyInterpreterState *interp = PyThreadState_GET()->interp;
3230 /* Bootstrap check: if the filesystem codec is implemented in Python, we
3231 cannot use it to encode and decode filenames before it is loaded. Load
3232 the Python codec requires to encode at least its own filename. Use the C
3233 version of the locale codec until the codec registry is initialized and
3234 the Python codec is loaded.
3235
3236 Py_FileSystemDefaultEncoding is shared between all interpreters, we
3237 cannot only rely on it: check also interp->fscodec_initialized for
3238 subinterpreters. */
3239 if (Py_FileSystemDefaultEncoding && interp->fscodec_initialized) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003240 return PyUnicode_Decode(s, size,
3241 Py_FileSystemDefaultEncoding,
Victor Stinnerb9a20ad2010-04-30 16:37:52 +00003242 "surrogateescape");
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003243 }
3244 else {
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003245 /* locale encoding with surrogateescape */
3246 wchar_t *wchar;
3247 PyObject *unicode;
Victor Stinner168e1172010-10-16 23:16:16 +00003248 size_t len;
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003249
3250 if (s[size] != '\0' || size != strlen(s)) {
3251 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3252 return NULL;
3253 }
3254
Victor Stinner168e1172010-10-16 23:16:16 +00003255 wchar = _Py_char2wchar(s, &len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003256 if (wchar == NULL)
Victor Stinnerd5af0a52010-11-08 23:34:29 +00003257 return PyErr_NoMemory();
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003258
Victor Stinner168e1172010-10-16 23:16:16 +00003259 unicode = PyUnicode_FromWideChar(wchar, len);
Victor Stinnerf3170cc2010-10-15 12:04:23 +00003260 PyMem_Free(wchar);
3261 return unicode;
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003262 }
Victor Stinnerad158722010-10-27 00:25:46 +00003263#endif
Guido van Rossum00bc0e02007-10-15 02:52:41 +00003264}
3265
Martin v. Löwis011e8422009-05-05 04:43:17 +00003266
3267int
3268PyUnicode_FSConverter(PyObject* arg, void* addr)
3269{
3270 PyObject *output = NULL;
3271 Py_ssize_t size;
3272 void *data;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003273 if (arg == NULL) {
3274 Py_DECREF(*(PyObject**)addr);
3275 return 1;
3276 }
Victor Stinnerdcb24032010-04-22 12:08:36 +00003277 if (PyBytes_Check(arg)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00003278 output = arg;
3279 Py_INCREF(output);
3280 }
3281 else {
3282 arg = PyUnicode_FromObject(arg);
3283 if (!arg)
3284 return 0;
Victor Stinnerae6265f2010-05-15 16:27:27 +00003285 output = PyUnicode_EncodeFSDefault(arg);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003286 Py_DECREF(arg);
3287 if (!output)
3288 return 0;
3289 if (!PyBytes_Check(output)) {
3290 Py_DECREF(output);
3291 PyErr_SetString(PyExc_TypeError, "encoder failed to return bytes");
3292 return 0;
3293 }
3294 }
Victor Stinner0ea2a462010-04-30 00:22:08 +00003295 size = PyBytes_GET_SIZE(output);
3296 data = PyBytes_AS_STRING(output);
Martin v. Löwis011e8422009-05-05 04:43:17 +00003297 if (size != strlen(data)) {
Benjamin Peterson7a6b44a2011-08-18 13:51:47 -05003298 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
Martin v. Löwis011e8422009-05-05 04:43:17 +00003299 Py_DECREF(output);
3300 return 0;
3301 }
3302 *(PyObject**)addr = output;
Martin v. Löwisc15bdef2009-05-29 14:47:46 +00003303 return Py_CLEANUP_SUPPORTED;
Martin v. Löwis011e8422009-05-05 04:43:17 +00003304}
3305
3306
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003307int
3308PyUnicode_FSDecoder(PyObject* arg, void* addr)
3309{
3310 PyObject *output = NULL;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003311 if (arg == NULL) {
3312 Py_DECREF(*(PyObject**)addr);
3313 return 1;
3314 }
3315 if (PyUnicode_Check(arg)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003316 if (PyUnicode_READY(arg))
3317 return 0;
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003318 output = arg;
3319 Py_INCREF(output);
3320 }
3321 else {
3322 arg = PyBytes_FromObject(arg);
3323 if (!arg)
3324 return 0;
3325 output = PyUnicode_DecodeFSDefaultAndSize(PyBytes_AS_STRING(arg),
3326 PyBytes_GET_SIZE(arg));
3327 Py_DECREF(arg);
3328 if (!output)
3329 return 0;
3330 if (!PyUnicode_Check(output)) {
3331 Py_DECREF(output);
3332 PyErr_SetString(PyExc_TypeError, "decoder failed to return unicode");
3333 return 0;
3334 }
3335 }
Victor Stinner065836e2011-10-27 01:56:33 +02003336 if (PyUnicode_READY(output) < 0) {
3337 Py_DECREF(output);
3338 return 0;
3339 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003340 if (findchar(PyUnicode_DATA(output), PyUnicode_KIND(output),
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02003341 PyUnicode_GET_LENGTH(output), 0, 1) >= 0) {
Victor Stinner47fcb5b2010-08-13 23:59:58 +00003342 PyErr_SetString(PyExc_TypeError, "embedded NUL character");
3343 Py_DECREF(output);
3344 return 0;
3345 }
3346 *(PyObject**)addr = output;
3347 return Py_CLEANUP_SUPPORTED;
3348}
3349
3350
Martin v. Löwis5b222132007-06-10 09:51:05 +00003351char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003352PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003353{
Christian Heimesf3863112007-11-22 07:46:41 +00003354 PyObject *bytes;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003355
Neal Norwitze0a0a6e2007-08-25 01:04:21 +00003356 if (!PyUnicode_Check(unicode)) {
3357 PyErr_BadArgument();
3358 return NULL;
3359 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003360 if (PyUnicode_READY(unicode) == -1)
Martin v. Löwis5b222132007-06-10 09:51:05 +00003361 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003362
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003363 if (PyUnicode_UTF8(unicode) == NULL) {
3364 assert(!PyUnicode_IS_COMPACT_ASCII(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003365 bytes = _PyUnicode_AsUTF8String(unicode, "strict");
3366 if (bytes == NULL)
3367 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003368 _PyUnicode_UTF8(unicode) = PyObject_MALLOC(PyBytes_GET_SIZE(bytes) + 1);
3369 if (_PyUnicode_UTF8(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003370 Py_DECREF(bytes);
3371 return NULL;
3372 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003373 _PyUnicode_UTF8_LENGTH(unicode) = PyBytes_GET_SIZE(bytes);
3374 Py_MEMCPY(_PyUnicode_UTF8(unicode),
3375 PyBytes_AS_STRING(bytes),
3376 _PyUnicode_UTF8_LENGTH(unicode) + 1);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003377 Py_DECREF(bytes);
3378 }
3379
3380 if (psize)
Victor Stinnere90fe6a2011-10-01 16:48:13 +02003381 *psize = PyUnicode_UTF8_LENGTH(unicode);
3382 return PyUnicode_UTF8(unicode);
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003383}
3384
3385char*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003386PyUnicode_AsUTF8(PyObject *unicode)
Guido van Rossum7d1df6c2007-08-29 13:53:23 +00003387{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003388 return PyUnicode_AsUTF8AndSize(unicode, NULL);
3389}
3390
3391#ifdef Py_DEBUG
Antoine Pitrou53bb5482011-10-10 23:49:24 +02003392static int unicode_as_unicode_calls = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003393#endif
3394
3395
3396Py_UNICODE *
3397PyUnicode_AsUnicodeAndSize(PyObject *unicode, Py_ssize_t *size)
3398{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003399 const unsigned char *one_byte;
3400#if SIZEOF_WCHAR_T == 4
3401 const Py_UCS2 *two_bytes;
3402#else
3403 const Py_UCS4 *four_bytes;
3404 const Py_UCS4 *ucs4_end;
3405 Py_ssize_t num_surrogates;
3406#endif
3407 wchar_t *w;
3408 wchar_t *wchar_end;
3409
3410 if (!PyUnicode_Check(unicode)) {
3411 PyErr_BadArgument();
3412 return NULL;
3413 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003414 if (_PyUnicode_WSTR(unicode) == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003415 /* Non-ASCII compact unicode object */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003416 assert(_PyUnicode_KIND(unicode) != 0);
3417 assert(PyUnicode_IS_READY(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003418
3419#ifdef Py_DEBUG
3420 ++unicode_as_unicode_calls;
3421#endif
3422
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003423 if (PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003424#if SIZEOF_WCHAR_T == 2
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003425 four_bytes = PyUnicode_4BYTE_DATA(unicode);
3426 ucs4_end = four_bytes + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003427 num_surrogates = 0;
3428
3429 for (; four_bytes < ucs4_end; ++four_bytes) {
3430 if (*four_bytes > 0xFFFF)
3431 ++num_surrogates;
3432 }
3433
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003434 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(
3435 sizeof(wchar_t) * (_PyUnicode_LENGTH(unicode) + 1 + num_surrogates));
3436 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003437 PyErr_NoMemory();
3438 return NULL;
3439 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003440 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode) + num_surrogates;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003441
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003442 w = _PyUnicode_WSTR(unicode);
3443 wchar_end = w + _PyUnicode_WSTR_LENGTH(unicode);
3444 four_bytes = PyUnicode_4BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003445 for (; four_bytes < ucs4_end; ++four_bytes, ++w) {
3446 if (*four_bytes > 0xFFFF) {
3447 /* encode surrogate pair in this case */
3448 *w++ = 0xD800 | ((*four_bytes - 0x10000) >> 10);
3449 *w = 0xDC00 | ((*four_bytes - 0x10000) & 0x3FF);
3450 }
3451 else
3452 *w = *four_bytes;
3453
3454 if (w > wchar_end) {
3455 assert(0 && "Miscalculated string end");
3456 }
3457 }
3458 *w = 0;
3459#else
3460 /* sizeof(wchar_t) == 4 */
3461 Py_FatalError("Impossible unicode object state, wstr and str "
3462 "should share memory already.");
3463 return NULL;
3464#endif
3465 }
3466 else {
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003467 _PyUnicode_WSTR(unicode) = (wchar_t *) PyObject_MALLOC(sizeof(wchar_t) *
3468 (_PyUnicode_LENGTH(unicode) + 1));
3469 if (!_PyUnicode_WSTR(unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003470 PyErr_NoMemory();
3471 return NULL;
3472 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003473 if (!PyUnicode_IS_COMPACT_ASCII(unicode))
3474 _PyUnicode_WSTR_LENGTH(unicode) = _PyUnicode_LENGTH(unicode);
3475 w = _PyUnicode_WSTR(unicode);
3476 wchar_end = w + _PyUnicode_LENGTH(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003477
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003478 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND) {
3479 one_byte = PyUnicode_1BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003480 for (; w < wchar_end; ++one_byte, ++w)
3481 *w = *one_byte;
3482 /* null-terminate the wstr */
3483 *w = 0;
3484 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003485 else if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003486#if SIZEOF_WCHAR_T == 4
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003487 two_bytes = PyUnicode_2BYTE_DATA(unicode);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003488 for (; w < wchar_end; ++two_bytes, ++w)
3489 *w = *two_bytes;
3490 /* null-terminate the wstr */
3491 *w = 0;
3492#else
3493 /* sizeof(wchar_t) == 2 */
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003494 PyObject_FREE(_PyUnicode_WSTR(unicode));
3495 _PyUnicode_WSTR(unicode) = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003496 Py_FatalError("Impossible unicode object state, wstr "
3497 "and str should share memory already.");
3498 return NULL;
3499#endif
3500 }
3501 else {
3502 assert(0 && "This should never happen.");
3503 }
3504 }
3505 }
3506 if (size != NULL)
Victor Stinner9db1a8b2011-10-23 20:04:37 +02003507 *size = PyUnicode_WSTR_LENGTH(unicode);
3508 return _PyUnicode_WSTR(unicode);
Martin v. Löwis5b222132007-06-10 09:51:05 +00003509}
3510
Alexander Belopolsky40018472011-02-26 01:02:56 +00003511Py_UNICODE *
3512PyUnicode_AsUnicode(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003513{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003514 return PyUnicode_AsUnicodeAndSize(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00003515}
3516
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003517
Alexander Belopolsky40018472011-02-26 01:02:56 +00003518Py_ssize_t
3519PyUnicode_GetSize(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00003520{
3521 if (!PyUnicode_Check(unicode)) {
3522 PyErr_BadArgument();
3523 goto onError;
3524 }
3525 return PyUnicode_GET_SIZE(unicode);
3526
Benjamin Peterson29060642009-01-31 22:14:21 +00003527 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00003528 return -1;
3529}
3530
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003531Py_ssize_t
3532PyUnicode_GetLength(PyObject *unicode)
3533{
Victor Stinner5a706cf2011-10-02 00:36:53 +02003534 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003535 PyErr_BadArgument();
3536 return -1;
3537 }
3538
3539 return PyUnicode_GET_LENGTH(unicode);
3540}
3541
3542Py_UCS4
3543PyUnicode_ReadChar(PyObject *unicode, Py_ssize_t index)
3544{
Victor Stinner2fe5ced2011-10-02 00:25:40 +02003545 if (!PyUnicode_Check(unicode) || PyUnicode_READY(unicode) == -1) {
3546 PyErr_BadArgument();
3547 return (Py_UCS4)-1;
3548 }
3549 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3550 PyErr_SetString(PyExc_IndexError, "string index out of range");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003551 return (Py_UCS4)-1;
3552 }
3553 return PyUnicode_READ_CHAR(unicode, index);
3554}
3555
3556int
3557PyUnicode_WriteChar(PyObject *unicode, Py_ssize_t index, Py_UCS4 ch)
3558{
3559 if (!PyUnicode_Check(unicode) || !PyUnicode_IS_COMPACT(unicode)) {
Victor Stinnercd9950f2011-10-02 00:34:53 +02003560 PyErr_BadArgument();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003561 return -1;
3562 }
Victor Stinnercd9950f2011-10-02 00:34:53 +02003563 if (index < 0 || index >= _PyUnicode_LENGTH(unicode)) {
3564 PyErr_SetString(PyExc_IndexError, "string index out of range");
3565 return -1;
3566 }
3567 if (_PyUnicode_Dirty(unicode))
3568 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02003569 PyUnicode_WRITE(PyUnicode_KIND(unicode), PyUnicode_DATA(unicode),
3570 index, ch);
3571 return 0;
3572}
3573
Alexander Belopolsky40018472011-02-26 01:02:56 +00003574const char *
3575PyUnicode_GetDefaultEncoding(void)
Fred Drakee4315f52000-05-09 19:53:39 +00003576{
Victor Stinner42cb4622010-09-01 19:39:01 +00003577 return "utf-8";
Fred Drakee4315f52000-05-09 19:53:39 +00003578}
3579
Victor Stinner554f3f02010-06-16 23:33:54 +00003580/* create or adjust a UnicodeDecodeError */
3581static void
3582make_decode_exception(PyObject **exceptionObject,
3583 const char *encoding,
3584 const char *input, Py_ssize_t length,
3585 Py_ssize_t startpos, Py_ssize_t endpos,
3586 const char *reason)
3587{
3588 if (*exceptionObject == NULL) {
3589 *exceptionObject = PyUnicodeDecodeError_Create(
3590 encoding, input, length, startpos, endpos, reason);
3591 }
3592 else {
3593 if (PyUnicodeDecodeError_SetStart(*exceptionObject, startpos))
3594 goto onError;
3595 if (PyUnicodeDecodeError_SetEnd(*exceptionObject, endpos))
3596 goto onError;
3597 if (PyUnicodeDecodeError_SetReason(*exceptionObject, reason))
3598 goto onError;
3599 }
3600 return;
3601
3602onError:
3603 Py_DECREF(*exceptionObject);
3604 *exceptionObject = NULL;
3605}
3606
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003607/* error handling callback helper:
3608 build arguments, call the callback and check the arguments,
Fred Drakedb390c12005-10-28 14:39:47 +00003609 if no exception occurred, copy the replacement to the output
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003610 and adjust various state variables.
3611 return 0 on success, -1 on error
3612*/
3613
Alexander Belopolsky40018472011-02-26 01:02:56 +00003614static int
3615unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003616 const char *encoding, const char *reason,
3617 const char **input, const char **inend, Py_ssize_t *startinpos,
3618 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003619 PyObject **output, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003620{
Benjamin Peterson142957c2008-07-04 19:55:29 +00003621 static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003622
3623 PyObject *restuple = NULL;
3624 PyObject *repunicode = NULL;
Victor Stinner596a6c42011-11-09 00:02:18 +01003625 Py_ssize_t outsize;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003626 Py_ssize_t insize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003627 Py_ssize_t requiredsize;
3628 Py_ssize_t newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003629 PyObject *inputobj = NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003630 int res = -1;
3631
Victor Stinner596a6c42011-11-09 00:02:18 +01003632 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND)
3633 outsize = PyUnicode_GET_LENGTH(*output);
3634 else
3635 outsize = _PyUnicode_WSTR_LENGTH(*output);
3636
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003637 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003638 *errorHandler = PyCodec_LookupError(errors);
3639 if (*errorHandler == NULL)
3640 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003641 }
3642
Victor Stinner554f3f02010-06-16 23:33:54 +00003643 make_decode_exception(exceptionObject,
3644 encoding,
3645 *input, *inend - *input,
3646 *startinpos, *endinpos,
3647 reason);
3648 if (*exceptionObject == NULL)
3649 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003650
3651 restuple = PyObject_CallFunctionObjArgs(*errorHandler, *exceptionObject, NULL);
3652 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00003653 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003654 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00003655 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00003656 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003657 }
3658 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type, &repunicode, &newpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003659 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003660 if (PyUnicode_READY(repunicode) < 0)
3661 goto onError;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003662
3663 /* Copy back the bytes variables, which might have been modified by the
3664 callback */
3665 inputobj = PyUnicodeDecodeError_GetObject(*exceptionObject);
3666 if (!inputobj)
3667 goto onError;
Christian Heimes72b710a2008-05-26 13:28:38 +00003668 if (!PyBytes_Check(inputobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003669 PyErr_Format(PyExc_TypeError, "exception attribute object must be bytes");
Walter Dörwalde78178e2007-07-30 13:31:40 +00003670 }
Christian Heimes72b710a2008-05-26 13:28:38 +00003671 *input = PyBytes_AS_STRING(inputobj);
3672 insize = PyBytes_GET_SIZE(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003673 *inend = *input + insize;
Walter Dörwald36f938f2007-08-10 10:11:43 +00003674 /* we can DECREF safely, as the exception has another reference,
3675 so the object won't go away. */
3676 Py_DECREF(inputobj);
Walter Dörwalde78178e2007-07-30 13:31:40 +00003677
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003678 if (newpos<0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003679 newpos = insize+newpos;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003680 if (newpos<0 || newpos>insize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00003681 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", newpos);
3682 goto onError;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00003683 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003684
Victor Stinner596a6c42011-11-09 00:02:18 +01003685 if (_PyUnicode_KIND(*output) != PyUnicode_WCHAR_KIND) {
3686 /* need more space? (at least enough for what we
3687 have+the replacement+the rest of the string (starting
3688 at the new input position), so we won't have to check space
3689 when there are no errors in the rest of the string) */
3690 Py_ssize_t replen = PyUnicode_GET_LENGTH(repunicode);
3691 requiredsize = *outpos + replen + insize-newpos;
3692 if (requiredsize > outsize) {
3693 if (requiredsize<2*outsize)
3694 requiredsize = 2*outsize;
3695 if (unicode_resize(output, requiredsize) < 0)
3696 goto onError;
3697 }
3698 if (unicode_widen(output, PyUnicode_MAX_CHAR_VALUE(repunicode)) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00003699 goto onError;
Victor Stinner596a6c42011-11-09 00:02:18 +01003700 copy_characters(*output, *outpos, repunicode, 0, replen);
3701 *outpos += replen;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003702 }
Victor Stinner596a6c42011-11-09 00:02:18 +01003703 else {
3704 wchar_t *repwstr;
3705 Py_ssize_t repwlen;
3706 repwstr = PyUnicode_AsUnicodeAndSize(repunicode, &repwlen);
3707 if (repwstr == NULL)
3708 goto onError;
3709 /* need more space? (at least enough for what we
3710 have+the replacement+the rest of the string (starting
3711 at the new input position), so we won't have to check space
3712 when there are no errors in the rest of the string) */
3713 requiredsize = *outpos + repwlen + insize-newpos;
3714 if (requiredsize > outsize) {
3715 if (requiredsize < 2*outsize)
3716 requiredsize = 2*outsize;
3717 if (unicode_resize(output, requiredsize) < 0)
3718 goto onError;
3719 }
3720 wcsncpy(_PyUnicode_WSTR(*output) + *outpos, repwstr, repwlen);
3721 *outpos += repwlen;
3722 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003723 *endinpos = newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003724 *inptr = *input + newpos;
Walter Dörwalde78178e2007-07-30 13:31:40 +00003725
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003726 /* we made it! */
3727 res = 0;
3728
Benjamin Peterson29060642009-01-31 22:14:21 +00003729 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003730 Py_XDECREF(restuple);
3731 return res;
3732}
3733
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003734/* --- UTF-7 Codec -------------------------------------------------------- */
3735
Antoine Pitrou244651a2009-05-04 18:56:13 +00003736/* See RFC2152 for details. We encode conservatively and decode liberally. */
3737
3738/* Three simple macros defining base-64. */
3739
3740/* Is c a base-64 character? */
3741
3742#define IS_BASE64(c) \
3743 (((c) >= 'A' && (c) <= 'Z') || \
3744 ((c) >= 'a' && (c) <= 'z') || \
3745 ((c) >= '0' && (c) <= '9') || \
3746 (c) == '+' || (c) == '/')
3747
3748/* given that c is a base-64 character, what is its base-64 value? */
3749
3750#define FROM_BASE64(c) \
3751 (((c) >= 'A' && (c) <= 'Z') ? (c) - 'A' : \
3752 ((c) >= 'a' && (c) <= 'z') ? (c) - 'a' + 26 : \
3753 ((c) >= '0' && (c) <= '9') ? (c) - '0' + 52 : \
3754 (c) == '+' ? 62 : 63)
3755
3756/* What is the base-64 character of the bottom 6 bits of n? */
3757
3758#define TO_BASE64(n) \
3759 ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(n) & 0x3f])
3760
3761/* DECODE_DIRECT: this byte encountered in a UTF-7 string should be
3762 * decoded as itself. We are permissive on decoding; the only ASCII
3763 * byte not decoding to itself is the + which begins a base64
3764 * string. */
3765
3766#define DECODE_DIRECT(c) \
3767 ((c) <= 127 && (c) != '+')
3768
3769/* The UTF-7 encoder treats ASCII characters differently according to
3770 * whether they are Set D, Set O, Whitespace, or special (i.e. none of
3771 * the above). See RFC2152. This array identifies these different
3772 * sets:
3773 * 0 : "Set D"
3774 * alphanumeric and '(),-./:?
3775 * 1 : "Set O"
3776 * !"#$%&*;<=>@[]^_`{|}
3777 * 2 : "whitespace"
3778 * ht nl cr sp
3779 * 3 : special (must be base64 encoded)
3780 * everything else (i.e. +\~ and non-printing codes 0-8 11-12 14-31 127)
3781 */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003782
Tim Petersced69f82003-09-16 20:30:58 +00003783static
Antoine Pitrou244651a2009-05-04 18:56:13 +00003784char utf7_category[128] = {
3785/* nul soh stx etx eot enq ack bel bs ht nl vt np cr so si */
3786 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
3787/* dle dc1 dc2 dc3 dc4 nak syn etb can em sub esc fs gs rs us */
3788 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
3789/* sp ! " # $ % & ' ( ) * + , - . / */
3790 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 0,
3791/* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
3792 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
3793/* @ A B C D E F G H I J K L M N O */
3794 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3795/* P Q R S T U V W X Y Z [ \ ] ^ _ */
3796 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
3797/* ` a b c d e f g h i j k l m n o */
3798 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3799/* p q r s t u v w x y z { | } ~ del */
3800 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3,
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003801};
3802
Antoine Pitrou244651a2009-05-04 18:56:13 +00003803/* ENCODE_DIRECT: this character should be encoded as itself. The
3804 * answer depends on whether we are encoding set O as itself, and also
3805 * on whether we are encoding whitespace as itself. RFC2152 makes it
3806 * clear that the answers to these questions vary between
3807 * applications, so this code needs to be flexible. */
Marc-André Lemburge115ec82005-10-19 22:33:31 +00003808
Antoine Pitrou244651a2009-05-04 18:56:13 +00003809#define ENCODE_DIRECT(c, directO, directWS) \
3810 ((c) < 128 && (c) > 0 && \
3811 ((utf7_category[(c)] == 0) || \
3812 (directWS && (utf7_category[(c)] == 2)) || \
3813 (directO && (utf7_category[(c)] == 1))))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003814
Alexander Belopolsky40018472011-02-26 01:02:56 +00003815PyObject *
3816PyUnicode_DecodeUTF7(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003817 Py_ssize_t size,
3818 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003819{
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003820 return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
3821}
3822
Antoine Pitrou244651a2009-05-04 18:56:13 +00003823/* The decoder. The only state we preserve is our read position,
3824 * i.e. how many characters we have consumed. So if we end in the
3825 * middle of a shift sequence we have to back off the read position
3826 * and the output to the beginning of the sequence, otherwise we lose
3827 * all the shift state (seen bits, number of bits seen, high
3828 * surrogate). */
3829
Alexander Belopolsky40018472011-02-26 01:02:56 +00003830PyObject *
3831PyUnicode_DecodeUTF7Stateful(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03003832 Py_ssize_t size,
3833 const char *errors,
3834 Py_ssize_t *consumed)
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003835{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003836 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00003837 Py_ssize_t startinpos;
3838 Py_ssize_t endinpos;
3839 Py_ssize_t outpos;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003840 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003841 PyObject *unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003842 const char *errmsg = "";
3843 int inShift = 0;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003844 Py_ssize_t shiftOutStart;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003845 unsigned int base64bits = 0;
3846 unsigned long base64buffer = 0;
3847 Py_UNICODE surrogate = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003848 PyObject *errorHandler = NULL;
3849 PyObject *exc = NULL;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003850
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003851 /* Start off assuming it's all ASCII. Widen later as necessary. */
3852 unicode = PyUnicode_New(size, 127);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003853 if (!unicode)
3854 return NULL;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003855 if (size == 0) {
3856 if (consumed)
3857 *consumed = 0;
Victor Stinner7931d9a2011-11-04 00:22:48 +01003858 return unicode;
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003859 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003860
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003861 shiftOutStart = outpos = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003862 e = s + size;
3863
3864 while (s < e) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003865 Py_UCS4 ch;
Benjamin Peterson29060642009-01-31 22:14:21 +00003866 restart:
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00003867 ch = (unsigned char) *s;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003868
Antoine Pitrou244651a2009-05-04 18:56:13 +00003869 if (inShift) { /* in a base-64 section */
3870 if (IS_BASE64(ch)) { /* consume a base-64 character */
3871 base64buffer = (base64buffer << 6) | FROM_BASE64(ch);
3872 base64bits += 6;
3873 s++;
3874 if (base64bits >= 16) {
3875 /* we have enough bits for a UTF-16 value */
3876 Py_UNICODE outCh = (Py_UNICODE)
3877 (base64buffer >> (base64bits-16));
3878 base64bits -= 16;
3879 base64buffer &= (1 << base64bits) - 1; /* clear high bits */
3880 if (surrogate) {
3881 /* expecting a second surrogate */
3882 if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003883 Py_UCS4 ch2 = (((surrogate & 0x3FF)<<10)
3884 | (outCh & 0x3FF)) + 0x10000;
3885 if (unicode_putchar(&unicode, &outpos, ch2) < 0)
3886 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003887 surrogate = 0;
3888 }
3889 else {
3890 surrogate = 0;
3891 errmsg = "second surrogate missing";
3892 goto utf7Error;
3893 }
3894 }
3895 else if (outCh >= 0xD800 && outCh <= 0xDBFF) {
3896 /* first surrogate */
3897 surrogate = outCh;
3898 }
3899 else if (outCh >= 0xDC00 && outCh <= 0xDFFF) {
3900 errmsg = "unexpected second surrogate";
3901 goto utf7Error;
3902 }
3903 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003904 if (unicode_putchar(&unicode, &outpos, outCh) < 0)
3905 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003906 }
3907 }
3908 }
3909 else { /* now leaving a base-64 section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003910 inShift = 0;
3911 s++;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003912 if (surrogate) {
3913 errmsg = "second surrogate missing at end of shift sequence";
Tim Petersced69f82003-09-16 20:30:58 +00003914 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003915 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003916 if (base64bits > 0) { /* left-over bits */
3917 if (base64bits >= 6) {
3918 /* We've seen at least one base-64 character */
3919 errmsg = "partial character in shift sequence";
3920 goto utf7Error;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003921 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003922 else {
3923 /* Some bits remain; they should be zero */
3924 if (base64buffer != 0) {
3925 errmsg = "non-zero padding bits in shift sequence";
3926 goto utf7Error;
3927 }
3928 }
3929 }
3930 if (ch != '-') {
3931 /* '-' is absorbed; other terminating
3932 characters are preserved */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003933 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3934 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003935 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003936 }
3937 }
3938 else if ( ch == '+' ) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003939 startinpos = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003940 s++; /* consume '+' */
3941 if (s < e && *s == '-') { /* '+-' encodes '+' */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003942 s++;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003943 if (unicode_putchar(&unicode, &outpos, '+') < 0)
3944 goto onError;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003945 }
3946 else { /* begin base64-encoded section */
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003947 inShift = 1;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003948 shiftOutStart = outpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003949 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003950 }
3951 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003952 else if (DECODE_DIRECT(ch)) { /* character decodes as itself */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003953 if (unicode_putchar(&unicode, &outpos, ch) < 0)
3954 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003955 s++;
3956 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003957 else {
3958 startinpos = s-starts;
3959 s++;
3960 errmsg = "unexpected special character";
3961 goto utf7Error;
3962 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003963 continue;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003964utf7Error:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00003965 endinpos = s-starts;
3966 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00003967 errors, &errorHandler,
3968 "utf7", errmsg,
3969 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003970 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00003971 goto onError;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003972 }
3973
Antoine Pitrou244651a2009-05-04 18:56:13 +00003974 /* end of string */
3975
3976 if (inShift && !consumed) { /* in shift sequence, no more to follow */
3977 /* if we're in an inconsistent state, that's an error */
3978 if (surrogate ||
3979 (base64bits >= 6) ||
3980 (base64bits > 0 && base64buffer != 0)) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003981 endinpos = size;
3982 if (unicode_decode_call_errorhandler(
3983 errors, &errorHandler,
3984 "utf7", "unterminated shift sequence",
3985 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003986 &unicode, &outpos))
Antoine Pitrou244651a2009-05-04 18:56:13 +00003987 goto onError;
3988 if (s < e)
3989 goto restart;
3990 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00003991 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00003992
3993 /* return state */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003994 if (consumed) {
Antoine Pitrou244651a2009-05-04 18:56:13 +00003995 if (inShift) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01003996 outpos = shiftOutStart; /* back off output */
Christian Heimes5d14c2b2007-11-20 23:38:09 +00003997 *consumed = startinpos;
Antoine Pitrou244651a2009-05-04 18:56:13 +00003998 }
3999 else {
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004000 *consumed = s-starts;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004001 }
Christian Heimes5d14c2b2007-11-20 23:38:09 +00004002 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004003
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004004 if (unicode_resize(&unicode, outpos) < 0)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004005 goto onError;
4006
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004007 Py_XDECREF(errorHandler);
4008 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02004009#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02004010 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004011 Py_DECREF(unicode);
4012 return NULL;
4013 }
Victor Stinner17efeed2011-10-04 20:05:46 +02004014#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004015 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004016 return unicode;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004017
Benjamin Peterson29060642009-01-31 22:14:21 +00004018 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004019 Py_XDECREF(errorHandler);
4020 Py_XDECREF(exc);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004021 Py_DECREF(unicode);
4022 return NULL;
4023}
4024
4025
Alexander Belopolsky40018472011-02-26 01:02:56 +00004026PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004027_PyUnicode_EncodeUTF7(PyObject *str,
4028 int base64SetO,
4029 int base64WhiteSpace,
4030 const char *errors)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004031{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004032 int kind;
4033 void *data;
4034 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004035 PyObject *v;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004036 Py_ssize_t allocated;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004037 int inShift = 0;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004038 Py_ssize_t i;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004039 unsigned int base64bits = 0;
4040 unsigned long base64buffer = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004041 char * out;
4042 char * start;
4043
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004044 if (PyUnicode_READY(str) < 0)
4045 return NULL;
4046 kind = PyUnicode_KIND(str);
4047 data = PyUnicode_DATA(str);
4048 len = PyUnicode_GET_LENGTH(str);
4049
4050 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00004051 return PyBytes_FromStringAndSize(NULL, 0);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004052
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004053 /* It might be possible to tighten this worst case */
4054 allocated = 8 * len;
4055 if (allocated / 8 != len)
Neal Norwitz3ce5d922008-08-24 07:08:55 +00004056 return PyErr_NoMemory();
4057
Antoine Pitrou244651a2009-05-04 18:56:13 +00004058 v = PyBytes_FromStringAndSize(NULL, allocated);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004059 if (v == NULL)
4060 return NULL;
4061
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004062 start = out = PyBytes_AS_STRING(v);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004063 for (i = 0; i < len; ++i) {
4064 Py_UNICODE ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004065
Antoine Pitrou244651a2009-05-04 18:56:13 +00004066 if (inShift) {
4067 if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4068 /* shifting out */
4069 if (base64bits) { /* output remaining bits */
4070 *out++ = TO_BASE64(base64buffer << (6-base64bits));
4071 base64buffer = 0;
4072 base64bits = 0;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004073 }
4074 inShift = 0;
Antoine Pitrou244651a2009-05-04 18:56:13 +00004075 /* Characters not in the BASE64 set implicitly unshift the sequence
4076 so no '-' is required, except if the character is itself a '-' */
4077 if (IS_BASE64(ch) || ch == '-') {
4078 *out++ = '-';
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004079 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004080 *out++ = (char) ch;
4081 }
4082 else {
4083 goto encode_char;
Tim Petersced69f82003-09-16 20:30:58 +00004084 }
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004085 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004086 else { /* not in a shift sequence */
4087 if (ch == '+') {
4088 *out++ = '+';
4089 *out++ = '-';
4090 }
4091 else if (ENCODE_DIRECT(ch, !base64SetO, !base64WhiteSpace)) {
4092 *out++ = (char) ch;
4093 }
4094 else {
4095 *out++ = '+';
4096 inShift = 1;
4097 goto encode_char;
4098 }
4099 }
4100 continue;
4101encode_char:
4102#ifdef Py_UNICODE_WIDE
4103 if (ch >= 0x10000) {
4104 /* code first surrogate */
4105 base64bits += 16;
4106 base64buffer = (base64buffer << 16) | 0xd800 | ((ch-0x10000) >> 10);
4107 while (base64bits >= 6) {
4108 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4109 base64bits -= 6;
4110 }
4111 /* prepare second surrogate */
4112 ch = 0xDC00 | ((ch-0x10000) & 0x3FF);
4113 }
4114#endif
4115 base64bits += 16;
4116 base64buffer = (base64buffer << 16) | ch;
4117 while (base64bits >= 6) {
4118 *out++ = TO_BASE64(base64buffer >> (base64bits-6));
4119 base64bits -= 6;
4120 }
Hye-Shik Chang1bc09b72004-01-03 19:35:43 +00004121 }
Antoine Pitrou244651a2009-05-04 18:56:13 +00004122 if (base64bits)
4123 *out++= TO_BASE64(base64buffer << (6-base64bits) );
4124 if (inShift)
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004125 *out++ = '-';
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00004126 if (_PyBytes_Resize(&v, out - start) < 0)
4127 return NULL;
4128 return v;
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004129}
Martin v. Löwis1db7c132011-11-10 18:24:32 +01004130PyObject *
4131PyUnicode_EncodeUTF7(const Py_UNICODE *s,
4132 Py_ssize_t size,
4133 int base64SetO,
4134 int base64WhiteSpace,
4135 const char *errors)
4136{
4137 PyObject *result;
4138 PyObject *tmp = PyUnicode_FromUnicode(s, size);
4139 if (tmp == NULL)
4140 return NULL;
4141 result = _PyUnicode_EncodeUTF7(tmp, base64SetO,
4142 base64WhiteSpace, errors);
4143 Py_DECREF(tmp);
4144 return result;
4145}
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004146
Antoine Pitrou244651a2009-05-04 18:56:13 +00004147#undef IS_BASE64
4148#undef FROM_BASE64
4149#undef TO_BASE64
4150#undef DECODE_DIRECT
4151#undef ENCODE_DIRECT
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00004152
Guido van Rossumd57fd912000-03-10 22:53:23 +00004153/* --- UTF-8 Codec -------------------------------------------------------- */
4154
Tim Petersced69f82003-09-16 20:30:58 +00004155static
Guido van Rossumd57fd912000-03-10 22:53:23 +00004156char utf8_code_length[256] = {
Ezio Melotti57221d02010-07-01 07:32:02 +00004157 /* Map UTF-8 encoded prefix byte to sequence length. Zero means
4158 illegal prefix. See RFC 3629 for details */
4159 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 00-0F */
4160 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Victor Stinner4a2b7a12010-08-13 14:03:48 +00004161 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Guido van Rossumd57fd912000-03-10 22:53:23 +00004162 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4163 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4164 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4165 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
Ezio Melotti57221d02010-07-01 07:32:02 +00004166 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 70-7F */
4167 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 +00004168 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
4169 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Ezio Melotti57221d02010-07-01 07:32:02 +00004170 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* B0-BF */
4171 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* C0-C1 + C2-CF */
4172 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, /* D0-DF */
4173 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, /* E0-EF */
4174 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 +00004175};
4176
Alexander Belopolsky40018472011-02-26 01:02:56 +00004177PyObject *
4178PyUnicode_DecodeUTF8(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03004179 Py_ssize_t size,
4180 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004181{
Walter Dörwald69652032004-09-07 20:24:22 +00004182 return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
4183}
4184
Antoine Pitrouab868312009-01-10 15:40:25 +00004185/* Mask to check or force alignment of a pointer to C 'long' boundaries */
4186#define LONG_PTR_MASK (size_t) (SIZEOF_LONG - 1)
4187
4188/* Mask to quickly check whether a C 'long' contains a
4189 non-ASCII, UTF8-encoded char. */
4190#if (SIZEOF_LONG == 8)
4191# define ASCII_CHAR_MASK 0x8080808080808080L
4192#elif (SIZEOF_LONG == 4)
4193# define ASCII_CHAR_MASK 0x80808080L
4194#else
4195# error C 'long' size should be either 4 or 8!
4196#endif
4197
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004198/* Scans a UTF-8 string and returns the maximum character to be expected,
4199 the size of the decoded unicode string and if any major errors were
4200 encountered.
4201
4202 This function does check basic UTF-8 sanity, it does however NOT CHECK
4203 if the string contains surrogates, and if all continuation bytes are
4204 within the correct ranges, these checks are performed in
4205 PyUnicode_DecodeUTF8Stateful.
4206
4207 If it sets has_errors to 1, it means the value of unicode_size and max_char
4208 will be bogus and you should not rely on useful information in them.
4209 */
4210static Py_UCS4
4211utf8_max_char_size_and_has_errors(const char *s, Py_ssize_t string_size,
4212 Py_ssize_t *unicode_size, Py_ssize_t* consumed,
4213 int *has_errors)
4214{
4215 Py_ssize_t n;
4216 Py_ssize_t char_count = 0;
4217 Py_UCS4 max_char = 127, new_max;
4218 Py_UCS4 upper_bound;
4219 const unsigned char *p = (const unsigned char *)s;
4220 const unsigned char *end = p + string_size;
4221 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
4222 int err = 0;
4223
4224 for (; p < end && !err; ++p, ++char_count) {
4225 /* Only check value if it's not a ASCII char... */
4226 if (*p < 0x80) {
4227 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
4228 an explanation. */
4229 if (!((size_t) p & LONG_PTR_MASK)) {
4230 /* Help register allocation */
4231 register const unsigned char *_p = p;
4232 while (_p < aligned_end) {
4233 unsigned long value = *(unsigned long *) _p;
4234 if (value & ASCII_CHAR_MASK)
4235 break;
4236 _p += SIZEOF_LONG;
4237 char_count += SIZEOF_LONG;
4238 }
4239 p = _p;
4240 if (p == end)
4241 break;
4242 }
4243 }
4244 if (*p >= 0x80) {
4245 n = utf8_code_length[*p];
4246 new_max = max_char;
4247 switch (n) {
4248 /* invalid start byte */
4249 case 0:
4250 err = 1;
4251 break;
4252 case 2:
4253 /* Code points between 0x00FF and 0x07FF inclusive.
4254 Approximate the upper bound of the code point,
4255 if this flips over 255 we can be sure it will be more
4256 than 255 and the string will need 2 bytes per code coint,
4257 if it stays under or equal to 255, we can be sure 1 byte
4258 is enough.
4259 ((*p & 0b00011111) << 6) | 0b00111111 */
4260 upper_bound = ((*p & 0x1F) << 6) | 0x3F;
4261 if (max_char < upper_bound)
4262 new_max = upper_bound;
4263 /* Ensure we track at least that we left ASCII space. */
4264 if (new_max < 128)
4265 new_max = 128;
4266 break;
4267 case 3:
4268 /* Between 0x0FFF and 0xFFFF inclusive, so values are
4269 always > 255 and <= 65535 and will always need 2 bytes. */
4270 if (max_char < 65535)
4271 new_max = 65535;
4272 break;
4273 case 4:
4274 /* Code point will be above 0xFFFF for sure in this case. */
4275 new_max = 65537;
4276 break;
4277 /* Internal error, this should be caught by the first if */
4278 case 1:
4279 default:
4280 assert(0 && "Impossible case in utf8_max_char_and_size");
4281 err = 1;
4282 }
4283 /* Instead of number of overall bytes for this code point,
Georg Brandl7597add2011-10-05 16:36:47 +02004284 n contains the number of following bytes: */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004285 --n;
4286 /* Check if the follow up chars are all valid continuation bytes */
4287 if (n >= 1) {
4288 const unsigned char *cont;
4289 if ((p + n) >= end) {
4290 if (consumed == 0)
4291 /* incomplete data, non-incremental decoding */
4292 err = 1;
4293 break;
4294 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004295 for (cont = p + 1; cont <= (p + n); ++cont) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004296 if ((*cont & 0xc0) != 0x80) {
4297 err = 1;
4298 break;
4299 }
4300 }
4301 p += n;
4302 }
4303 else
4304 err = 1;
4305 max_char = new_max;
4306 }
4307 }
4308
4309 if (unicode_size)
4310 *unicode_size = char_count;
4311 if (has_errors)
4312 *has_errors = err;
4313 return max_char;
4314}
4315
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004316/* Similar to PyUnicode_WRITE but may attempt to widen and resize the string
4317 in case of errors. Implicit parameters: unicode, kind, data, has_errors,
4318 onError. Potential resizing overallocates, so the result needs to shrink
4319 at the end.
4320*/
4321#define WRITE_MAYBE_FAIL(index, value) \
4322 do { \
4323 if (has_errors) { \
4324 Py_ssize_t pos = index; \
4325 if (pos > PyUnicode_GET_LENGTH(unicode) && \
4326 unicode_resize(&unicode, pos + pos/8) < 0) \
4327 goto onError; \
4328 if (unicode_putchar(&unicode, &pos, value) < 0) \
4329 goto onError; \
4330 } \
4331 else \
4332 PyUnicode_WRITE(kind, data, index, value); \
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004333 } while (0)
4334
Alexander Belopolsky40018472011-02-26 01:02:56 +00004335PyObject *
4336PyUnicode_DecodeUTF8Stateful(const char *s,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004337 Py_ssize_t size,
4338 const char *errors,
4339 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00004340{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004341 const char *starts = s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004342 int n;
Ezio Melotti57221d02010-07-01 07:32:02 +00004343 int k;
Martin v. Löwis18e16552006-02-15 17:27:45 +00004344 Py_ssize_t startinpos;
4345 Py_ssize_t endinpos;
Antoine Pitrouab868312009-01-10 15:40:25 +00004346 const char *e, *aligned_end;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004347 PyObject *unicode;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004348 const char *errmsg = "";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004349 PyObject *errorHandler = NULL;
4350 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004351 Py_UCS4 maxchar = 0;
4352 Py_ssize_t unicode_size;
4353 Py_ssize_t i;
4354 int kind;
4355 void *data;
4356 int has_errors;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004357
Walter Dörwald69652032004-09-07 20:24:22 +00004358 if (size == 0) {
4359 if (consumed)
4360 *consumed = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004361 return (PyObject *)PyUnicode_New(0, 0);
Walter Dörwald69652032004-09-07 20:24:22 +00004362 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004363 maxchar = utf8_max_char_size_and_has_errors(s, size, &unicode_size,
4364 consumed, &has_errors);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004365 if (has_errors)
Victor Stinner62aa4d02011-11-09 00:03:45 +01004366 /* maxchar and size computation might be incorrect;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004367 code below widens and resizes as necessary. */
4368 unicode = PyUnicode_New(size, 127);
4369 else
Victor Stinner7931d9a2011-11-04 00:22:48 +01004370 unicode = PyUnicode_New(unicode_size, maxchar);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004371 if (!unicode)
4372 return NULL;
4373 /* When the string is ASCII only, just use memcpy and return.
4374 unicode_size may be != size if there is an incomplete UTF-8
4375 sequence at the end of the ASCII block. */
4376 if (!has_errors && maxchar < 128 && size == unicode_size) {
4377 Py_MEMCPY(PyUnicode_1BYTE_DATA(unicode), s, unicode_size);
4378 return unicode;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004379 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004380 kind = PyUnicode_KIND(unicode);
4381 data = PyUnicode_DATA(unicode);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004382 /* Unpack UTF-8 encoded data */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004383 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004384 e = s + size;
Antoine Pitrouab868312009-01-10 15:40:25 +00004385 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004386
4387 while (s < e) {
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004388 Py_UCS4 ch = (unsigned char)*s;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004389
4390 if (ch < 0x80) {
Antoine Pitrouab868312009-01-10 15:40:25 +00004391 /* Fast path for runs of ASCII characters. Given that common UTF-8
4392 input will consist of an overwhelming majority of ASCII
4393 characters, we try to optimize for this case by checking
4394 as many characters as a C 'long' can contain.
4395 First, check if we can do an aligned read, as most CPUs have
4396 a penalty for unaligned reads.
4397 */
4398 if (!((size_t) s & LONG_PTR_MASK)) {
4399 /* Help register allocation */
4400 register const char *_s = s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004401 register Py_ssize_t _i = i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004402 while (_s < aligned_end) {
4403 /* Read a whole long at a time (either 4 or 8 bytes),
4404 and do a fast unrolled copy if it only contains ASCII
4405 characters. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004406 unsigned long value = *(unsigned long *) _s;
4407 if (value & ASCII_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00004408 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004409 WRITE_MAYBE_FAIL(_i+0, _s[0]);
4410 WRITE_MAYBE_FAIL(_i+1, _s[1]);
4411 WRITE_MAYBE_FAIL(_i+2, _s[2]);
4412 WRITE_MAYBE_FAIL(_i+3, _s[3]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004413#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004414 WRITE_MAYBE_FAIL(_i+4, _s[4]);
4415 WRITE_MAYBE_FAIL(_i+5, _s[5]);
4416 WRITE_MAYBE_FAIL(_i+6, _s[6]);
4417 WRITE_MAYBE_FAIL(_i+7, _s[7]);
Antoine Pitrouab868312009-01-10 15:40:25 +00004418#endif
4419 _s += SIZEOF_LONG;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004420 _i += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00004421 }
4422 s = _s;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004423 i = _i;
Antoine Pitrouab868312009-01-10 15:40:25 +00004424 if (s == e)
4425 break;
4426 ch = (unsigned char)*s;
4427 }
4428 }
4429
4430 if (ch < 0x80) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004431 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004432 s++;
4433 continue;
4434 }
4435
4436 n = utf8_code_length[ch];
4437
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004438 if (s + n > e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004439 if (consumed)
4440 break;
4441 else {
4442 errmsg = "unexpected end of data";
4443 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004444 endinpos = startinpos+1;
4445 for (k=1; (k < size-startinpos) && ((s[k]&0xC0) == 0x80); k++)
4446 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004447 goto utf8Error;
4448 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00004449 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004450
4451 switch (n) {
4452
4453 case 0:
Ezio Melotti57221d02010-07-01 07:32:02 +00004454 errmsg = "invalid start byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004455 startinpos = s-starts;
4456 endinpos = startinpos+1;
4457 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004458
4459 case 1:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004460 errmsg = "internal error";
Benjamin Peterson29060642009-01-31 22:14:21 +00004461 startinpos = s-starts;
4462 endinpos = startinpos+1;
4463 goto utf8Error;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004464
4465 case 2:
Marc-André Lemburg9542f482000-07-17 18:23:13 +00004466 if ((s[1] & 0xc0) != 0x80) {
Ezio Melotti57221d02010-07-01 07:32:02 +00004467 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004468 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004469 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00004470 goto utf8Error;
4471 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004472 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004473 assert ((ch > 0x007F) && (ch <= 0x07FF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004474 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004475 break;
4476
4477 case 3:
Ezio Melotti9bf2b3a2010-07-03 04:52:19 +00004478 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4479 will result in surrogates in range d800-dfff. Surrogates are
4480 not valid UTF-8 so they are rejected.
4481 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4482 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
Tim Petersced69f82003-09-16 20:30:58 +00004483 if ((s[1] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004484 (s[2] & 0xc0) != 0x80 ||
4485 ((unsigned char)s[0] == 0xE0 &&
4486 (unsigned char)s[1] < 0xA0) ||
4487 ((unsigned char)s[0] == 0xED &&
4488 (unsigned char)s[1] > 0x9F)) {
4489 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004490 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004491 endinpos = startinpos + 1;
4492
4493 /* if s[1] first two bits are 1 and 0, then the invalid
4494 continuation byte is s[2], so increment endinpos by 1,
4495 if not, s[1] is invalid and endinpos doesn't need to
4496 be incremented. */
4497 if ((s[1] & 0xC0) == 0x80)
4498 endinpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +00004499 goto utf8Error;
4500 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004501 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
Ezio Melotti57221d02010-07-01 07:32:02 +00004502 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004503 WRITE_MAYBE_FAIL(i++, ch);
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004504 break;
4505
4506 case 4:
4507 if ((s[1] & 0xc0) != 0x80 ||
4508 (s[2] & 0xc0) != 0x80 ||
Ezio Melotti57221d02010-07-01 07:32:02 +00004509 (s[3] & 0xc0) != 0x80 ||
4510 ((unsigned char)s[0] == 0xF0 &&
4511 (unsigned char)s[1] < 0x90) ||
4512 ((unsigned char)s[0] == 0xF4 &&
4513 (unsigned char)s[1] > 0x8F)) {
4514 errmsg = "invalid continuation byte";
Benjamin Peterson29060642009-01-31 22:14:21 +00004515 startinpos = s-starts;
Ezio Melotti57221d02010-07-01 07:32:02 +00004516 endinpos = startinpos + 1;
4517 if ((s[1] & 0xC0) == 0x80) {
4518 endinpos++;
4519 if ((s[2] & 0xC0) == 0x80)
4520 endinpos++;
4521 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004522 goto utf8Error;
4523 }
Marc-André Lemburge12896e2000-07-07 17:51:08 +00004524 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
Ezio Melotti57221d02010-07-01 07:32:02 +00004525 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4526 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4527
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004528 WRITE_MAYBE_FAIL(i++, ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004529 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004530 }
4531 s += n;
Benjamin Peterson29060642009-01-31 22:14:21 +00004532 continue;
Tim Petersced69f82003-09-16 20:30:58 +00004533
Benjamin Peterson29060642009-01-31 22:14:21 +00004534 utf8Error:
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004535 if (!has_errors) {
4536 PyObject *tmp;
4537 Py_ssize_t k;
4538 /* We encountered some error that wasn't detected in the original scan,
4539 e.g. an encoded surrogate character. The original maxchar computation may
4540 have been incorrect, so redo it now. */
4541 for (k = 0, maxchar = 0; k < i; k++)
4542 maxchar = Py_MAX(maxchar, PyUnicode_READ(kind, data, k));
4543 tmp = PyUnicode_New(PyUnicode_GET_LENGTH(unicode), maxchar);
4544 if (tmp == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004545 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004546 PyUnicode_CopyCharacters(tmp, 0, unicode, 0, i);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004547 Py_DECREF(unicode);
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004548 unicode = tmp;
4549 has_errors = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004550 }
Benjamin Peterson29060642009-01-31 22:14:21 +00004551 if (unicode_decode_call_errorhandler(
4552 errors, &errorHandler,
4553 "utf8", errmsg,
4554 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004555 &unicode, &i))
Benjamin Peterson29060642009-01-31 22:14:21 +00004556 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004557 /* Update data because unicode_decode_call_errorhandler might have
4558 re-created or resized the unicode object. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004559 data = PyUnicode_DATA(unicode);
4560 kind = PyUnicode_KIND(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00004561 aligned_end = (const char *) ((size_t) e & ~LONG_PTR_MASK);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004562 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004563 /* Ensure the unicode_size calculation above was correct: */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004564 assert(has_errors || i == unicode_size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004565
Walter Dörwald69652032004-09-07 20:24:22 +00004566 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00004567 *consumed = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004568
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004569 /* Adjust length and ready string when it contained errors and
4570 is of the old resizable kind. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004571 if (has_errors) {
Victor Stinner7931d9a2011-11-04 00:22:48 +01004572 if (PyUnicode_Resize(&unicode, i) < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004573 goto onError;
4574 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004575
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004576 Py_XDECREF(errorHandler);
4577 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02004578 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01004579 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00004580
Benjamin Peterson29060642009-01-31 22:14:21 +00004581 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00004582 Py_XDECREF(errorHandler);
4583 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004584 Py_DECREF(unicode);
4585 return NULL;
4586}
4587
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004588#undef WRITE_MAYBE_FAIL
Antoine Pitrouab868312009-01-10 15:40:25 +00004589
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004590#ifdef __APPLE__
4591
4592/* Simplified UTF-8 decoder using surrogateescape error handler,
4593 used to decode the command line arguments on Mac OS X. */
4594
4595wchar_t*
4596_Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size)
4597{
4598 int n;
4599 const char *e;
4600 wchar_t *unicode, *p;
4601
4602 /* Note: size will always be longer than the resulting Unicode
4603 character count */
4604 if (PY_SSIZE_T_MAX / sizeof(wchar_t) < (size + 1)) {
4605 PyErr_NoMemory();
4606 return NULL;
4607 }
4608 unicode = PyMem_Malloc((size + 1) * sizeof(wchar_t));
4609 if (!unicode)
4610 return NULL;
4611
4612 /* Unpack UTF-8 encoded data */
4613 p = unicode;
4614 e = s + size;
4615 while (s < e) {
4616 Py_UCS4 ch = (unsigned char)*s;
4617
4618 if (ch < 0x80) {
4619 *p++ = (wchar_t)ch;
4620 s++;
4621 continue;
4622 }
4623
4624 n = utf8_code_length[ch];
4625 if (s + n > e) {
4626 goto surrogateescape;
4627 }
4628
4629 switch (n) {
4630 case 0:
4631 case 1:
4632 goto surrogateescape;
4633
4634 case 2:
4635 if ((s[1] & 0xc0) != 0x80)
4636 goto surrogateescape;
4637 ch = ((s[0] & 0x1f) << 6) + (s[1] & 0x3f);
4638 assert ((ch > 0x007F) && (ch <= 0x07FF));
4639 *p++ = (wchar_t)ch;
4640 break;
4641
4642 case 3:
4643 /* Decoding UTF-8 sequences in range \xed\xa0\x80-\xed\xbf\xbf
4644 will result in surrogates in range d800-dfff. Surrogates are
4645 not valid UTF-8 so they are rejected.
4646 See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
4647 (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt */
4648 if ((s[1] & 0xc0) != 0x80 ||
4649 (s[2] & 0xc0) != 0x80 ||
4650 ((unsigned char)s[0] == 0xE0 &&
4651 (unsigned char)s[1] < 0xA0) ||
4652 ((unsigned char)s[0] == 0xED &&
4653 (unsigned char)s[1] > 0x9F)) {
4654
4655 goto surrogateescape;
4656 }
4657 ch = ((s[0] & 0x0f) << 12) + ((s[1] & 0x3f) << 6) + (s[2] & 0x3f);
4658 assert ((ch > 0x07FF) && (ch <= 0xFFFF));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004659 *p++ = (wchar_t)ch;
Victor Stinnerf933e1a2010-10-20 22:58:25 +00004660 break;
4661
4662 case 4:
4663 if ((s[1] & 0xc0) != 0x80 ||
4664 (s[2] & 0xc0) != 0x80 ||
4665 (s[3] & 0xc0) != 0x80 ||
4666 ((unsigned char)s[0] == 0xF0 &&
4667 (unsigned char)s[1] < 0x90) ||
4668 ((unsigned char)s[0] == 0xF4 &&
4669 (unsigned char)s[1] > 0x8F)) {
4670 goto surrogateescape;
4671 }
4672 ch = ((s[0] & 0x7) << 18) + ((s[1] & 0x3f) << 12) +
4673 ((s[2] & 0x3f) << 6) + (s[3] & 0x3f);
4674 assert ((ch > 0xFFFF) && (ch <= 0x10ffff));
4675
4676#if SIZEOF_WCHAR_T == 4
4677 *p++ = (wchar_t)ch;
4678#else
4679 /* compute and append the two surrogates: */
4680
4681 /* translate from 10000..10FFFF to 0..FFFF */
4682 ch -= 0x10000;
4683
4684 /* high surrogate = top 10 bits added to D800 */
4685 *p++ = (wchar_t)(0xD800 + (ch >> 10));
4686
4687 /* low surrogate = bottom 10 bits added to DC00 */
4688 *p++ = (wchar_t)(0xDC00 + (ch & 0x03FF));
4689#endif
4690 break;
4691 }
4692 s += n;
4693 continue;
4694
4695 surrogateescape:
4696 *p++ = 0xDC00 + ch;
4697 s++;
4698 }
4699 *p = L'\0';
4700 return unicode;
4701}
4702
4703#endif /* __APPLE__ */
Antoine Pitrouab868312009-01-10 15:40:25 +00004704
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004705/* Primary internal function which creates utf8 encoded bytes objects.
4706
4707 Allocation strategy: if the string is short, convert into a stack buffer
Tim Peters602f7402002-04-27 18:03:26 +00004708 and allocate exactly as much space needed at the end. Else allocate the
4709 maximum possible needed (4 result bytes per Unicode character), and return
4710 the excess memory at the end.
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004711*/
Tim Peters7e3d9612002-04-21 03:26:37 +00004712PyObject *
Victor Stinner7931d9a2011-11-04 00:22:48 +01004713_PyUnicode_AsUTF8String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004714{
Tim Peters602f7402002-04-27 18:03:26 +00004715#define MAX_SHORT_UNICHARS 300 /* largest size we'll do on the stack */
Tim Peters0eca65c2002-04-21 17:28:06 +00004716
Guido van Rossum98297ee2007-11-06 21:34:58 +00004717 Py_ssize_t i; /* index into s of next input byte */
4718 PyObject *result; /* result string object */
4719 char *p; /* next free byte in output buffer */
4720 Py_ssize_t nallocated; /* number of result bytes allocated */
4721 Py_ssize_t nneeded; /* number of result bytes needed */
Tim Peters602f7402002-04-27 18:03:26 +00004722 char stackbuf[MAX_SHORT_UNICHARS * 4];
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004723 PyObject *errorHandler = NULL;
4724 PyObject *exc = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004725 int kind;
4726 void *data;
4727 Py_ssize_t size;
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00004728
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004729 if (!PyUnicode_Check(unicode)) {
4730 PyErr_BadArgument();
4731 return NULL;
4732 }
4733
4734 if (PyUnicode_READY(unicode) == -1)
4735 return NULL;
4736
Victor Stinnere90fe6a2011-10-01 16:48:13 +02004737 if (PyUnicode_UTF8(unicode))
4738 return PyBytes_FromStringAndSize(PyUnicode_UTF8(unicode),
4739 PyUnicode_UTF8_LENGTH(unicode));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004740
4741 kind = PyUnicode_KIND(unicode);
4742 data = PyUnicode_DATA(unicode);
4743 size = PyUnicode_GET_LENGTH(unicode);
4744
Tim Peters602f7402002-04-27 18:03:26 +00004745 assert(size >= 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004746
Tim Peters602f7402002-04-27 18:03:26 +00004747 if (size <= MAX_SHORT_UNICHARS) {
4748 /* Write into the stack buffer; nallocated can't overflow.
4749 * At the end, we'll allocate exactly as much heap space as it
4750 * turns out we need.
4751 */
4752 nallocated = Py_SAFE_DOWNCAST(sizeof(stackbuf), size_t, int);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004753 result = NULL; /* will allocate after we're done */
Tim Peters602f7402002-04-27 18:03:26 +00004754 p = stackbuf;
4755 }
4756 else {
4757 /* Overallocate on the heap, and give the excess back at the end. */
4758 nallocated = size * 4;
4759 if (nallocated / 4 != size) /* overflow! */
4760 return PyErr_NoMemory();
Christian Heimes72b710a2008-05-26 13:28:38 +00004761 result = PyBytes_FromStringAndSize(NULL, nallocated);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004762 if (result == NULL)
Tim Peters602f7402002-04-27 18:03:26 +00004763 return NULL;
Christian Heimes72b710a2008-05-26 13:28:38 +00004764 p = PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004765 }
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004766
Tim Peters602f7402002-04-27 18:03:26 +00004767 for (i = 0; i < size;) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004768 Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004769
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004770 if (ch < 0x80)
Tim Peters602f7402002-04-27 18:03:26 +00004771 /* Encode ASCII */
Guido van Rossumd57fd912000-03-10 22:53:23 +00004772 *p++ = (char) ch;
Marc-André Lemburg3688a882002-02-06 18:09:02 +00004773
Guido van Rossumd57fd912000-03-10 22:53:23 +00004774 else if (ch < 0x0800) {
Tim Peters602f7402002-04-27 18:03:26 +00004775 /* Encode Latin-1 */
Marc-André Lemburgdc724d62002-02-06 18:20:19 +00004776 *p++ = (char)(0xc0 | (ch >> 6));
4777 *p++ = (char)(0x80 | (ch & 0x3f));
Victor Stinner31be90b2010-04-22 19:38:16 +00004778 } else if (0xD800 <= ch && ch <= 0xDFFF) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004779 Py_ssize_t newpos;
4780 PyObject *rep;
4781 Py_ssize_t repsize, k, startpos;
4782 startpos = i-1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004783 rep = unicode_encode_call_errorhandler(
4784 errors, &errorHandler, "utf-8", "surrogates not allowed",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004785 unicode, &exc, startpos, startpos+1, &newpos);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004786 if (!rep)
4787 goto error;
Victor Stinner31be90b2010-04-22 19:38:16 +00004788
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004789 if (PyBytes_Check(rep))
4790 repsize = PyBytes_GET_SIZE(rep);
4791 else
4792 repsize = PyUnicode_GET_SIZE(rep);
4793
4794 if (repsize > 4) {
4795 Py_ssize_t offset;
4796
4797 if (result == NULL)
4798 offset = p - stackbuf;
Victor Stinner31be90b2010-04-22 19:38:16 +00004799 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004800 offset = p - PyBytes_AS_STRING(result);
Victor Stinner31be90b2010-04-22 19:38:16 +00004801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004802 if (nallocated > PY_SSIZE_T_MAX - repsize + 4) {
4803 /* integer overflow */
4804 PyErr_NoMemory();
4805 goto error;
4806 }
4807 nallocated += repsize - 4;
4808 if (result != NULL) {
4809 if (_PyBytes_Resize(&result, nallocated) < 0)
4810 goto error;
4811 } else {
4812 result = PyBytes_FromStringAndSize(NULL, nallocated);
Victor Stinner31be90b2010-04-22 19:38:16 +00004813 if (result == NULL)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004814 goto error;
4815 Py_MEMCPY(PyBytes_AS_STRING(result), stackbuf, offset);
4816 }
4817 p = PyBytes_AS_STRING(result) + offset;
4818 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004819
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004820 if (PyBytes_Check(rep)) {
4821 char *prep = PyBytes_AS_STRING(rep);
4822 for(k = repsize; k > 0; k--)
4823 *p++ = *prep++;
4824 } else /* rep is unicode */ {
4825 const Py_UNICODE *prep = PyUnicode_AS_UNICODE(rep);
4826 Py_UNICODE c;
4827
4828 for(k=0; k<repsize; k++) {
4829 c = prep[k];
4830 if (0x80 <= c) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01004831 raise_encode_exception(&exc, "utf-8",
Victor Stinner7931d9a2011-11-04 00:22:48 +01004832 unicode,
Martin v. Löwis9e816682011-11-02 12:45:42 +01004833 i-1, i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004834 "surrogates not allowed");
Victor Stinner31be90b2010-04-22 19:38:16 +00004835 goto error;
4836 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004837 *p++ = (char)prep[k];
Victor Stinner31be90b2010-04-22 19:38:16 +00004838 }
Victor Stinner31be90b2010-04-22 19:38:16 +00004839 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004840 Py_DECREF(rep);
Victor Stinner31be90b2010-04-22 19:38:16 +00004841 } else if (ch < 0x10000) {
4842 *p++ = (char)(0xe0 | (ch >> 12));
4843 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4844 *p++ = (char)(0x80 | (ch & 0x3f));
4845 } else /* ch >= 0x10000 */ {
Tim Peters602f7402002-04-27 18:03:26 +00004846 /* Encode UCS4 Unicode ordinals */
4847 *p++ = (char)(0xf0 | (ch >> 18));
4848 *p++ = (char)(0x80 | ((ch >> 12) & 0x3f));
4849 *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
4850 *p++ = (char)(0x80 | (ch & 0x3f));
4851 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00004852 }
Tim Peters0eca65c2002-04-21 17:28:06 +00004853
Guido van Rossum98297ee2007-11-06 21:34:58 +00004854 if (result == NULL) {
Tim Peters602f7402002-04-27 18:03:26 +00004855 /* This was stack allocated. */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004856 nneeded = p - stackbuf;
Tim Peters602f7402002-04-27 18:03:26 +00004857 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004858 result = PyBytes_FromStringAndSize(stackbuf, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004859 }
4860 else {
Christian Heimesf3863112007-11-22 07:46:41 +00004861 /* Cut back to size actually needed. */
Christian Heimes72b710a2008-05-26 13:28:38 +00004862 nneeded = p - PyBytes_AS_STRING(result);
Tim Peters602f7402002-04-27 18:03:26 +00004863 assert(nneeded <= nallocated);
Christian Heimes72b710a2008-05-26 13:28:38 +00004864 _PyBytes_Resize(&result, nneeded);
Tim Peters602f7402002-04-27 18:03:26 +00004865 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004866
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004867 Py_XDECREF(errorHandler);
4868 Py_XDECREF(exc);
Guido van Rossum98297ee2007-11-06 21:34:58 +00004869 return result;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00004870 error:
4871 Py_XDECREF(errorHandler);
4872 Py_XDECREF(exc);
4873 Py_XDECREF(result);
4874 return NULL;
Martin v. Löwis2a7ff352002-04-21 09:59:45 +00004875
Tim Peters602f7402002-04-27 18:03:26 +00004876#undef MAX_SHORT_UNICHARS
Guido van Rossumd57fd912000-03-10 22:53:23 +00004877}
4878
Alexander Belopolsky40018472011-02-26 01:02:56 +00004879PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004880PyUnicode_EncodeUTF8(const Py_UNICODE *s,
4881 Py_ssize_t size,
4882 const char *errors)
4883{
4884 PyObject *v, *unicode;
4885
4886 unicode = PyUnicode_FromUnicode(s, size);
4887 if (unicode == NULL)
4888 return NULL;
4889 v = _PyUnicode_AsUTF8String(unicode, errors);
4890 Py_DECREF(unicode);
4891 return v;
4892}
4893
4894PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00004895PyUnicode_AsUTF8String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00004896{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02004897 return _PyUnicode_AsUTF8String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00004898}
4899
Walter Dörwald41980ca2007-08-16 21:55:45 +00004900/* --- UTF-32 Codec ------------------------------------------------------- */
4901
4902PyObject *
4903PyUnicode_DecodeUTF32(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004904 Py_ssize_t size,
4905 const char *errors,
4906 int *byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004907{
4908 return PyUnicode_DecodeUTF32Stateful(s, size, errors, byteorder, NULL);
4909}
4910
4911PyObject *
4912PyUnicode_DecodeUTF32Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00004913 Py_ssize_t size,
4914 const char *errors,
4915 int *byteorder,
4916 Py_ssize_t *consumed)
Walter Dörwald41980ca2007-08-16 21:55:45 +00004917{
4918 const char *starts = s;
4919 Py_ssize_t startinpos;
4920 Py_ssize_t endinpos;
4921 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01004922 PyObject *unicode;
Mark Dickinson7db923c2010-06-12 09:10:14 +00004923 const unsigned char *q, *e;
Walter Dörwald41980ca2007-08-16 21:55:45 +00004924 int bo = 0; /* assume native ordering by default */
4925 const char *errmsg = "";
Walter Dörwald41980ca2007-08-16 21:55:45 +00004926 /* Offsets from q for retrieving bytes in the right order. */
4927#ifdef BYTEORDER_IS_LITTLE_ENDIAN
4928 int iorder[] = {0, 1, 2, 3};
4929#else
4930 int iorder[] = {3, 2, 1, 0};
4931#endif
4932 PyObject *errorHandler = NULL;
4933 PyObject *exc = NULL;
Victor Stinner313a1202010-06-11 23:56:51 +00004934
Walter Dörwald41980ca2007-08-16 21:55:45 +00004935 q = (unsigned char *)s;
4936 e = q + size;
4937
4938 if (byteorder)
4939 bo = *byteorder;
4940
4941 /* Check for BOM marks (U+FEFF) in the input and adjust current
4942 byte order setting accordingly. In native mode, the leading BOM
4943 mark is skipped, in all other modes, it is copied to the output
4944 stream as-is (giving a ZWNBSP character). */
4945 if (bo == 0) {
4946 if (size >= 4) {
4947 const Py_UCS4 bom = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
Benjamin Peterson29060642009-01-31 22:14:21 +00004948 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00004949#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00004950 if (bom == 0x0000FEFF) {
4951 q += 4;
4952 bo = -1;
4953 }
4954 else if (bom == 0xFFFE0000) {
4955 q += 4;
4956 bo = 1;
4957 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004958#else
Benjamin Peterson29060642009-01-31 22:14:21 +00004959 if (bom == 0x0000FEFF) {
4960 q += 4;
4961 bo = 1;
4962 }
4963 else if (bom == 0xFFFE0000) {
4964 q += 4;
4965 bo = -1;
4966 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004967#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00004968 }
Walter Dörwald41980ca2007-08-16 21:55:45 +00004969 }
4970
4971 if (bo == -1) {
4972 /* force LE */
4973 iorder[0] = 0;
4974 iorder[1] = 1;
4975 iorder[2] = 2;
4976 iorder[3] = 3;
4977 }
4978 else if (bo == 1) {
4979 /* force BE */
4980 iorder[0] = 3;
4981 iorder[1] = 2;
4982 iorder[2] = 1;
4983 iorder[3] = 0;
4984 }
4985
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004986 /* This might be one to much, because of a BOM */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004987 unicode = PyUnicode_New((size+3)/4, 127);
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004988 if (!unicode)
4989 return NULL;
4990 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01004991 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01004992 outpos = 0;
Antoine Pitroucc0cfd32010-06-11 21:46:32 +00004993
Walter Dörwald41980ca2007-08-16 21:55:45 +00004994 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00004995 Py_UCS4 ch;
4996 /* remaining bytes at the end? (size should be divisible by 4) */
4997 if (e-q<4) {
4998 if (consumed)
4999 break;
5000 errmsg = "truncated data";
5001 startinpos = ((const char *)q)-starts;
5002 endinpos = ((const char *)e)-starts;
5003 goto utf32Error;
5004 /* The remaining input chars are ignored if the callback
5005 chooses to skip the input */
5006 }
5007 ch = (q[iorder[3]] << 24) | (q[iorder[2]] << 16) |
5008 (q[iorder[1]] << 8) | q[iorder[0]];
Walter Dörwald41980ca2007-08-16 21:55:45 +00005009
Benjamin Peterson29060642009-01-31 22:14:21 +00005010 if (ch >= 0x110000)
5011 {
5012 errmsg = "codepoint not in range(0x110000)";
5013 startinpos = ((const char *)q)-starts;
5014 endinpos = startinpos+4;
5015 goto utf32Error;
5016 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005017 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5018 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005019 q += 4;
5020 continue;
5021 utf32Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005022 if (unicode_decode_call_errorhandler(
5023 errors, &errorHandler,
5024 "utf32", errmsg,
5025 &starts, (const char **)&e, &startinpos, &endinpos, &exc, (const char **)&q,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005026 &unicode, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005027 goto onError;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005028 }
5029
5030 if (byteorder)
5031 *byteorder = bo;
5032
5033 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005034 *consumed = (const char *)q-starts;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005035
5036 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005037 if (PyUnicode_Resize(&unicode, outpos) < 0)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005038 goto onError;
5039
5040 Py_XDECREF(errorHandler);
5041 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005042#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005043 if (_PyUnicode_READY_REPLACE(&unicode)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005044 Py_DECREF(unicode);
5045 return NULL;
5046 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005047#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005048 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005049 return unicode;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005050
Benjamin Peterson29060642009-01-31 22:14:21 +00005051 onError:
Walter Dörwald41980ca2007-08-16 21:55:45 +00005052 Py_DECREF(unicode);
5053 Py_XDECREF(errorHandler);
5054 Py_XDECREF(exc);
5055 return NULL;
5056}
5057
5058PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005059_PyUnicode_EncodeUTF32(PyObject *str,
5060 const char *errors,
5061 int byteorder)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005062{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005063 int kind;
5064 void *data;
5065 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005066 PyObject *v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005067 unsigned char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005068 Py_ssize_t nsize, bytesize, i;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005069 /* Offsets from p for storing byte pairs in the right order. */
5070#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5071 int iorder[] = {0, 1, 2, 3};
5072#else
5073 int iorder[] = {3, 2, 1, 0};
5074#endif
5075
Benjamin Peterson29060642009-01-31 22:14:21 +00005076#define STORECHAR(CH) \
5077 do { \
5078 p[iorder[3]] = ((CH) >> 24) & 0xff; \
5079 p[iorder[2]] = ((CH) >> 16) & 0xff; \
5080 p[iorder[1]] = ((CH) >> 8) & 0xff; \
5081 p[iorder[0]] = (CH) & 0xff; \
5082 p += 4; \
Walter Dörwald41980ca2007-08-16 21:55:45 +00005083 } while(0)
5084
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005085 if (!PyUnicode_Check(str)) {
5086 PyErr_BadArgument();
5087 return NULL;
5088 }
5089 if (PyUnicode_READY(str) < 0)
5090 return NULL;
5091 kind = PyUnicode_KIND(str);
5092 data = PyUnicode_DATA(str);
5093 len = PyUnicode_GET_LENGTH(str);
5094
5095 nsize = len + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005096 bytesize = nsize * 4;
5097 if (bytesize / 4 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005098 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005099 v = PyBytes_FromStringAndSize(NULL, bytesize);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005100 if (v == NULL)
5101 return NULL;
5102
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005103 p = (unsigned char *)PyBytes_AS_STRING(v);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005104 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005105 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005106 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005107 goto done;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005108
5109 if (byteorder == -1) {
5110 /* force LE */
5111 iorder[0] = 0;
5112 iorder[1] = 1;
5113 iorder[2] = 2;
5114 iorder[3] = 3;
5115 }
5116 else if (byteorder == 1) {
5117 /* force BE */
5118 iorder[0] = 3;
5119 iorder[1] = 2;
5120 iorder[2] = 1;
5121 iorder[3] = 0;
5122 }
5123
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005124 for (i = 0; i < len; i++)
5125 STORECHAR(PyUnicode_READ(kind, data, i));
Guido van Rossum98297ee2007-11-06 21:34:58 +00005126
5127 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005128 return v;
Walter Dörwald41980ca2007-08-16 21:55:45 +00005129#undef STORECHAR
5130}
5131
Alexander Belopolsky40018472011-02-26 01:02:56 +00005132PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005133PyUnicode_EncodeUTF32(const Py_UNICODE *s,
5134 Py_ssize_t size,
5135 const char *errors,
5136 int byteorder)
5137{
5138 PyObject *result;
5139 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5140 if (tmp == NULL)
5141 return NULL;
5142 result = _PyUnicode_EncodeUTF32(tmp, errors, byteorder);
5143 Py_DECREF(tmp);
5144 return result;
5145}
5146
5147PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005148PyUnicode_AsUTF32String(PyObject *unicode)
Walter Dörwald41980ca2007-08-16 21:55:45 +00005149{
Walter Dörwald41980ca2007-08-16 21:55:45 +00005150 return PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(unicode),
Benjamin Peterson29060642009-01-31 22:14:21 +00005151 PyUnicode_GET_SIZE(unicode),
5152 NULL,
5153 0);
Walter Dörwald41980ca2007-08-16 21:55:45 +00005154}
5155
Guido van Rossumd57fd912000-03-10 22:53:23 +00005156/* --- UTF-16 Codec ------------------------------------------------------- */
5157
Tim Peters772747b2001-08-09 22:21:55 +00005158PyObject *
5159PyUnicode_DecodeUTF16(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005160 Py_ssize_t size,
5161 const char *errors,
5162 int *byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005163{
Walter Dörwald69652032004-09-07 20:24:22 +00005164 return PyUnicode_DecodeUTF16Stateful(s, size, errors, byteorder, NULL);
5165}
5166
Antoine Pitrouab868312009-01-10 15:40:25 +00005167/* Two masks for fast checking of whether a C 'long' may contain
5168 UTF16-encoded surrogate characters. This is an efficient heuristic,
5169 assuming that non-surrogate characters with a code point >= 0x8000 are
5170 rare in most input.
5171 FAST_CHAR_MASK is used when the input is in native byte ordering,
5172 SWAPPED_FAST_CHAR_MASK when the input is in byteswapped ordering.
Benjamin Peterson29060642009-01-31 22:14:21 +00005173*/
Antoine Pitrouab868312009-01-10 15:40:25 +00005174#if (SIZEOF_LONG == 8)
5175# define FAST_CHAR_MASK 0x8000800080008000L
5176# define SWAPPED_FAST_CHAR_MASK 0x0080008000800080L
5177#elif (SIZEOF_LONG == 4)
5178# define FAST_CHAR_MASK 0x80008000L
5179# define SWAPPED_FAST_CHAR_MASK 0x00800080L
5180#else
5181# error C 'long' size should be either 4 or 8!
5182#endif
5183
Walter Dörwald69652032004-09-07 20:24:22 +00005184PyObject *
5185PyUnicode_DecodeUTF16Stateful(const char *s,
Benjamin Peterson29060642009-01-31 22:14:21 +00005186 Py_ssize_t size,
5187 const char *errors,
5188 int *byteorder,
5189 Py_ssize_t *consumed)
Walter Dörwald69652032004-09-07 20:24:22 +00005190{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005191 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005192 Py_ssize_t startinpos;
5193 Py_ssize_t endinpos;
5194 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005195 PyObject *unicode;
Antoine Pitrouab868312009-01-10 15:40:25 +00005196 const unsigned char *q, *e, *aligned_end;
Tim Peters772747b2001-08-09 22:21:55 +00005197 int bo = 0; /* assume native ordering by default */
Antoine Pitrouab868312009-01-10 15:40:25 +00005198 int native_ordering = 0;
Marc-André Lemburg9542f482000-07-17 18:23:13 +00005199 const char *errmsg = "";
Tim Peters772747b2001-08-09 22:21:55 +00005200 /* Offsets from q for retrieving byte pairs in the right order. */
5201#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5202 int ihi = 1, ilo = 0;
5203#else
5204 int ihi = 0, ilo = 1;
5205#endif
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005206 PyObject *errorHandler = NULL;
5207 PyObject *exc = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005208
5209 /* Note: size will always be longer than the resulting Unicode
5210 character count */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005211 unicode = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005212 if (!unicode)
5213 return NULL;
5214 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005215 return unicode;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005216 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005217
Tim Peters772747b2001-08-09 22:21:55 +00005218 q = (unsigned char *)s;
Antoine Pitrouab868312009-01-10 15:40:25 +00005219 e = q + size - 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005220
5221 if (byteorder)
Tim Peters772747b2001-08-09 22:21:55 +00005222 bo = *byteorder;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005223
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005224 /* Check for BOM marks (U+FEFF) in the input and adjust current
5225 byte order setting accordingly. In native mode, the leading BOM
5226 mark is skipped, in all other modes, it is copied to the output
5227 stream as-is (giving a ZWNBSP character). */
5228 if (bo == 0) {
Walter Dörwald69652032004-09-07 20:24:22 +00005229 if (size >= 2) {
5230 const Py_UNICODE bom = (q[ihi] << 8) | q[ilo];
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005231#ifdef BYTEORDER_IS_LITTLE_ENDIAN
Benjamin Peterson29060642009-01-31 22:14:21 +00005232 if (bom == 0xFEFF) {
5233 q += 2;
5234 bo = -1;
5235 }
5236 else if (bom == 0xFFFE) {
5237 q += 2;
5238 bo = 1;
5239 }
Tim Petersced69f82003-09-16 20:30:58 +00005240#else
Benjamin Peterson29060642009-01-31 22:14:21 +00005241 if (bom == 0xFEFF) {
5242 q += 2;
5243 bo = 1;
5244 }
5245 else if (bom == 0xFFFE) {
5246 q += 2;
5247 bo = -1;
5248 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005249#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00005250 }
Marc-André Lemburg489b56e2001-05-21 20:30:15 +00005251 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005252
Tim Peters772747b2001-08-09 22:21:55 +00005253 if (bo == -1) {
5254 /* force LE */
5255 ihi = 1;
5256 ilo = 0;
5257 }
5258 else if (bo == 1) {
5259 /* force BE */
5260 ihi = 0;
5261 ilo = 1;
5262 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005263#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5264 native_ordering = ilo < ihi;
5265#else
5266 native_ordering = ilo > ihi;
5267#endif
Tim Peters772747b2001-08-09 22:21:55 +00005268
Antoine Pitrouab868312009-01-10 15:40:25 +00005269 aligned_end = (const unsigned char *) ((size_t) e & ~LONG_PTR_MASK);
Tim Peters772747b2001-08-09 22:21:55 +00005270 while (q < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00005271 Py_UNICODE ch;
Antoine Pitrouab868312009-01-10 15:40:25 +00005272 /* First check for possible aligned read of a C 'long'. Unaligned
5273 reads are more expensive, better to defer to another iteration. */
5274 if (!((size_t) q & LONG_PTR_MASK)) {
5275 /* Fast path for runs of non-surrogate chars. */
5276 register const unsigned char *_q = q;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005277 int kind = PyUnicode_KIND(unicode);
5278 void *data = PyUnicode_DATA(unicode);
5279 while (_q < aligned_end) {
5280 unsigned long block = * (unsigned long *) _q;
5281 unsigned short *pblock = (unsigned short*)&block;
5282 Py_UCS4 maxch;
5283 if (native_ordering) {
5284 /* Can use buffer directly */
5285 if (block & FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005286 break;
Antoine Pitrouab868312009-01-10 15:40:25 +00005287 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005288 else {
5289 /* Need to byte-swap */
5290 unsigned char *_p = (unsigned char*)pblock;
5291 if (block & SWAPPED_FAST_CHAR_MASK)
Antoine Pitrouab868312009-01-10 15:40:25 +00005292 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005293 _p[0] = _q[1];
5294 _p[1] = _q[0];
5295 _p[2] = _q[3];
5296 _p[3] = _q[2];
Antoine Pitrouab868312009-01-10 15:40:25 +00005297#if (SIZEOF_LONG == 8)
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005298 _p[4] = _q[5];
5299 _p[5] = _q[4];
5300 _p[6] = _q[7];
5301 _p[7] = _q[6];
Antoine Pitrouab868312009-01-10 15:40:25 +00005302#endif
Antoine Pitrouab868312009-01-10 15:40:25 +00005303 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005304 maxch = Py_MAX(pblock[0], pblock[1]);
5305#if SIZEOF_LONG == 8
5306 maxch = Py_MAX(maxch, Py_MAX(pblock[2], pblock[3]));
5307#endif
5308 if (maxch > PyUnicode_MAX_CHAR_VALUE(unicode)) {
5309 if (unicode_widen(&unicode, maxch) < 0)
5310 goto onError;
5311 kind = PyUnicode_KIND(unicode);
5312 data = PyUnicode_DATA(unicode);
5313 }
5314 PyUnicode_WRITE(kind, data, outpos++, pblock[0]);
5315 PyUnicode_WRITE(kind, data, outpos++, pblock[1]);
5316#if SIZEOF_LONG == 8
5317 PyUnicode_WRITE(kind, data, outpos++, pblock[2]);
5318 PyUnicode_WRITE(kind, data, outpos++, pblock[3]);
5319#endif
5320 _q += SIZEOF_LONG;
Antoine Pitrouab868312009-01-10 15:40:25 +00005321 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005322 q = _q;
5323 if (q >= e)
5324 break;
5325 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005326 ch = (q[ihi] << 8) | q[ilo];
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005327
Benjamin Peterson14339b62009-01-31 16:36:08 +00005328 q += 2;
Benjamin Peterson29060642009-01-31 22:14:21 +00005329
5330 if (ch < 0xD800 || ch > 0xDFFF) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005331 if (unicode_putchar(&unicode, &outpos, ch) < 0)
5332 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005333 continue;
5334 }
5335
5336 /* UTF-16 code pair: */
5337 if (q > e) {
5338 errmsg = "unexpected end of data";
5339 startinpos = (((const char *)q) - 2) - starts;
5340 endinpos = ((const char *)e) + 1 - starts;
5341 goto utf16Error;
5342 }
5343 if (0xD800 <= ch && ch <= 0xDBFF) {
5344 Py_UNICODE ch2 = (q[ihi] << 8) | q[ilo];
5345 q += 2;
5346 if (0xDC00 <= ch2 && ch2 <= 0xDFFF) {
Victor Stinner62aa4d02011-11-09 00:03:45 +01005347 if (unicode_putchar(&unicode, &outpos,
5348 (((ch & 0x3FF)<<10) |
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005349 (ch2 & 0x3FF)) + 0x10000) < 0)
5350 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00005351 continue;
5352 }
5353 else {
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005354 errmsg = "illegal UTF-16 surrogate";
Benjamin Peterson29060642009-01-31 22:14:21 +00005355 startinpos = (((const char *)q)-4)-starts;
5356 endinpos = startinpos+2;
5357 goto utf16Error;
5358 }
5359
Benjamin Peterson14339b62009-01-31 16:36:08 +00005360 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005361 errmsg = "illegal encoding";
5362 startinpos = (((const char *)q)-2)-starts;
5363 endinpos = startinpos+2;
5364 /* Fall through to report the error */
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005365
Benjamin Peterson29060642009-01-31 22:14:21 +00005366 utf16Error:
Benjamin Peterson29060642009-01-31 22:14:21 +00005367 if (unicode_decode_call_errorhandler(
Antoine Pitrouab868312009-01-10 15:40:25 +00005368 errors,
5369 &errorHandler,
5370 "utf16", errmsg,
5371 &starts,
5372 (const char **)&e,
5373 &startinpos,
5374 &endinpos,
5375 &exc,
5376 (const char **)&q,
5377 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005378 &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00005379 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005380 }
Antoine Pitrouab868312009-01-10 15:40:25 +00005381 /* remaining byte at the end? (size should be even) */
5382 if (e == q) {
5383 if (!consumed) {
5384 errmsg = "truncated data";
5385 startinpos = ((const char *)q) - starts;
5386 endinpos = ((const char *)e) + 1 - starts;
Antoine Pitrouab868312009-01-10 15:40:25 +00005387 if (unicode_decode_call_errorhandler(
5388 errors,
5389 &errorHandler,
5390 "utf16", errmsg,
5391 &starts,
5392 (const char **)&e,
5393 &startinpos,
5394 &endinpos,
5395 &exc,
5396 (const char **)&q,
5397 &unicode,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005398 &outpos))
Antoine Pitrouab868312009-01-10 15:40:25 +00005399 goto onError;
5400 /* The remaining input chars are ignored if the callback
5401 chooses to skip the input */
5402 }
5403 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00005404
5405 if (byteorder)
5406 *byteorder = bo;
5407
Walter Dörwald69652032004-09-07 20:24:22 +00005408 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00005409 *consumed = (const char *)q-starts;
Walter Dörwald69652032004-09-07 20:24:22 +00005410
Guido van Rossumd57fd912000-03-10 22:53:23 +00005411 /* Adjust length */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005412 if (PyUnicode_Resize(&unicode, outpos) < 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005413 goto onError;
5414
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005415 Py_XDECREF(errorHandler);
5416 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005417 assert(_PyUnicode_CheckConsistency(unicode, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005418 return unicode;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005419
Benjamin Peterson29060642009-01-31 22:14:21 +00005420 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005421 Py_DECREF(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005422 Py_XDECREF(errorHandler);
5423 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005424 return NULL;
5425}
5426
Antoine Pitrouab868312009-01-10 15:40:25 +00005427#undef FAST_CHAR_MASK
5428#undef SWAPPED_FAST_CHAR_MASK
5429
Tim Peters772747b2001-08-09 22:21:55 +00005430PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005431_PyUnicode_EncodeUTF16(PyObject *str,
5432 const char *errors,
5433 int byteorder)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005434{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005435 int kind;
5436 void *data;
5437 Py_ssize_t len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005438 PyObject *v;
Tim Peters772747b2001-08-09 22:21:55 +00005439 unsigned char *p;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005440 Py_ssize_t nsize, bytesize;
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005441 Py_ssize_t i, pairs;
Tim Peters772747b2001-08-09 22:21:55 +00005442 /* Offsets from p for storing byte pairs in the right order. */
5443#ifdef BYTEORDER_IS_LITTLE_ENDIAN
5444 int ihi = 1, ilo = 0;
5445#else
5446 int ihi = 0, ilo = 1;
5447#endif
5448
Benjamin Peterson29060642009-01-31 22:14:21 +00005449#define STORECHAR(CH) \
5450 do { \
5451 p[ihi] = ((CH) >> 8) & 0xff; \
5452 p[ilo] = (CH) & 0xff; \
5453 p += 2; \
Tim Peters772747b2001-08-09 22:21:55 +00005454 } while(0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005455
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005456 if (!PyUnicode_Check(str)) {
5457 PyErr_BadArgument();
5458 return NULL;
5459 }
5460 if (PyUnicode_READY(str) < 0)
5461 return NULL;
5462 kind = PyUnicode_KIND(str);
5463 data = PyUnicode_DATA(str);
5464 len = PyUnicode_GET_LENGTH(str);
5465
5466 pairs = 0;
5467 if (kind == PyUnicode_4BYTE_KIND)
5468 for (i = 0; i < len; i++)
5469 if (PyUnicode_READ(kind, data, i) >= 0x10000)
5470 pairs++;
5471 /* 2 * (len + pairs + (byteorder == 0)) */
5472 if (len > PY_SSIZE_T_MAX - pairs - (byteorder == 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00005473 return PyErr_NoMemory();
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005474 nsize = len + pairs + (byteorder == 0);
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005475 bytesize = nsize * 2;
5476 if (bytesize / 2 != nsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005477 return PyErr_NoMemory();
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005478 v = PyBytes_FromStringAndSize(NULL, bytesize);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005479 if (v == NULL)
5480 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005481
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005482 p = (unsigned char *)PyBytes_AS_STRING(v);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005483 if (byteorder == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00005484 STORECHAR(0xFEFF);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005485 if (len == 0)
Guido van Rossum98297ee2007-11-06 21:34:58 +00005486 goto done;
Tim Peters772747b2001-08-09 22:21:55 +00005487
5488 if (byteorder == -1) {
5489 /* force LE */
5490 ihi = 1;
5491 ilo = 0;
5492 }
5493 else if (byteorder == 1) {
5494 /* force BE */
5495 ihi = 0;
5496 ilo = 1;
5497 }
5498
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005499 for (i = 0; i < len; i++) {
5500 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
5501 Py_UCS4 ch2 = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +00005502 if (ch >= 0x10000) {
5503 ch2 = 0xDC00 | ((ch-0x10000) & 0x3FF);
5504 ch = 0xD800 | ((ch-0x10000) >> 10);
5505 }
Tim Peters772747b2001-08-09 22:21:55 +00005506 STORECHAR(ch);
5507 if (ch2)
5508 STORECHAR(ch2);
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005509 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00005510
5511 done:
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005512 return v;
Tim Peters772747b2001-08-09 22:21:55 +00005513#undef STORECHAR
Guido van Rossumd57fd912000-03-10 22:53:23 +00005514}
5515
Alexander Belopolsky40018472011-02-26 01:02:56 +00005516PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005517PyUnicode_EncodeUTF16(const Py_UNICODE *s,
5518 Py_ssize_t size,
5519 const char *errors,
5520 int byteorder)
5521{
5522 PyObject *result;
5523 PyObject *tmp = PyUnicode_FromUnicode(s, size);
5524 if (tmp == NULL)
5525 return NULL;
5526 result = _PyUnicode_EncodeUTF16(tmp, errors, byteorder);
5527 Py_DECREF(tmp);
5528 return result;
5529}
5530
5531PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00005532PyUnicode_AsUTF16String(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005533{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005534 return _PyUnicode_EncodeUTF16(unicode, NULL, 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005535}
5536
5537/* --- Unicode Escape Codec ----------------------------------------------- */
5538
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005539/* Helper function for PyUnicode_DecodeUnicodeEscape, determines
5540 if all the escapes in the string make it still a valid ASCII string.
5541 Returns -1 if any escapes were found which cause the string to
5542 pop out of ASCII range. Otherwise returns the length of the
5543 required buffer to hold the string.
5544 */
Antoine Pitrou53bb5482011-10-10 23:49:24 +02005545static Py_ssize_t
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005546length_of_escaped_ascii_string(const char *s, Py_ssize_t size)
5547{
5548 const unsigned char *p = (const unsigned char *)s;
5549 const unsigned char *end = p + size;
5550 Py_ssize_t length = 0;
5551
5552 if (size < 0)
5553 return -1;
5554
5555 for (; p < end; ++p) {
5556 if (*p > 127) {
5557 /* Non-ASCII */
5558 return -1;
5559 }
5560 else if (*p != '\\') {
5561 /* Normal character */
5562 ++length;
5563 }
5564 else {
5565 /* Backslash-escape, check next char */
5566 ++p;
5567 /* Escape sequence reaches till end of string or
5568 non-ASCII follow-up. */
5569 if (p >= end || *p > 127)
5570 return -1;
5571 switch (*p) {
5572 case '\n':
5573 /* backslash + \n result in zero characters */
5574 break;
5575 case '\\': case '\'': case '\"':
5576 case 'b': case 'f': case 't':
5577 case 'n': case 'r': case 'v': case 'a':
5578 ++length;
5579 break;
5580 case '0': case '1': case '2': case '3':
5581 case '4': case '5': case '6': case '7':
5582 case 'x': case 'u': case 'U': case 'N':
5583 /* these do not guarantee ASCII characters */
5584 return -1;
5585 default:
5586 /* count the backslash + the other character */
5587 length += 2;
5588 }
5589 }
5590 }
5591 return length;
5592}
5593
5594/* Similar to PyUnicode_WRITE but either write into wstr field
5595 or treat string as ASCII. */
5596#define WRITE_ASCII_OR_WSTR(kind, buf, index, value) \
5597 do { \
5598 if ((kind) != PyUnicode_WCHAR_KIND) \
5599 ((unsigned char *)(buf))[(index)] = (unsigned char)(value); \
5600 else \
5601 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value); \
5602 } while (0)
5603
5604#define WRITE_WSTR(buf, index, value) \
5605 assert(kind == PyUnicode_WCHAR_KIND), \
5606 ((Py_UNICODE *)(buf))[(index)] = (Py_UNICODE)(value)
5607
5608
Fredrik Lundh06d12682001-01-24 07:59:11 +00005609static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
Marc-André Lemburg0f774e32000-06-28 16:43:35 +00005610
Alexander Belopolsky40018472011-02-26 01:02:56 +00005611PyObject *
5612PyUnicode_DecodeUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03005613 Py_ssize_t size,
Victor Stinnerc17f5402011-09-29 00:16:58 +02005614 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005615{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005616 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00005617 Py_ssize_t startinpos;
5618 Py_ssize_t endinpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005619 int j;
Victor Stinner7931d9a2011-11-04 00:22:48 +01005620 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005621 const char *end;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005622 char* message;
5623 Py_UCS4 chr = 0xffffffff; /* in case 'getcode' messes up */
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005624 PyObject *errorHandler = NULL;
5625 PyObject *exc = NULL;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005626 Py_ssize_t len;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005627 Py_ssize_t i;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005628
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005629 len = length_of_escaped_ascii_string(s, size);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005630
5631 /* After length_of_escaped_ascii_string() there are two alternatives,
5632 either the string is pure ASCII with named escapes like \n, etc.
5633 and we determined it's exact size (common case)
5634 or it contains \x, \u, ... escape sequences. then we create a
5635 legacy wchar string and resize it at the end of this function. */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005636 if (len >= 0) {
5637 v = PyUnicode_New(len, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005638 if (!v)
5639 goto onError;
5640 assert(PyUnicode_KIND(v) == PyUnicode_1BYTE_KIND);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005641 }
5642 else {
5643 /* Escaped strings will always be longer than the resulting
5644 Unicode string, so we start with size here and then reduce the
5645 length after conversion to the true value.
5646 (but if the error callback returns a long replacement string
5647 we'll have to allocate more space) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005648 v = PyUnicode_New(size, 127);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005649 if (!v)
5650 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005651 len = size;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005652 }
5653
Guido van Rossumd57fd912000-03-10 22:53:23 +00005654 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01005655 return v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005656 i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005657 end = s + size;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005658
Guido van Rossumd57fd912000-03-10 22:53:23 +00005659 while (s < end) {
5660 unsigned char c;
Marc-André Lemburg063e0cb2000-07-07 11:27:45 +00005661 Py_UNICODE x;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005662 int digits;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005663
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005664 /* The only case in which i == ascii_length is a backslash
5665 followed by a newline. */
5666 assert(i <= len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005667
Guido van Rossumd57fd912000-03-10 22:53:23 +00005668 /* Non-escape characters are interpreted as Unicode ordinals */
5669 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005670 if (unicode_putchar(&v, &i, (unsigned char) *s++) < 0)
5671 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005672 continue;
5673 }
5674
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005675 startinpos = s-starts;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005676 /* \ - Escapes */
5677 s++;
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005678 c = *s++;
5679 if (s > end)
5680 c = '\0'; /* Invalid after \ */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005681
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005682 /* The only case in which i == ascii_length is a backslash
5683 followed by a newline. */
5684 assert(i < len || (i == len && c == '\n'));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005685
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005686 switch (c) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005687
Benjamin Peterson29060642009-01-31 22:14:21 +00005688 /* \x escapes */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005689#define WRITECHAR(ch) \
5690 do { \
5691 if (unicode_putchar(&v, &i, ch) < 0) \
5692 goto onError; \
5693 }while(0)
5694
Guido van Rossumd57fd912000-03-10 22:53:23 +00005695 case '\n': break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005696 case '\\': WRITECHAR('\\'); break;
5697 case '\'': WRITECHAR('\''); break;
5698 case '\"': WRITECHAR('\"'); break;
5699 case 'b': WRITECHAR('\b'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005700 /* FF */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005701 case 'f': WRITECHAR('\014'); break;
5702 case 't': WRITECHAR('\t'); break;
5703 case 'n': WRITECHAR('\n'); break;
5704 case 'r': WRITECHAR('\r'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005705 /* VT */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005706 case 'v': WRITECHAR('\013'); break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005707 /* BEL, not classic C */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005708 case 'a': WRITECHAR('\007'); break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005709
Benjamin Peterson29060642009-01-31 22:14:21 +00005710 /* \OOO (octal) escapes */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005711 case '0': case '1': case '2': case '3':
5712 case '4': case '5': case '6': case '7':
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005713 x = s[-1] - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005714 if (s < end && '0' <= *s && *s <= '7') {
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005715 x = (x<<3) + *s++ - '0';
Guido van Rossum8ce8a782007-11-01 19:42:39 +00005716 if (s < end && '0' <= *s && *s <= '7')
Guido van Rossum0e4f6572000-05-01 21:27:20 +00005717 x = (x<<3) + *s++ - '0';
Guido van Rossumd57fd912000-03-10 22:53:23 +00005718 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005719 WRITECHAR(x);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005720 break;
5721
Benjamin Peterson29060642009-01-31 22:14:21 +00005722 /* hex escapes */
5723 /* \xXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005724 case 'x':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005725 digits = 2;
5726 message = "truncated \\xXX escape";
5727 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005728
Benjamin Peterson29060642009-01-31 22:14:21 +00005729 /* \uXXXX */
Guido van Rossumd57fd912000-03-10 22:53:23 +00005730 case 'u':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005731 digits = 4;
5732 message = "truncated \\uXXXX escape";
5733 goto hexescape;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005734
Benjamin Peterson29060642009-01-31 22:14:21 +00005735 /* \UXXXXXXXX */
Fredrik Lundhdf846752000-09-03 11:29:49 +00005736 case 'U':
Fredrik Lundhccc74732001-02-18 22:13:49 +00005737 digits = 8;
5738 message = "truncated \\UXXXXXXXX escape";
5739 hexescape:
5740 chr = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005741 if (s+digits>end) {
5742 endinpos = size;
5743 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005744 errors, &errorHandler,
5745 "unicodeescape", "end of string in escape sequence",
5746 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005747 &v, &i))
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005748 goto onError;
5749 goto nextByte;
5750 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005751 for (j = 0; j < digits; ++j) {
5752 c = (unsigned char) s[j];
David Malcolm96960882010-11-05 17:23:41 +00005753 if (!Py_ISXDIGIT(c)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005754 endinpos = (s+j+1)-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005755 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005756 errors, &errorHandler,
5757 "unicodeescape", message,
5758 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005759 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005760 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005761 len = PyUnicode_GET_LENGTH(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005762 goto nextByte;
Fredrik Lundhdf846752000-09-03 11:29:49 +00005763 }
5764 chr = (chr<<4) & ~0xF;
5765 if (c >= '0' && c <= '9')
5766 chr += c - '0';
5767 else if (c >= 'a' && c <= 'f')
5768 chr += 10 + c - 'a';
5769 else
5770 chr += 10 + c - 'A';
5771 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005772 s += j;
Jeremy Hylton504de6b2003-10-06 05:08:26 +00005773 if (chr == 0xffffffff && PyErr_Occurred())
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005774 /* _decoding_error will have already written into the
5775 target buffer. */
5776 break;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005777 store:
Fredrik Lundhdf846752000-09-03 11:29:49 +00005778 /* when we get here, chr is a 32-bit unicode character */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005779 if (chr <= 0x10ffff) {
5780 WRITECHAR(chr);
Fredrik Lundhdf846752000-09-03 11:29:49 +00005781 } else {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005782 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005783 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005784 errors, &errorHandler,
5785 "unicodeescape", "illegal Unicode character",
5786 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005787 &v, &i))
Fredrik Lundhdf846752000-09-03 11:29:49 +00005788 goto onError;
5789 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005790 break;
5791
Benjamin Peterson29060642009-01-31 22:14:21 +00005792 /* \N{name} */
Fredrik Lundhccc74732001-02-18 22:13:49 +00005793 case 'N':
5794 message = "malformed \\N character escape";
5795 if (ucnhash_CAPI == NULL) {
5796 /* load the unicode data module */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005797 ucnhash_CAPI = (_PyUnicode_Name_CAPI *)PyCapsule_Import(
5798 PyUnicodeData_CAPSULE_NAME, 1);
Fredrik Lundhccc74732001-02-18 22:13:49 +00005799 if (ucnhash_CAPI == NULL)
5800 goto ucnhashError;
5801 }
5802 if (*s == '{') {
5803 const char *start = s+1;
5804 /* look for the closing brace */
5805 while (*s != '}' && s < end)
5806 s++;
5807 if (s > start && s < end && *s == '}') {
5808 /* found a name. look it up in the unicode database */
5809 message = "unknown Unicode character name";
5810 s++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005811 if (ucnhash_CAPI->getcode(NULL, start, (int)(s-start-1),
Ezio Melotti931b8aa2011-10-21 21:57:36 +03005812 &chr, 0))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005813 goto store;
5814 }
5815 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005816 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005817 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005818 errors, &errorHandler,
5819 "unicodeescape", message,
5820 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005821 &v, &i))
Fredrik Lundhccc74732001-02-18 22:13:49 +00005822 goto onError;
Fredrik Lundhccc74732001-02-18 22:13:49 +00005823 break;
5824
5825 default:
Walter Dörwald8c077222002-03-25 11:16:18 +00005826 if (s > end) {
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005827 message = "\\ at end of string";
5828 s--;
5829 endinpos = s-starts;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005830 if (unicode_decode_call_errorhandler(
Benjamin Peterson29060642009-01-31 22:14:21 +00005831 errors, &errorHandler,
5832 "unicodeescape", message,
5833 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005834 &v, &i))
Walter Dörwald8c077222002-03-25 11:16:18 +00005835 goto onError;
5836 }
5837 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005838 WRITECHAR('\\');
5839 WRITECHAR(s[-1]);
Walter Dörwald8c077222002-03-25 11:16:18 +00005840 }
Fredrik Lundhccc74732001-02-18 22:13:49 +00005841 break;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005842 }
Benjamin Peterson29060642009-01-31 22:14:21 +00005843 nextByte:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005844 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005845 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005846#undef WRITECHAR
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005847
Martin v. Löwise9b11c12011-11-08 17:35:34 +01005848 if (PyUnicode_Resize(&v, i) < 0)
5849 goto onError;
Walter Dörwaldd4ade082003-08-15 15:00:26 +00005850 Py_XDECREF(errorHandler);
5851 Py_XDECREF(exc);
Victor Stinner17efeed2011-10-04 20:05:46 +02005852#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02005853 if (_PyUnicode_READY_REPLACE(&v)) {
5854 Py_DECREF(v);
5855 return NULL;
5856 }
Victor Stinner17efeed2011-10-04 20:05:46 +02005857#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02005858 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01005859 return v;
Walter Dörwald8c077222002-03-25 11:16:18 +00005860
Benjamin Peterson29060642009-01-31 22:14:21 +00005861 ucnhashError:
Fredrik Lundh06d12682001-01-24 07:59:11 +00005862 PyErr_SetString(
5863 PyExc_UnicodeError,
5864 "\\N escapes not supported (can't load unicodedata module)"
5865 );
Hye-Shik Chang4af5c8c2006-03-07 15:39:21 +00005866 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005867 Py_XDECREF(errorHandler);
5868 Py_XDECREF(exc);
Fredrik Lundhf6056062001-01-20 11:15:25 +00005869 return NULL;
5870
Benjamin Peterson29060642009-01-31 22:14:21 +00005871 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00005872 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00005873 Py_XDECREF(errorHandler);
5874 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005875 return NULL;
5876}
5877
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02005878#undef WRITE_ASCII_OR_WSTR
5879#undef WRITE_WSTR
5880
Guido van Rossumd57fd912000-03-10 22:53:23 +00005881/* Return a Unicode-Escape string version of the Unicode object.
5882
5883 If quotes is true, the string is enclosed in u"" or u'' quotes as
5884 appropriate.
5885
5886*/
5887
Alexander Belopolsky40018472011-02-26 01:02:56 +00005888PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005889PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00005890{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005891 Py_ssize_t i, len;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005892 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005893 char *p;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005894 int kind;
5895 void *data;
5896 Py_ssize_t expandsize = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00005897
Thomas Wouters89f507f2006-12-13 04:49:30 +00005898 /* Initial allocation is based on the longest-possible unichr
5899 escape.
5900
5901 In wide (UTF-32) builds '\U00xxxxxx' is 10 chars per source
5902 unichr, so in this case it's the longest unichr escape. In
5903 narrow (UTF-16) builds this is five chars per source unichr
5904 since there are two unichrs in the surrogate pair, so in narrow
5905 (UTF-16) builds it's not the longest unichr escape.
5906
5907 In wide or narrow builds '\uxxxx' is 6 chars per source unichr,
5908 so in the narrow (UTF-16) build case it's the longest unichr
5909 escape.
5910 */
5911
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005912 if (!PyUnicode_Check(unicode)) {
5913 PyErr_BadArgument();
5914 return NULL;
5915 }
5916 if (PyUnicode_READY(unicode) < 0)
5917 return NULL;
5918 len = PyUnicode_GET_LENGTH(unicode);
5919 kind = PyUnicode_KIND(unicode);
5920 data = PyUnicode_DATA(unicode);
5921 switch(kind) {
5922 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
5923 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
5924 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
5925 }
5926
5927 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005928 return PyBytes_FromStringAndSize(NULL, 0);
5929
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005930 if (len > (PY_SSIZE_T_MAX - 2 - 1) / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00005931 return PyErr_NoMemory();
Neal Norwitz3ce5d922008-08-24 07:08:55 +00005932
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005933 repr = PyBytes_FromStringAndSize(NULL,
Benjamin Peterson29060642009-01-31 22:14:21 +00005934 2
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005935 + expandsize*len
Benjamin Peterson29060642009-01-31 22:14:21 +00005936 + 1);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005937 if (repr == NULL)
5938 return NULL;
5939
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00005940 p = PyBytes_AS_STRING(repr);
Guido van Rossumd57fd912000-03-10 22:53:23 +00005941
Martin v. Löwis1db7c132011-11-10 18:24:32 +01005942 for (i = 0; i < len; i++) {
5943 Py_UNICODE ch = PyUnicode_READ(kind, data, i);
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005944
Walter Dörwald79e913e2007-05-12 11:08:06 +00005945 /* Escape backslashes */
5946 if (ch == '\\') {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005947 *p++ = '\\';
5948 *p++ = (char) ch;
Walter Dörwald79e913e2007-05-12 11:08:06 +00005949 continue;
Tim Petersced69f82003-09-16 20:30:58 +00005950 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005951
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005952 /* Map 21-bit characters to '\U00xxxxxx' */
5953 else if (ch >= 0x10000) {
5954 *p++ = '\\';
5955 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005956 *p++ = Py_hexdigits[(ch >> 28) & 0x0000000F];
5957 *p++ = Py_hexdigits[(ch >> 24) & 0x0000000F];
5958 *p++ = Py_hexdigits[(ch >> 20) & 0x0000000F];
5959 *p++ = Py_hexdigits[(ch >> 16) & 0x0000000F];
5960 *p++ = Py_hexdigits[(ch >> 12) & 0x0000000F];
5961 *p++ = Py_hexdigits[(ch >> 8) & 0x0000000F];
5962 *p++ = Py_hexdigits[(ch >> 4) & 0x0000000F];
5963 *p++ = Py_hexdigits[ch & 0x0000000F];
Benjamin Peterson29060642009-01-31 22:14:21 +00005964 continue;
Martin v. Löwis0ba70cc2001-06-26 22:22:37 +00005965 }
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005966
Guido van Rossumd57fd912000-03-10 22:53:23 +00005967 /* Map 16-bit characters to '\uxxxx' */
Marc-André Lemburg6c6bfb72001-07-20 17:39:11 +00005968 if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005969 *p++ = '\\';
5970 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005971 *p++ = Py_hexdigits[(ch >> 12) & 0x000F];
5972 *p++ = Py_hexdigits[(ch >> 8) & 0x000F];
5973 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5974 *p++ = Py_hexdigits[ch & 0x000F];
Guido van Rossumd57fd912000-03-10 22:53:23 +00005975 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005976
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005977 /* Map special whitespace to '\t', \n', '\r' */
5978 else if (ch == '\t') {
5979 *p++ = '\\';
5980 *p++ = 't';
5981 }
5982 else if (ch == '\n') {
5983 *p++ = '\\';
5984 *p++ = 'n';
5985 }
5986 else if (ch == '\r') {
5987 *p++ = '\\';
5988 *p++ = 'r';
5989 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005990
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005991 /* Map non-printable US ASCII to '\xhh' */
Marc-André Lemburg11326de2001-11-28 12:56:20 +00005992 else if (ch < ' ' || ch >= 0x7F) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00005993 *p++ = '\\';
Ka-Ping Yeefa004ad2001-01-24 17:19:08 +00005994 *p++ = 'x';
Victor Stinnerf5cff562011-10-14 02:13:11 +02005995 *p++ = Py_hexdigits[(ch >> 4) & 0x000F];
5996 *p++ = Py_hexdigits[ch & 0x000F];
Tim Petersced69f82003-09-16 20:30:58 +00005997 }
Marc-André Lemburg80d1dd52001-07-25 16:05:59 +00005998
Guido van Rossumd57fd912000-03-10 22:53:23 +00005999 /* Copy everything else as-is */
6000 else
6001 *p++ = (char) ch;
6002 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006003
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006004 assert(p - PyBytes_AS_STRING(repr) > 0);
6005 if (_PyBytes_Resize(&repr, p - PyBytes_AS_STRING(repr)) < 0)
6006 return NULL;
6007 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006008}
6009
Alexander Belopolsky40018472011-02-26 01:02:56 +00006010PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006011PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
6012 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006013{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006014 PyObject *result;
6015 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6016 if (tmp == NULL)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006017 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006018 result = PyUnicode_AsUnicodeEscapeString(tmp);
6019 Py_DECREF(tmp);
6020 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006021}
6022
6023/* --- Raw Unicode Escape Codec ------------------------------------------- */
6024
Alexander Belopolsky40018472011-02-26 01:02:56 +00006025PyObject *
6026PyUnicode_DecodeRawUnicodeEscape(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006027 Py_ssize_t size,
6028 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006029{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006030 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006031 Py_ssize_t startinpos;
6032 Py_ssize_t endinpos;
6033 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006034 PyObject *v;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006035 const char *end;
6036 const char *bs;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006037 PyObject *errorHandler = NULL;
6038 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006039
Guido van Rossumd57fd912000-03-10 22:53:23 +00006040 /* Escaped strings will always be longer than the resulting
6041 Unicode string, so we start with size here and then reduce the
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006042 length after conversion to the true value. (But decoding error
6043 handler might have to resize the string) */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006044 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006045 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006046 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006047 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006048 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006049 outpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006050 end = s + size;
6051 while (s < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006052 unsigned char c;
6053 Py_UCS4 x;
6054 int i;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006055 int count;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006056
Benjamin Peterson29060642009-01-31 22:14:21 +00006057 /* Non-escape characters are interpreted as Unicode ordinals */
6058 if (*s != '\\') {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006059 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6060 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006061 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006062 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006063 startinpos = s-starts;
6064
6065 /* \u-escapes are only interpreted iff the number of leading
6066 backslashes if odd */
6067 bs = s;
6068 for (;s < end;) {
6069 if (*s != '\\')
6070 break;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006071 if (unicode_putchar(&v, &outpos, (unsigned char)*s++) < 0)
6072 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00006073 }
6074 if (((s - bs) & 1) == 0 ||
6075 s >= end ||
6076 (*s != 'u' && *s != 'U')) {
6077 continue;
6078 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006079 outpos--;
Benjamin Peterson29060642009-01-31 22:14:21 +00006080 count = *s=='u' ? 4 : 8;
6081 s++;
6082
6083 /* \uXXXX with 4 hex digits, \Uxxxxxxxx with 8 */
Benjamin Peterson29060642009-01-31 22:14:21 +00006084 for (x = 0, i = 0; i < count; ++i, ++s) {
6085 c = (unsigned char)*s;
David Malcolm96960882010-11-05 17:23:41 +00006086 if (!Py_ISXDIGIT(c)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006087 endinpos = s-starts;
6088 if (unicode_decode_call_errorhandler(
6089 errors, &errorHandler,
6090 "rawunicodeescape", "truncated \\uXXXX",
6091 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006092 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006093 goto onError;
6094 goto nextByte;
6095 }
6096 x = (x<<4) & ~0xF;
6097 if (c >= '0' && c <= '9')
6098 x += c - '0';
6099 else if (c >= 'a' && c <= 'f')
6100 x += 10 + c - 'a';
6101 else
6102 x += 10 + c - 'A';
6103 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006104 if (x <= 0x10ffff) {
6105 if (unicode_putchar(&v, &outpos, x) < 0)
6106 goto onError;
Christian Heimesfe337bf2008-03-23 21:54:12 +00006107 } else {
6108 endinpos = s-starts;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006109 if (unicode_decode_call_errorhandler(
6110 errors, &errorHandler,
6111 "rawunicodeescape", "\\Uxxxxxxxx out of range",
Benjamin Peterson29060642009-01-31 22:14:21 +00006112 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006113 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006114 goto onError;
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006115 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006116 nextByte:
6117 ;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006118 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006119 if (PyUnicode_Resize(&v, outpos) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006120 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006121 Py_XDECREF(errorHandler);
6122 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006123 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006124 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006125
Benjamin Peterson29060642009-01-31 22:14:21 +00006126 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006127 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006128 Py_XDECREF(errorHandler);
6129 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006130 return NULL;
6131}
6132
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006133
Alexander Belopolsky40018472011-02-26 01:02:56 +00006134PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006135PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006136{
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006137 PyObject *repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006138 char *p;
6139 char *q;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006140 Py_ssize_t expandsize, pos;
6141 int kind;
6142 void *data;
6143 Py_ssize_t len;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006144
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006145 if (!PyUnicode_Check(unicode)) {
6146 PyErr_BadArgument();
6147 return NULL;
6148 }
6149 if (PyUnicode_READY(unicode) < 0)
6150 return NULL;
6151 kind = PyUnicode_KIND(unicode);
6152 data = PyUnicode_DATA(unicode);
6153 len = PyUnicode_GET_LENGTH(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006154
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006155 switch(kind) {
6156 case PyUnicode_1BYTE_KIND: expandsize = 4; break;
6157 case PyUnicode_2BYTE_KIND: expandsize = 6; break;
6158 case PyUnicode_4BYTE_KIND: expandsize = 10; break;
6159 }
6160
6161 if (len > PY_SSIZE_T_MAX / expandsize)
Benjamin Peterson29060642009-01-31 22:14:21 +00006162 return PyErr_NoMemory();
Benjamin Peterson14339b62009-01-31 16:36:08 +00006163
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006164 repr = PyBytes_FromStringAndSize(NULL, expandsize * len);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006165 if (repr == NULL)
6166 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006167 if (len == 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006168 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006169
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006170 p = q = PyBytes_AS_STRING(repr);
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006171 for (pos = 0; pos < len; pos++) {
6172 Py_UCS4 ch = PyUnicode_READ(kind, data, pos);
Benjamin Peterson29060642009-01-31 22:14:21 +00006173 /* Map 32-bit characters to '\Uxxxxxxxx' */
6174 if (ch >= 0x10000) {
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00006175 *p++ = '\\';
6176 *p++ = 'U';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006177 *p++ = Py_hexdigits[(ch >> 28) & 0xf];
6178 *p++ = Py_hexdigits[(ch >> 24) & 0xf];
6179 *p++ = Py_hexdigits[(ch >> 20) & 0xf];
6180 *p++ = Py_hexdigits[(ch >> 16) & 0xf];
6181 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6182 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6183 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6184 *p++ = Py_hexdigits[ch & 15];
Tim Petersced69f82003-09-16 20:30:58 +00006185 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006186 /* Map 16-bit characters to '\uxxxx' */
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006187 else if (ch >= 256) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00006188 *p++ = '\\';
6189 *p++ = 'u';
Victor Stinnerf5cff562011-10-14 02:13:11 +02006190 *p++ = Py_hexdigits[(ch >> 12) & 0xf];
6191 *p++ = Py_hexdigits[(ch >> 8) & 0xf];
6192 *p++ = Py_hexdigits[(ch >> 4) & 0xf];
6193 *p++ = Py_hexdigits[ch & 15];
Guido van Rossumd57fd912000-03-10 22:53:23 +00006194 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006195 /* Copy everything else as-is */
6196 else
Guido van Rossumd57fd912000-03-10 22:53:23 +00006197 *p++ = (char) ch;
6198 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00006199
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006200 assert(p > q);
6201 if (_PyBytes_Resize(&repr, p - q) < 0)
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006202 return NULL;
6203 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006204}
6205
Alexander Belopolsky40018472011-02-26 01:02:56 +00006206PyObject *
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006207PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
6208 Py_ssize_t size)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006209{
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006210 PyObject *result;
6211 PyObject *tmp = PyUnicode_FromUnicode(s, size);
6212 if (tmp == NULL)
Walter Dörwald711005d2007-05-12 12:03:26 +00006213 return NULL;
Martin v. Löwis1db7c132011-11-10 18:24:32 +01006214 result = PyUnicode_AsRawUnicodeEscapeString(tmp);
6215 Py_DECREF(tmp);
6216 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006217}
6218
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006219/* --- Unicode Internal Codec ------------------------------------------- */
6220
Alexander Belopolsky40018472011-02-26 01:02:56 +00006221PyObject *
6222_PyUnicode_DecodeUnicodeInternal(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006223 Py_ssize_t size,
6224 const char *errors)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006225{
6226 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006227 Py_ssize_t startinpos;
6228 Py_ssize_t endinpos;
6229 Py_ssize_t outpos;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006230 PyObject *v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006231 const char *end;
6232 const char *reason;
6233 PyObject *errorHandler = NULL;
6234 PyObject *exc = NULL;
6235
Thomas Wouters89f507f2006-12-13 04:49:30 +00006236 /* XXX overflow detection missing */
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006237 v = PyUnicode_New((size+Py_UNICODE_SIZE-1)/ Py_UNICODE_SIZE, 127);
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006238 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006239 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006240 if (PyUnicode_GET_LENGTH(v) == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006241 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006242 outpos = 0;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006243 end = s + size;
6244
6245 while (s < end) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006246 Py_UCS4 ch = *(Py_UNICODE*)s;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006247 /* We have to sanity check the raw data, otherwise doom looms for
6248 some malformed UCS-4 data. */
6249 if (
Benjamin Peterson29060642009-01-31 22:14:21 +00006250#ifdef Py_UNICODE_WIDE
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006251 ch > 0x10ffff ||
Benjamin Peterson29060642009-01-31 22:14:21 +00006252#endif
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006253 end-s < Py_UNICODE_SIZE
6254 )
Benjamin Peterson29060642009-01-31 22:14:21 +00006255 {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006256 startinpos = s - starts;
6257 if (end-s < Py_UNICODE_SIZE) {
6258 endinpos = end-starts;
6259 reason = "truncated input";
6260 }
6261 else {
6262 endinpos = s - starts + Py_UNICODE_SIZE;
6263 reason = "illegal code point (> 0x10FFFF)";
6264 }
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006265 if (unicode_decode_call_errorhandler(
6266 errors, &errorHandler,
6267 "unicode_internal", reason,
Walter Dörwalde78178e2007-07-30 13:31:40 +00006268 &starts, &end, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006269 &v, &outpos)) {
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006270 goto onError;
6271 }
6272 }
6273 else {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006274 if (unicode_putchar(&v, &outpos, ch) < 0)
6275 goto onError;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006276 s += Py_UNICODE_SIZE;
6277 }
6278 }
6279
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006280 if (PyUnicode_Resize(&v, outpos) < 0)
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006281 goto onError;
6282 Py_XDECREF(errorHandler);
6283 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006284 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006285 return v;
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006286
Benjamin Peterson29060642009-01-31 22:14:21 +00006287 onError:
Walter Dörwalda47d1c02005-08-30 10:23:14 +00006288 Py_XDECREF(v);
6289 Py_XDECREF(errorHandler);
6290 Py_XDECREF(exc);
6291 return NULL;
6292}
6293
Guido van Rossumd57fd912000-03-10 22:53:23 +00006294/* --- Latin-1 Codec ------------------------------------------------------ */
6295
Alexander Belopolsky40018472011-02-26 01:02:56 +00006296PyObject *
6297PyUnicode_DecodeLatin1(const char *s,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006298 Py_ssize_t size,
6299 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006300{
Guido van Rossumd57fd912000-03-10 22:53:23 +00006301 /* Latin-1 is equivalent to the first 256 ordinals in Unicode. */
Victor Stinnere57b1c02011-09-28 22:20:48 +02006302 return _PyUnicode_FromUCS1((unsigned char*)s, size);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006303}
6304
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006305/* create or adjust a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006306static void
6307make_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006308 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006309 PyObject *unicode,
6310 Py_ssize_t startpos, Py_ssize_t endpos,
6311 const char *reason)
6312{
6313 if (*exceptionObject == NULL) {
6314 *exceptionObject = PyObject_CallFunction(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006315 PyExc_UnicodeEncodeError, "sOnns",
Martin v. Löwis9e816682011-11-02 12:45:42 +01006316 encoding, unicode, startpos, endpos, reason);
6317 }
6318 else {
6319 if (PyUnicodeEncodeError_SetStart(*exceptionObject, startpos))
6320 goto onError;
6321 if (PyUnicodeEncodeError_SetEnd(*exceptionObject, endpos))
6322 goto onError;
6323 if (PyUnicodeEncodeError_SetReason(*exceptionObject, reason))
6324 goto onError;
6325 return;
6326 onError:
6327 Py_DECREF(*exceptionObject);
6328 *exceptionObject = NULL;
6329 }
6330}
6331
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006332/* raises a UnicodeEncodeError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006333static void
6334raise_encode_exception(PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006335 const char *encoding,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006336 PyObject *unicode,
6337 Py_ssize_t startpos, Py_ssize_t endpos,
6338 const char *reason)
6339{
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006340 make_encode_exception(exceptionObject,
Martin v. Löwis9e816682011-11-02 12:45:42 +01006341 encoding, unicode, startpos, endpos, reason);
6342 if (*exceptionObject != NULL)
6343 PyCodec_StrictErrors(*exceptionObject);
6344}
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006345
6346/* error handling callback helper:
6347 build arguments, call the callback and check the arguments,
6348 put the result into newpos and return the replacement string, which
6349 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006350static PyObject *
6351unicode_encode_call_errorhandler(const char *errors,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006352 PyObject **errorHandler,
6353 const char *encoding, const char *reason,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006354 PyObject *unicode, PyObject **exceptionObject,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006355 Py_ssize_t startpos, Py_ssize_t endpos,
6356 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006357{
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006358 static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006359 Py_ssize_t len;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006360 PyObject *restuple;
6361 PyObject *resunicode;
6362
6363 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006364 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006365 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006366 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006367 }
6368
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006369 if (PyUnicode_READY(unicode) < 0)
6370 return NULL;
6371 len = PyUnicode_GET_LENGTH(unicode);
6372
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006373 make_encode_exception(exceptionObject,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006374 encoding, unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006375 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006376 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006377
6378 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00006379 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006380 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006381 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006382 if (!PyTuple_Check(restuple)) {
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006383 PyErr_SetString(PyExc_TypeError, &argparse[3]);
Benjamin Peterson29060642009-01-31 22:14:21 +00006384 Py_DECREF(restuple);
6385 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006386 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006387 if (!PyArg_ParseTuple(restuple, argparse,
Benjamin Peterson29060642009-01-31 22:14:21 +00006388 &resunicode, newpos)) {
6389 Py_DECREF(restuple);
6390 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006391 }
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006392 if (!PyUnicode_Check(resunicode) && !PyBytes_Check(resunicode)) {
6393 PyErr_SetString(PyExc_TypeError, &argparse[3]);
6394 Py_DECREF(restuple);
6395 return NULL;
6396 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006397 if (*newpos<0)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006398 *newpos = len + *newpos;
6399 if (*newpos<0 || *newpos>len) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006400 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
6401 Py_DECREF(restuple);
6402 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00006403 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006404 Py_INCREF(resunicode);
6405 Py_DECREF(restuple);
6406 return resunicode;
6407}
6408
Alexander Belopolsky40018472011-02-26 01:02:56 +00006409static PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006410unicode_encode_ucs1(PyObject *unicode,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006411 const char *errors,
Victor Stinnerfcd96532011-11-04 00:28:50 +01006412 unsigned int limit)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006413{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006414 /* input state */
6415 Py_ssize_t pos=0, size;
6416 int kind;
6417 void *data;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006418 /* output object */
6419 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006420 /* pointer into the output */
6421 char *str;
6422 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00006423 Py_ssize_t ressize;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00006424 const char *encoding = (limit == 256) ? "latin-1" : "ascii";
6425 const char *reason = (limit == 256) ? "ordinal not in range(256)" : "ordinal not in range(128)";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006426 PyObject *errorHandler = NULL;
6427 PyObject *exc = NULL;
6428 /* the following variable is used for caching string comparisons
6429 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
6430 int known_errorHandler = -1;
6431
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006432 if (PyUnicode_READY(unicode) < 0)
6433 return NULL;
6434 size = PyUnicode_GET_LENGTH(unicode);
6435 kind = PyUnicode_KIND(unicode);
6436 data = PyUnicode_DATA(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006437 /* allocate enough for a simple encoding without
6438 replacements, if we need more, we'll resize */
Guido van Rossum98297ee2007-11-06 21:34:58 +00006439 if (size == 0)
Christian Heimes72b710a2008-05-26 13:28:38 +00006440 return PyBytes_FromStringAndSize(NULL, 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006441 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006442 if (res == NULL)
Guido van Rossum98297ee2007-11-06 21:34:58 +00006443 return NULL;
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006444 str = PyBytes_AS_STRING(res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006445 ressize = size;
6446
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006447 while (pos < size) {
6448 Py_UCS4 c = PyUnicode_READ(kind, data, pos);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006449
Benjamin Peterson29060642009-01-31 22:14:21 +00006450 /* can we encode this? */
6451 if (c<limit) {
6452 /* no overflow check, because we know that the space is enough */
6453 *str++ = (char)c;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006454 ++pos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006455 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006456 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006457 Py_ssize_t requiredsize;
6458 PyObject *repunicode;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006459 Py_ssize_t repsize, newpos, respos, i;
Benjamin Peterson29060642009-01-31 22:14:21 +00006460 /* startpos for collecting unencodable chars */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006461 Py_ssize_t collstart = pos;
6462 Py_ssize_t collend = pos;
Benjamin Peterson29060642009-01-31 22:14:21 +00006463 /* find all unecodable characters */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006464 while ((collend < size) && (PyUnicode_READ(kind, data, collend)>=limit))
Benjamin Peterson29060642009-01-31 22:14:21 +00006465 ++collend;
6466 /* cache callback name lookup (if not done yet, i.e. it's the first error) */
6467 if (known_errorHandler==-1) {
6468 if ((errors==NULL) || (!strcmp(errors, "strict")))
6469 known_errorHandler = 1;
6470 else if (!strcmp(errors, "replace"))
6471 known_errorHandler = 2;
6472 else if (!strcmp(errors, "ignore"))
6473 known_errorHandler = 3;
6474 else if (!strcmp(errors, "xmlcharrefreplace"))
6475 known_errorHandler = 4;
6476 else
6477 known_errorHandler = 0;
6478 }
6479 switch (known_errorHandler) {
6480 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006481 raise_encode_exception(&exc, encoding, unicode, collstart, collend, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006482 goto onError;
6483 case 2: /* replace */
6484 while (collstart++<collend)
6485 *str++ = '?'; /* fall through */
6486 case 3: /* ignore */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006487 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006488 break;
6489 case 4: /* xmlcharrefreplace */
6490 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006491 /* determine replacement size */
6492 for (i = collstart, repsize = 0; i < collend; ++i) {
6493 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
6494 if (ch < 10)
Benjamin Peterson29060642009-01-31 22:14:21 +00006495 repsize += 2+1+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006496 else if (ch < 100)
Benjamin Peterson29060642009-01-31 22:14:21 +00006497 repsize += 2+2+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006498 else if (ch < 1000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006499 repsize += 2+3+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006500 else if (ch < 10000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006501 repsize += 2+4+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006502#ifndef Py_UNICODE_WIDE
Benjamin Peterson29060642009-01-31 22:14:21 +00006503 else
6504 repsize += 2+5+1;
Hye-Shik Chang40e95092003-12-22 01:31:13 +00006505#else
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006506 else if (ch < 100000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006507 repsize += 2+5+1;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006508 else if (ch < 1000000)
Benjamin Peterson29060642009-01-31 22:14:21 +00006509 repsize += 2+6+1;
6510 else
6511 repsize += 2+7+1;
Hye-Shik Chang4a264fb2003-12-19 01:59:56 +00006512#endif
Benjamin Peterson29060642009-01-31 22:14:21 +00006513 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006514 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006515 if (requiredsize > ressize) {
6516 if (requiredsize<2*ressize)
6517 requiredsize = 2*ressize;
6518 if (_PyBytes_Resize(&res, requiredsize))
6519 goto onError;
6520 str = PyBytes_AS_STRING(res) + respos;
6521 ressize = requiredsize;
6522 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006523 /* generate replacement */
6524 for (i = collstart; i < collend; ++i) {
6525 str += sprintf(str, "&#%d;", PyUnicode_READ(kind, data, i));
Benjamin Peterson29060642009-01-31 22:14:21 +00006526 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006527 pos = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00006528 break;
6529 default:
6530 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006531 encoding, reason, unicode, &exc,
6532 collstart, collend, &newpos);
6533 if (repunicode == NULL || (PyUnicode_Check(repunicode) &&
6534 PyUnicode_READY(repunicode) < 0))
Benjamin Peterson29060642009-01-31 22:14:21 +00006535 goto onError;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006536 if (PyBytes_Check(repunicode)) {
6537 /* Directly copy bytes result to output. */
6538 repsize = PyBytes_Size(repunicode);
6539 if (repsize > 1) {
6540 /* Make room for all additional bytes. */
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006541 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006542 if (_PyBytes_Resize(&res, ressize+repsize-1)) {
6543 Py_DECREF(repunicode);
6544 goto onError;
6545 }
Amaury Forgeot d'Arc84ec8d92009-06-29 22:36:49 +00006546 str = PyBytes_AS_STRING(res) + respos;
Martin v. Löwis011e8422009-05-05 04:43:17 +00006547 ressize += repsize-1;
6548 }
6549 memcpy(str, PyBytes_AsString(repunicode), repsize);
6550 str += repsize;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006551 pos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006552 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00006553 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00006554 }
Benjamin Peterson29060642009-01-31 22:14:21 +00006555 /* need more space? (at least enough for what we
6556 have+the replacement+the rest of the string, so
6557 we won't have to check space for encodable characters) */
6558 respos = str - PyBytes_AS_STRING(res);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006559 repsize = PyUnicode_GET_LENGTH(repunicode);
6560 requiredsize = respos+repsize+(size-collend);
Benjamin Peterson29060642009-01-31 22:14:21 +00006561 if (requiredsize > ressize) {
6562 if (requiredsize<2*ressize)
6563 requiredsize = 2*ressize;
6564 if (_PyBytes_Resize(&res, requiredsize)) {
6565 Py_DECREF(repunicode);
6566 goto onError;
6567 }
6568 str = PyBytes_AS_STRING(res) + respos;
6569 ressize = requiredsize;
6570 }
6571 /* check if there is anything unencodable in the replacement
6572 and copy it to the output */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006573 for (i = 0; repsize-->0; ++i, ++str) {
6574 c = PyUnicode_READ_CHAR(repunicode, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00006575 if (c >= limit) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01006576 raise_encode_exception(&exc, encoding, unicode,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006577 pos, pos+1, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00006578 Py_DECREF(repunicode);
6579 goto onError;
6580 }
6581 *str = (char)c;
6582 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006583 pos = newpos;
Benjamin Peterson14339b62009-01-31 16:36:08 +00006584 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00006585 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00006586 }
6587 }
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006588 /* Resize if we allocated to much */
6589 size = str - PyBytes_AS_STRING(res);
6590 if (size < ressize) { /* If this falls res will be NULL */
Alexandre Vassalottibad1b922008-12-27 09:49:09 +00006591 assert(size >= 0);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006592 if (_PyBytes_Resize(&res, size) < 0)
6593 goto onError;
6594 }
6595
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006596 Py_XDECREF(errorHandler);
6597 Py_XDECREF(exc);
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00006598 return res;
6599
6600 onError:
6601 Py_XDECREF(res);
6602 Py_XDECREF(errorHandler);
6603 Py_XDECREF(exc);
6604 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006605}
6606
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006607/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006608PyObject *
6609PyUnicode_EncodeLatin1(const Py_UNICODE *p,
Ezio Melotti2aa2b3b2011-09-29 00:58:57 +03006610 Py_ssize_t size,
6611 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006612{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006613 PyObject *result;
6614 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6615 if (unicode == NULL)
6616 return NULL;
6617 result = unicode_encode_ucs1(unicode, errors, 256);
6618 Py_DECREF(unicode);
6619 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006620}
6621
Alexander Belopolsky40018472011-02-26 01:02:56 +00006622PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006623_PyUnicode_AsLatin1String(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006624{
6625 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006626 PyErr_BadArgument();
6627 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006628 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006629 if (PyUnicode_READY(unicode) == -1)
6630 return NULL;
6631 /* Fast path: if it is a one-byte string, construct
6632 bytes object directly. */
6633 if (PyUnicode_KIND(unicode) == PyUnicode_1BYTE_KIND)
6634 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6635 PyUnicode_GET_LENGTH(unicode));
6636 /* Non-Latin-1 characters present. Defer to above function to
6637 raise the exception. */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006638 return unicode_encode_ucs1(unicode, errors, 256);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006639}
6640
6641PyObject*
6642PyUnicode_AsLatin1String(PyObject *unicode)
6643{
6644 return _PyUnicode_AsLatin1String(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006645}
6646
6647/* --- 7-bit ASCII Codec -------------------------------------------------- */
6648
Alexander Belopolsky40018472011-02-26 01:02:56 +00006649PyObject *
6650PyUnicode_DecodeASCII(const char *s,
6651 Py_ssize_t size,
6652 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006653{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006654 const char *starts = s;
Victor Stinner7931d9a2011-11-04 00:22:48 +01006655 PyObject *v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006656 int kind;
6657 void *data;
Martin v. Löwis18e16552006-02-15 17:27:45 +00006658 Py_ssize_t startinpos;
6659 Py_ssize_t endinpos;
6660 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006661 const char *e;
Victor Stinner702c7342011-10-05 13:50:52 +02006662 int has_error;
6663 const unsigned char *p = (const unsigned char *)s;
6664 const unsigned char *end = p + size;
6665 const unsigned char *aligned_end = (const unsigned char *) ((size_t) end & ~LONG_PTR_MASK);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006666 PyObject *errorHandler = NULL;
6667 PyObject *exc = NULL;
Tim Petersced69f82003-09-16 20:30:58 +00006668
Guido van Rossumd57fd912000-03-10 22:53:23 +00006669 /* ASCII is equivalent to the first 128 ordinals in Unicode. */
Victor Stinner702c7342011-10-05 13:50:52 +02006670 if (size == 1 && (unsigned char)s[0] < 128)
6671 return get_latin1_char((unsigned char)s[0]);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006672
Victor Stinner702c7342011-10-05 13:50:52 +02006673 has_error = 0;
6674 while (p < end && !has_error) {
6675 /* Fast path, see below in PyUnicode_DecodeUTF8Stateful for
6676 an explanation. */
6677 if (!((size_t) p & LONG_PTR_MASK)) {
6678 /* Help register allocation */
6679 register const unsigned char *_p = p;
6680 while (_p < aligned_end) {
6681 unsigned long value = *(unsigned long *) _p;
6682 if (value & ASCII_CHAR_MASK) {
6683 has_error = 1;
6684 break;
6685 }
6686 _p += SIZEOF_LONG;
6687 }
6688 if (_p == end)
6689 break;
6690 if (has_error)
6691 break;
6692 p = _p;
6693 }
6694 if (*p & 0x80) {
6695 has_error = 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006696 break;
Victor Stinner702c7342011-10-05 13:50:52 +02006697 }
6698 else {
6699 ++p;
6700 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00006701 }
Victor Stinner702c7342011-10-05 13:50:52 +02006702 if (!has_error)
6703 return unicode_fromascii((const unsigned char *)s, size);
Tim Petersced69f82003-09-16 20:30:58 +00006704
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006705 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006706 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00006707 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006708 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01006709 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006710 kind = PyUnicode_KIND(v);
6711 data = PyUnicode_DATA(v);
6712 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006713 e = s + size;
6714 while (s < e) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006715 register unsigned char c = (unsigned char)*s;
6716 if (c < 128) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006717 PyUnicode_WRITE(kind, data, outpos++, c);
Benjamin Peterson29060642009-01-31 22:14:21 +00006718 ++s;
6719 }
6720 else {
6721 startinpos = s-starts;
6722 endinpos = startinpos + 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00006723 if (unicode_decode_call_errorhandler(
6724 errors, &errorHandler,
6725 "ascii", "ordinal not in range(128)",
6726 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006727 &v, &outpos))
Benjamin Peterson29060642009-01-31 22:14:21 +00006728 goto onError;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006729 kind = PyUnicode_KIND(v);
6730 data = PyUnicode_DATA(v);
Benjamin Peterson29060642009-01-31 22:14:21 +00006731 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00006732 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01006733 if (PyUnicode_Resize(&v, outpos) < 0)
6734 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006735 Py_XDECREF(errorHandler);
6736 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02006737 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01006738 return v;
Tim Petersced69f82003-09-16 20:30:58 +00006739
Benjamin Peterson29060642009-01-31 22:14:21 +00006740 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00006741 Py_XDECREF(v);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00006742 Py_XDECREF(errorHandler);
6743 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006744 return NULL;
6745}
6746
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006747/* Deprecated */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006748PyObject *
6749PyUnicode_EncodeASCII(const Py_UNICODE *p,
6750 Py_ssize_t size,
6751 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006752{
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006753 PyObject *result;
6754 PyObject *unicode = PyUnicode_FromUnicode(p, size);
6755 if (unicode == NULL)
6756 return NULL;
6757 result = unicode_encode_ucs1(unicode, errors, 128);
6758 Py_DECREF(unicode);
6759 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006760}
6761
Alexander Belopolsky40018472011-02-26 01:02:56 +00006762PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006763_PyUnicode_AsASCIIString(PyObject *unicode, const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00006764{
6765 if (!PyUnicode_Check(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006766 PyErr_BadArgument();
6767 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00006768 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006769 if (PyUnicode_READY(unicode) == -1)
6770 return NULL;
6771 /* Fast path: if it is an ASCII-only string, construct bytes object
6772 directly. Else defer to above function to raise the exception. */
6773 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
6774 return PyBytes_FromStringAndSize(PyUnicode_DATA(unicode),
6775 PyUnicode_GET_LENGTH(unicode));
Martin v. Löwis23e275b2011-11-02 18:02:51 +01006776 return unicode_encode_ucs1(unicode, errors, 128);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02006777}
6778
6779PyObject *
6780PyUnicode_AsASCIIString(PyObject *unicode)
6781{
6782 return _PyUnicode_AsASCIIString(unicode, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00006783}
6784
Victor Stinner99b95382011-07-04 14:23:54 +02006785#ifdef HAVE_MBCS
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006786
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00006787/* --- MBCS codecs for Windows -------------------------------------------- */
Guido van Rossum2ea3e142000-03-31 17:24:09 +00006788
Hirokazu Yamamoto35302462009-03-21 13:23:27 +00006789#if SIZEOF_INT < SIZEOF_SIZE_T
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006790#define NEED_RETRY
6791#endif
6792
Victor Stinner3a50e702011-10-18 21:21:00 +02006793#ifndef WC_ERR_INVALID_CHARS
6794# define WC_ERR_INVALID_CHARS 0x0080
6795#endif
6796
6797static char*
6798code_page_name(UINT code_page, PyObject **obj)
6799{
6800 *obj = NULL;
6801 if (code_page == CP_ACP)
6802 return "mbcs";
6803 if (code_page == CP_UTF7)
6804 return "CP_UTF7";
6805 if (code_page == CP_UTF8)
6806 return "CP_UTF8";
6807
6808 *obj = PyBytes_FromFormat("cp%u", code_page);
6809 if (*obj == NULL)
6810 return NULL;
6811 return PyBytes_AS_STRING(*obj);
6812}
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006813
Alexander Belopolsky40018472011-02-26 01:02:56 +00006814static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006815is_dbcs_lead_byte(UINT code_page, const char *s, int offset)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006816{
6817 const char *curr = s + offset;
Victor Stinner3a50e702011-10-18 21:21:00 +02006818 const char *prev;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006819
Victor Stinner3a50e702011-10-18 21:21:00 +02006820 if (!IsDBCSLeadByteEx(code_page, *curr))
6821 return 0;
6822
6823 prev = CharPrevExA(code_page, s, curr, 0);
6824 if (prev == curr)
6825 return 1;
6826 /* FIXME: This code is limited to "true" double-byte encodings,
6827 as it assumes an incomplete character consists of a single
6828 byte. */
6829 if (curr - prev == 2)
6830 return 1;
6831 if (!IsDBCSLeadByteEx(code_page, *prev))
6832 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006833 return 0;
6834}
6835
Victor Stinner3a50e702011-10-18 21:21:00 +02006836static DWORD
6837decode_code_page_flags(UINT code_page)
6838{
6839 if (code_page == CP_UTF7) {
6840 /* The CP_UTF7 decoder only supports flags=0 */
6841 return 0;
6842 }
6843 else
6844 return MB_ERR_INVALID_CHARS;
6845}
6846
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006847/*
Victor Stinner3a50e702011-10-18 21:21:00 +02006848 * Decode a byte string from a Windows code page into unicode object in strict
6849 * mode.
6850 *
6851 * Returns consumed size if succeed, returns -2 on decode error, or raise a
6852 * WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006853 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00006854static int
Victor Stinner3a50e702011-10-18 21:21:00 +02006855decode_code_page_strict(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006856 PyObject **v,
Victor Stinner3a50e702011-10-18 21:21:00 +02006857 const char *in,
6858 int insize)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006859{
Victor Stinner3a50e702011-10-18 21:21:00 +02006860 const DWORD flags = decode_code_page_flags(code_page);
6861 Py_UNICODE *out;
6862 DWORD outsize;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006863
6864 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02006865 assert(insize > 0);
6866 outsize = MultiByteToWideChar(code_page, flags, in, insize, NULL, 0);
6867 if (outsize <= 0)
6868 goto error;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006869
6870 if (*v == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00006871 /* Create unicode object */
Victor Stinner76a31a62011-11-04 00:05:13 +01006872 *v = (PyObject*)_PyUnicode_New(outsize);
Benjamin Peterson29060642009-01-31 22:14:21 +00006873 if (*v == NULL)
6874 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006875 out = PyUnicode_AS_UNICODE(*v);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006876 }
6877 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00006878 /* Extend unicode object */
Victor Stinner3a50e702011-10-18 21:21:00 +02006879 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
Victor Stinner76a31a62011-11-04 00:05:13 +01006880 if (PyUnicode_Resize(v, n + outsize) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00006881 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02006882 out = PyUnicode_AS_UNICODE(*v) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006883 }
6884
6885 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02006886 outsize = MultiByteToWideChar(code_page, flags, in, insize, out, outsize);
6887 if (outsize <= 0)
6888 goto error;
6889 return insize;
Victor Stinner554f3f02010-06-16 23:33:54 +00006890
Victor Stinner3a50e702011-10-18 21:21:00 +02006891error:
6892 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
6893 return -2;
6894 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00006895 return -1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006896}
6897
Victor Stinner3a50e702011-10-18 21:21:00 +02006898/*
6899 * Decode a byte string from a code page into unicode object with an error
6900 * handler.
6901 *
6902 * Returns consumed size if succeed, or raise a WindowsError or
6903 * UnicodeDecodeError exception and returns -1 on error.
6904 */
6905static int
6906decode_code_page_errors(UINT code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01006907 PyObject **v,
6908 const char *in, const int size,
Victor Stinner3a50e702011-10-18 21:21:00 +02006909 const char *errors)
6910{
6911 const char *startin = in;
6912 const char *endin = in + size;
6913 const DWORD flags = decode_code_page_flags(code_page);
6914 /* Ideally, we should get reason from FormatMessage. This is the Windows
6915 2000 English version of the message. */
6916 const char *reason = "No mapping for the Unicode character exists "
6917 "in the target code page.";
6918 /* each step cannot decode more than 1 character, but a character can be
6919 represented as a surrogate pair */
6920 wchar_t buffer[2], *startout, *out;
6921 int insize, outsize;
6922 PyObject *errorHandler = NULL;
6923 PyObject *exc = NULL;
6924 PyObject *encoding_obj = NULL;
6925 char *encoding;
6926 DWORD err;
6927 int ret = -1;
6928
6929 assert(size > 0);
6930
6931 encoding = code_page_name(code_page, &encoding_obj);
6932 if (encoding == NULL)
6933 return -1;
6934
6935 if (errors == NULL || strcmp(errors, "strict") == 0) {
6936 /* The last error was ERROR_NO_UNICODE_TRANSLATION, then we raise a
6937 UnicodeDecodeError. */
6938 make_decode_exception(&exc, encoding, in, size, 0, 0, reason);
6939 if (exc != NULL) {
6940 PyCodec_StrictErrors(exc);
6941 Py_CLEAR(exc);
6942 }
6943 goto error;
6944 }
6945
6946 if (*v == NULL) {
6947 /* Create unicode object */
6948 if (size > PY_SSIZE_T_MAX / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6949 PyErr_NoMemory();
6950 goto error;
6951 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006952 *v = (PyObject*)_PyUnicode_New(size * Py_ARRAY_LENGTH(buffer));
Victor Stinner3a50e702011-10-18 21:21:00 +02006953 if (*v == NULL)
6954 goto error;
6955 startout = PyUnicode_AS_UNICODE(*v);
6956 }
6957 else {
6958 /* Extend unicode object */
6959 Py_ssize_t n = PyUnicode_GET_SIZE(*v);
6960 if (size > (PY_SSIZE_T_MAX - n) / (Py_ssize_t)Py_ARRAY_LENGTH(buffer)) {
6961 PyErr_NoMemory();
6962 goto error;
6963 }
Victor Stinner76a31a62011-11-04 00:05:13 +01006964 if (PyUnicode_Resize(v, n + size * Py_ARRAY_LENGTH(buffer)) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02006965 goto error;
6966 startout = PyUnicode_AS_UNICODE(*v) + n;
6967 }
6968
6969 /* Decode the byte string character per character */
6970 out = startout;
6971 while (in < endin)
6972 {
6973 /* Decode a character */
6974 insize = 1;
6975 do
6976 {
6977 outsize = MultiByteToWideChar(code_page, flags,
6978 in, insize,
6979 buffer, Py_ARRAY_LENGTH(buffer));
6980 if (outsize > 0)
6981 break;
6982 err = GetLastError();
6983 if (err != ERROR_NO_UNICODE_TRANSLATION
6984 && err != ERROR_INSUFFICIENT_BUFFER)
6985 {
6986 PyErr_SetFromWindowsErr(0);
6987 goto error;
6988 }
6989 insize++;
6990 }
6991 /* 4=maximum length of a UTF-8 sequence */
6992 while (insize <= 4 && (in + insize) <= endin);
6993
6994 if (outsize <= 0) {
6995 Py_ssize_t startinpos, endinpos, outpos;
6996
6997 startinpos = in - startin;
6998 endinpos = startinpos + 1;
6999 outpos = out - PyUnicode_AS_UNICODE(*v);
7000 if (unicode_decode_call_errorhandler(
7001 errors, &errorHandler,
7002 encoding, reason,
7003 &startin, &endin, &startinpos, &endinpos, &exc, &in,
Victor Stinner596a6c42011-11-09 00:02:18 +01007004 v, &outpos))
Victor Stinner3a50e702011-10-18 21:21:00 +02007005 {
7006 goto error;
7007 }
Victor Stinner596a6c42011-11-09 00:02:18 +01007008 out = PyUnicode_AS_UNICODE(*v) + outpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007009 }
7010 else {
7011 in += insize;
7012 memcpy(out, buffer, outsize * sizeof(wchar_t));
7013 out += outsize;
7014 }
7015 }
7016
7017 /* write a NUL character at the end */
7018 *out = 0;
7019
7020 /* Extend unicode object */
7021 outsize = out - startout;
7022 assert(outsize <= PyUnicode_WSTR_LENGTH(*v));
Victor Stinner76a31a62011-11-04 00:05:13 +01007023 if (PyUnicode_Resize(v, outsize) < 0)
Victor Stinner3a50e702011-10-18 21:21:00 +02007024 goto error;
Victor Stinner76a31a62011-11-04 00:05:13 +01007025 ret = size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007026
7027error:
7028 Py_XDECREF(encoding_obj);
7029 Py_XDECREF(errorHandler);
7030 Py_XDECREF(exc);
7031 return ret;
7032}
7033
Victor Stinner3a50e702011-10-18 21:21:00 +02007034static PyObject *
7035decode_code_page_stateful(int code_page,
Victor Stinner76a31a62011-11-04 00:05:13 +01007036 const char *s, Py_ssize_t size,
7037 const char *errors, Py_ssize_t *consumed)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007038{
Victor Stinner76a31a62011-11-04 00:05:13 +01007039 PyObject *v = NULL;
7040 int chunk_size, final, converted, done;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007041
Victor Stinner3a50e702011-10-18 21:21:00 +02007042 if (code_page < 0) {
7043 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7044 return NULL;
7045 }
7046
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007047 if (consumed)
Benjamin Peterson29060642009-01-31 22:14:21 +00007048 *consumed = 0;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007049
Victor Stinner76a31a62011-11-04 00:05:13 +01007050 do
7051 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007052#ifdef NEED_RETRY
Victor Stinner76a31a62011-11-04 00:05:13 +01007053 if (size > INT_MAX) {
7054 chunk_size = INT_MAX;
7055 final = 0;
7056 done = 0;
7057 }
7058 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007059#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007060 {
7061 chunk_size = (int)size;
7062 final = (consumed == NULL);
7063 done = 1;
7064 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007065
Victor Stinner76a31a62011-11-04 00:05:13 +01007066 /* Skip trailing lead-byte unless 'final' is set */
7067 if (!final && is_dbcs_lead_byte(code_page, s, chunk_size - 1))
7068 --chunk_size;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007069
Victor Stinner76a31a62011-11-04 00:05:13 +01007070 if (chunk_size == 0 && done) {
7071 if (v != NULL)
7072 break;
7073 Py_INCREF(unicode_empty);
7074 return unicode_empty;
7075 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007076
Victor Stinner76a31a62011-11-04 00:05:13 +01007077
7078 converted = decode_code_page_strict(code_page, &v,
7079 s, chunk_size);
7080 if (converted == -2)
7081 converted = decode_code_page_errors(code_page, &v,
7082 s, chunk_size,
7083 errors);
7084 assert(converted != 0);
7085
7086 if (converted < 0) {
7087 Py_XDECREF(v);
7088 return NULL;
7089 }
7090
7091 if (consumed)
7092 *consumed += converted;
7093
7094 s += converted;
7095 size -= converted;
7096 } while (!done);
Victor Stinner3a50e702011-10-18 21:21:00 +02007097
Victor Stinner17efeed2011-10-04 20:05:46 +02007098#ifndef DONT_MAKE_RESULT_READY
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02007099 if (_PyUnicode_READY_REPLACE(&v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007100 Py_DECREF(v);
7101 return NULL;
7102 }
Victor Stinner17efeed2011-10-04 20:05:46 +02007103#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007104 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner76a31a62011-11-04 00:05:13 +01007105 return v;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007106}
7107
Alexander Belopolsky40018472011-02-26 01:02:56 +00007108PyObject *
Victor Stinner3a50e702011-10-18 21:21:00 +02007109PyUnicode_DecodeCodePageStateful(int code_page,
7110 const char *s,
7111 Py_ssize_t size,
7112 const char *errors,
7113 Py_ssize_t *consumed)
7114{
7115 return decode_code_page_stateful(code_page, s, size, errors, consumed);
7116}
7117
7118PyObject *
7119PyUnicode_DecodeMBCSStateful(const char *s,
7120 Py_ssize_t size,
7121 const char *errors,
7122 Py_ssize_t *consumed)
7123{
7124 return decode_code_page_stateful(CP_ACP, s, size, errors, consumed);
7125}
7126
7127PyObject *
Alexander Belopolsky40018472011-02-26 01:02:56 +00007128PyUnicode_DecodeMBCS(const char *s,
7129 Py_ssize_t size,
7130 const char *errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007131{
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007132 return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
7133}
7134
Victor Stinner3a50e702011-10-18 21:21:00 +02007135static DWORD
7136encode_code_page_flags(UINT code_page, const char *errors)
7137{
7138 if (code_page == CP_UTF8) {
7139 if (winver.dwMajorVersion >= 6)
7140 /* CP_UTF8 supports WC_ERR_INVALID_CHARS on Windows Vista
7141 and later */
7142 return WC_ERR_INVALID_CHARS;
7143 else
7144 /* CP_UTF8 only supports flags=0 on Windows older than Vista */
7145 return 0;
7146 }
7147 else if (code_page == CP_UTF7) {
7148 /* CP_UTF7 only supports flags=0 */
7149 return 0;
7150 }
7151 else {
7152 if (errors != NULL && strcmp(errors, "replace") == 0)
7153 return 0;
7154 else
7155 return WC_NO_BEST_FIT_CHARS;
7156 }
7157}
7158
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007159/*
Victor Stinner3a50e702011-10-18 21:21:00 +02007160 * Encode a Unicode string to a Windows code page into a byte string in strict
7161 * mode.
7162 *
7163 * Returns consumed characters if succeed, returns -2 on encode error, or raise
7164 * a WindowsError and returns -1 on other error.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007165 */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007166static int
Victor Stinner3a50e702011-10-18 21:21:00 +02007167encode_code_page_strict(UINT code_page, PyObject **outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007168 PyObject *unicode, Py_ssize_t offset, int len,
Victor Stinner3a50e702011-10-18 21:21:00 +02007169 const char* errors)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007170{
Victor Stinner554f3f02010-06-16 23:33:54 +00007171 BOOL usedDefaultChar = FALSE;
Victor Stinner3a50e702011-10-18 21:21:00 +02007172 BOOL *pusedDefaultChar = &usedDefaultChar;
7173 int outsize;
Victor Stinner554f3f02010-06-16 23:33:54 +00007174 PyObject *exc = NULL;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007175 Py_UNICODE *p;
7176 Py_ssize_t size;
Victor Stinner3a50e702011-10-18 21:21:00 +02007177 const DWORD flags = encode_code_page_flags(code_page, NULL);
7178 char *out;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007179 /* Create a substring so that we can get the UTF-16 representation
7180 of just the slice under consideration. */
7181 PyObject *substring;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007182
Martin v. Löwis3d325192011-11-04 18:23:06 +01007183 assert(len > 0);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007184
Victor Stinner3a50e702011-10-18 21:21:00 +02007185 if (code_page != CP_UTF8 && code_page != CP_UTF7)
Victor Stinner554f3f02010-06-16 23:33:54 +00007186 pusedDefaultChar = &usedDefaultChar;
Victor Stinner3a50e702011-10-18 21:21:00 +02007187 else
Victor Stinner554f3f02010-06-16 23:33:54 +00007188 pusedDefaultChar = NULL;
Victor Stinner554f3f02010-06-16 23:33:54 +00007189
Victor Stinner2fc507f2011-11-04 20:06:39 +01007190 substring = PyUnicode_Substring(unicode, offset, offset+len);
7191 if (substring == NULL)
7192 return -1;
7193 p = PyUnicode_AsUnicodeAndSize(substring, &size);
7194 if (p == NULL) {
7195 Py_DECREF(substring);
7196 return -1;
7197 }
Martin v. Löwis3d325192011-11-04 18:23:06 +01007198
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007199 /* First get the size of the result */
Victor Stinner3a50e702011-10-18 21:21:00 +02007200 outsize = WideCharToMultiByte(code_page, flags,
7201 p, size,
7202 NULL, 0,
7203 NULL, pusedDefaultChar);
7204 if (outsize <= 0)
7205 goto error;
7206 /* If we used a default char, then we failed! */
Victor Stinner2fc507f2011-11-04 20:06:39 +01007207 if (pusedDefaultChar && *pusedDefaultChar) {
7208 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007209 return -2;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007210 }
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007211
Victor Stinner3a50e702011-10-18 21:21:00 +02007212 if (*outbytes == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007213 /* Create string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007214 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007215 if (*outbytes == NULL) {
7216 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007217 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007218 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007219 out = PyBytes_AS_STRING(*outbytes);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007220 }
7221 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007222 /* Extend string object */
Victor Stinner3a50e702011-10-18 21:21:00 +02007223 const Py_ssize_t n = PyBytes_Size(*outbytes);
7224 if (outsize > PY_SSIZE_T_MAX - n) {
7225 PyErr_NoMemory();
Victor Stinner2fc507f2011-11-04 20:06:39 +01007226 Py_DECREF(substring);
Benjamin Peterson29060642009-01-31 22:14:21 +00007227 return -1;
Victor Stinner3a50e702011-10-18 21:21:00 +02007228 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007229 if (_PyBytes_Resize(outbytes, n + outsize) < 0) {
7230 Py_DECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007231 return -1;
Victor Stinner2fc507f2011-11-04 20:06:39 +01007232 }
Victor Stinner3a50e702011-10-18 21:21:00 +02007233 out = PyBytes_AS_STRING(*outbytes) + n;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007234 }
7235
7236 /* Do the conversion */
Victor Stinner3a50e702011-10-18 21:21:00 +02007237 outsize = WideCharToMultiByte(code_page, flags,
7238 p, size,
7239 out, outsize,
7240 NULL, pusedDefaultChar);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007241 Py_CLEAR(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007242 if (outsize <= 0)
7243 goto error;
7244 if (pusedDefaultChar && *pusedDefaultChar)
7245 return -2;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007246 return 0;
Victor Stinner554f3f02010-06-16 23:33:54 +00007247
Victor Stinner3a50e702011-10-18 21:21:00 +02007248error:
Victor Stinner2fc507f2011-11-04 20:06:39 +01007249 Py_XDECREF(substring);
Victor Stinner3a50e702011-10-18 21:21:00 +02007250 if (GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
7251 return -2;
7252 PyErr_SetFromWindowsErr(0);
Victor Stinner554f3f02010-06-16 23:33:54 +00007253 return -1;
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007254}
7255
Victor Stinner3a50e702011-10-18 21:21:00 +02007256/*
7257 * Encode a Unicode string to a Windows code page into a byte string using a
7258 * error handler.
7259 *
7260 * Returns consumed characters if succeed, or raise a WindowsError and returns
7261 * -1 on other error.
7262 */
7263static int
7264encode_code_page_errors(UINT code_page, PyObject **outbytes,
Victor Stinner7581cef2011-11-03 22:32:33 +01007265 PyObject *unicode, Py_ssize_t unicode_offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007266 Py_ssize_t insize, const char* errors)
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007267{
Victor Stinner3a50e702011-10-18 21:21:00 +02007268 const DWORD flags = encode_code_page_flags(code_page, errors);
Victor Stinner2fc507f2011-11-04 20:06:39 +01007269 Py_ssize_t pos = unicode_offset;
7270 Py_ssize_t endin = unicode_offset + insize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007271 /* Ideally, we should get reason from FormatMessage. This is the Windows
7272 2000 English version of the message. */
7273 const char *reason = "invalid character";
7274 /* 4=maximum length of a UTF-8 sequence */
7275 char buffer[4];
7276 BOOL usedDefaultChar = FALSE, *pusedDefaultChar;
7277 Py_ssize_t outsize;
7278 char *out;
Victor Stinner3a50e702011-10-18 21:21:00 +02007279 PyObject *errorHandler = NULL;
7280 PyObject *exc = NULL;
7281 PyObject *encoding_obj = NULL;
7282 char *encoding;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007283 Py_ssize_t newpos, newoutsize;
Victor Stinner3a50e702011-10-18 21:21:00 +02007284 PyObject *rep;
7285 int ret = -1;
7286
7287 assert(insize > 0);
7288
7289 encoding = code_page_name(code_page, &encoding_obj);
7290 if (encoding == NULL)
7291 return -1;
7292
7293 if (errors == NULL || strcmp(errors, "strict") == 0) {
7294 /* The last error was ERROR_NO_UNICODE_TRANSLATION,
7295 then we raise a UnicodeEncodeError. */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007296 make_encode_exception(&exc, encoding, unicode, 0, 0, reason);
Victor Stinner3a50e702011-10-18 21:21:00 +02007297 if (exc != NULL) {
7298 PyCodec_StrictErrors(exc);
7299 Py_DECREF(exc);
7300 }
7301 Py_XDECREF(encoding_obj);
7302 return -1;
7303 }
7304
7305 if (code_page != CP_UTF8 && code_page != CP_UTF7)
7306 pusedDefaultChar = &usedDefaultChar;
7307 else
7308 pusedDefaultChar = NULL;
7309
7310 if (Py_ARRAY_LENGTH(buffer) > PY_SSIZE_T_MAX / insize) {
7311 PyErr_NoMemory();
7312 goto error;
7313 }
7314 outsize = insize * Py_ARRAY_LENGTH(buffer);
7315
7316 if (*outbytes == NULL) {
7317 /* Create string object */
7318 *outbytes = PyBytes_FromStringAndSize(NULL, outsize);
7319 if (*outbytes == NULL)
7320 goto error;
7321 out = PyBytes_AS_STRING(*outbytes);
7322 }
7323 else {
7324 /* Extend string object */
7325 Py_ssize_t n = PyBytes_Size(*outbytes);
7326 if (n > PY_SSIZE_T_MAX - outsize) {
7327 PyErr_NoMemory();
7328 goto error;
7329 }
7330 if (_PyBytes_Resize(outbytes, n + outsize) < 0)
7331 goto error;
7332 out = PyBytes_AS_STRING(*outbytes) + n;
7333 }
7334
7335 /* Encode the string character per character */
Martin v. Löwis3d325192011-11-04 18:23:06 +01007336 while (pos < endin)
Victor Stinner3a50e702011-10-18 21:21:00 +02007337 {
Victor Stinner2fc507f2011-11-04 20:06:39 +01007338 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, pos);
7339 wchar_t chars[2];
7340 int charsize;
7341 if (ch < 0x10000) {
7342 chars[0] = (wchar_t)ch;
7343 charsize = 1;
7344 }
7345 else {
7346 ch -= 0x10000;
7347 chars[0] = 0xd800 + (ch >> 10);
7348 chars[1] = 0xdc00 + (ch & 0x3ff);
7349 charsize = 2;
7350 }
7351
Victor Stinner3a50e702011-10-18 21:21:00 +02007352 outsize = WideCharToMultiByte(code_page, flags,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007353 chars, charsize,
Victor Stinner3a50e702011-10-18 21:21:00 +02007354 buffer, Py_ARRAY_LENGTH(buffer),
7355 NULL, pusedDefaultChar);
7356 if (outsize > 0) {
7357 if (pusedDefaultChar == NULL || !(*pusedDefaultChar))
7358 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007359 pos++;
Victor Stinner3a50e702011-10-18 21:21:00 +02007360 memcpy(out, buffer, outsize);
7361 out += outsize;
7362 continue;
7363 }
7364 }
7365 else if (GetLastError() != ERROR_NO_UNICODE_TRANSLATION) {
7366 PyErr_SetFromWindowsErr(0);
7367 goto error;
7368 }
7369
Victor Stinner3a50e702011-10-18 21:21:00 +02007370 rep = unicode_encode_call_errorhandler(
7371 errors, &errorHandler, encoding, reason,
Victor Stinner7581cef2011-11-03 22:32:33 +01007372 unicode, &exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007373 pos, pos + 1, &newpos);
Victor Stinner3a50e702011-10-18 21:21:00 +02007374 if (rep == NULL)
7375 goto error;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007376 pos = newpos;
Victor Stinner3a50e702011-10-18 21:21:00 +02007377
7378 if (PyBytes_Check(rep)) {
7379 outsize = PyBytes_GET_SIZE(rep);
7380 if (outsize != 1) {
7381 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7382 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7383 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7384 Py_DECREF(rep);
7385 goto error;
7386 }
7387 out = PyBytes_AS_STRING(*outbytes) + offset;
7388 }
7389 memcpy(out, PyBytes_AS_STRING(rep), outsize);
7390 out += outsize;
7391 }
7392 else {
7393 Py_ssize_t i;
7394 enum PyUnicode_Kind kind;
7395 void *data;
7396
7397 if (PyUnicode_READY(rep) < 0) {
7398 Py_DECREF(rep);
7399 goto error;
7400 }
7401
7402 outsize = PyUnicode_GET_LENGTH(rep);
7403 if (outsize != 1) {
7404 Py_ssize_t offset = out - PyBytes_AS_STRING(*outbytes);
7405 newoutsize = PyBytes_GET_SIZE(*outbytes) + (outsize - 1);
7406 if (_PyBytes_Resize(outbytes, newoutsize) < 0) {
7407 Py_DECREF(rep);
7408 goto error;
7409 }
7410 out = PyBytes_AS_STRING(*outbytes) + offset;
7411 }
7412 kind = PyUnicode_KIND(rep);
7413 data = PyUnicode_DATA(rep);
7414 for (i=0; i < outsize; i++) {
7415 Py_UCS4 ch = PyUnicode_READ(kind, data, i);
7416 if (ch > 127) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01007417 raise_encode_exception(&exc,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007418 encoding, unicode,
7419 pos, pos + 1,
Victor Stinner3a50e702011-10-18 21:21:00 +02007420 "unable to encode error handler result to ASCII");
7421 Py_DECREF(rep);
7422 goto error;
7423 }
7424 *out = (unsigned char)ch;
7425 out++;
7426 }
7427 }
7428 Py_DECREF(rep);
7429 }
7430 /* write a NUL byte */
7431 *out = 0;
7432 outsize = out - PyBytes_AS_STRING(*outbytes);
7433 assert(outsize <= PyBytes_GET_SIZE(*outbytes));
7434 if (_PyBytes_Resize(outbytes, outsize) < 0)
7435 goto error;
7436 ret = 0;
7437
7438error:
7439 Py_XDECREF(encoding_obj);
7440 Py_XDECREF(errorHandler);
7441 Py_XDECREF(exc);
7442 return ret;
7443}
7444
Victor Stinner3a50e702011-10-18 21:21:00 +02007445static PyObject *
7446encode_code_page(int code_page,
Victor Stinner7581cef2011-11-03 22:32:33 +01007447 PyObject *unicode,
Victor Stinner3a50e702011-10-18 21:21:00 +02007448 const char *errors)
7449{
Martin v. Löwis3d325192011-11-04 18:23:06 +01007450 Py_ssize_t len;
Victor Stinner3a50e702011-10-18 21:21:00 +02007451 PyObject *outbytes = NULL;
Victor Stinner7581cef2011-11-03 22:32:33 +01007452 Py_ssize_t offset;
Victor Stinner76a31a62011-11-04 00:05:13 +01007453 int chunk_len, ret, done;
Victor Stinner7581cef2011-11-03 22:32:33 +01007454
Victor Stinner2fc507f2011-11-04 20:06:39 +01007455 if (PyUnicode_READY(unicode) < 0)
7456 return NULL;
7457 len = PyUnicode_GET_LENGTH(unicode);
Guido van Rossum03e29f12000-05-04 15:52:20 +00007458
Victor Stinner3a50e702011-10-18 21:21:00 +02007459 if (code_page < 0) {
7460 PyErr_SetString(PyExc_ValueError, "invalid code page number");
7461 return NULL;
7462 }
7463
Martin v. Löwis3d325192011-11-04 18:23:06 +01007464 if (len == 0)
Victor Stinner76a31a62011-11-04 00:05:13 +01007465 return PyBytes_FromStringAndSize(NULL, 0);
7466
Victor Stinner7581cef2011-11-03 22:32:33 +01007467 offset = 0;
7468 do
7469 {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007470#ifdef NEED_RETRY
Victor Stinner2fc507f2011-11-04 20:06:39 +01007471 /* UTF-16 encoding may double the size, so use only INT_MAX/2
Martin v. Löwis3d325192011-11-04 18:23:06 +01007472 chunks. */
7473 if (len > INT_MAX/2) {
7474 chunk_len = INT_MAX/2;
Victor Stinner76a31a62011-11-04 00:05:13 +01007475 done = 0;
7476 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007477 else
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007478#endif
Victor Stinner76a31a62011-11-04 00:05:13 +01007479 {
Martin v. Löwis3d325192011-11-04 18:23:06 +01007480 chunk_len = (int)len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007481 done = 1;
7482 }
Victor Stinner2fc507f2011-11-04 20:06:39 +01007483
Victor Stinner76a31a62011-11-04 00:05:13 +01007484 ret = encode_code_page_strict(code_page, &outbytes,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007485 unicode, offset, chunk_len,
Victor Stinner76a31a62011-11-04 00:05:13 +01007486 errors);
7487 if (ret == -2)
7488 ret = encode_code_page_errors(code_page, &outbytes,
7489 unicode, offset,
Martin v. Löwis3d325192011-11-04 18:23:06 +01007490 chunk_len, errors);
Victor Stinner7581cef2011-11-03 22:32:33 +01007491 if (ret < 0) {
7492 Py_XDECREF(outbytes);
7493 return NULL;
7494 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007495
Victor Stinner7581cef2011-11-03 22:32:33 +01007496 offset += chunk_len;
Martin v. Löwis3d325192011-11-04 18:23:06 +01007497 len -= chunk_len;
Victor Stinner76a31a62011-11-04 00:05:13 +01007498 } while (!done);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007499
Victor Stinner3a50e702011-10-18 21:21:00 +02007500 return outbytes;
7501}
7502
7503PyObject *
7504PyUnicode_EncodeMBCS(const Py_UNICODE *p,
7505 Py_ssize_t size,
7506 const char *errors)
7507{
Victor Stinner7581cef2011-11-03 22:32:33 +01007508 PyObject *unicode, *res;
7509 unicode = PyUnicode_FromUnicode(p, size);
7510 if (unicode == NULL)
7511 return NULL;
7512 res = encode_code_page(CP_ACP, unicode, errors);
7513 Py_DECREF(unicode);
7514 return res;
Victor Stinner3a50e702011-10-18 21:21:00 +02007515}
7516
7517PyObject *
7518PyUnicode_EncodeCodePage(int code_page,
7519 PyObject *unicode,
7520 const char *errors)
7521{
Victor Stinner7581cef2011-11-03 22:32:33 +01007522 return encode_code_page(code_page, unicode, errors);
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007523}
Guido van Rossum2ea3e142000-03-31 17:24:09 +00007524
Alexander Belopolsky40018472011-02-26 01:02:56 +00007525PyObject *
7526PyUnicode_AsMBCSString(PyObject *unicode)
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007527{
7528 if (!PyUnicode_Check(unicode)) {
7529 PyErr_BadArgument();
7530 return NULL;
7531 }
Victor Stinner7581cef2011-11-03 22:32:33 +01007532 return PyUnicode_EncodeCodePage(CP_ACP, unicode, NULL);
Mark Hammond0ccda1e2003-07-01 00:13:27 +00007533}
7534
Thomas Wouters0e3f5912006-08-11 14:57:12 +00007535#undef NEED_RETRY
7536
Victor Stinner99b95382011-07-04 14:23:54 +02007537#endif /* HAVE_MBCS */
Guido van Rossumb7a40ba2000-03-28 02:01:52 +00007538
Guido van Rossumd57fd912000-03-10 22:53:23 +00007539/* --- Character Mapping Codec -------------------------------------------- */
7540
Alexander Belopolsky40018472011-02-26 01:02:56 +00007541PyObject *
7542PyUnicode_DecodeCharmap(const char *s,
7543 Py_ssize_t size,
7544 PyObject *mapping,
7545 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007546{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007547 const char *starts = s;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007548 Py_ssize_t startinpos;
7549 Py_ssize_t endinpos;
7550 Py_ssize_t outpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007551 const char *e;
Victor Stinner7931d9a2011-11-04 00:22:48 +01007552 PyObject *v;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007553 Py_ssize_t extrachars = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007554 PyObject *errorHandler = NULL;
7555 PyObject *exc = NULL;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007556 Py_UNICODE *mapstring = NULL;
Martin v. Löwis18e16552006-02-15 17:27:45 +00007557 Py_ssize_t maplen = 0;
Tim Petersced69f82003-09-16 20:30:58 +00007558
Guido van Rossumd57fd912000-03-10 22:53:23 +00007559 /* Default to Latin-1 */
7560 if (mapping == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007561 return PyUnicode_DecodeLatin1(s, size, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007562
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007563 v = PyUnicode_New(size, 127);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007564 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007565 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007566 if (size == 0)
Victor Stinner7931d9a2011-11-04 00:22:48 +01007567 return v;
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007568 outpos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007569 e = s + size;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007570 if (PyUnicode_CheckExact(mapping)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007571 mapstring = PyUnicode_AS_UNICODE(mapping);
7572 maplen = PyUnicode_GET_SIZE(mapping);
7573 while (s < e) {
7574 unsigned char ch = *s;
7575 Py_UNICODE x = 0xfffe; /* illegal value */
Guido van Rossumd57fd912000-03-10 22:53:23 +00007576
Benjamin Peterson29060642009-01-31 22:14:21 +00007577 if (ch < maplen)
7578 x = mapstring[ch];
Guido van Rossumd57fd912000-03-10 22:53:23 +00007579
Benjamin Peterson29060642009-01-31 22:14:21 +00007580 if (x == 0xfffe) {
7581 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007582 startinpos = s-starts;
7583 endinpos = startinpos+1;
7584 if (unicode_decode_call_errorhandler(
7585 errors, &errorHandler,
7586 "charmap", "character maps to <undefined>",
7587 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007588 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007589 goto onError;
7590 }
7591 continue;
7592 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007593 if (unicode_putchar(&v, &outpos, x) < 0)
7594 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007595 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007596 }
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007597 }
7598 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007599 while (s < e) {
7600 unsigned char ch = *s;
7601 PyObject *w, *x;
Walter Dörwaldd1c1e102005-10-06 20:29:57 +00007602
Benjamin Peterson29060642009-01-31 22:14:21 +00007603 /* Get mapping (char ordinal -> integer, Unicode char or None) */
7604 w = PyLong_FromLong((long)ch);
7605 if (w == NULL)
7606 goto onError;
7607 x = PyObject_GetItem(mapping, w);
7608 Py_DECREF(w);
7609 if (x == NULL) {
7610 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7611 /* No mapping found means: mapping is undefined. */
7612 PyErr_Clear();
7613 x = Py_None;
7614 Py_INCREF(x);
7615 } else
7616 goto onError;
7617 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00007618
Benjamin Peterson29060642009-01-31 22:14:21 +00007619 /* Apply mapping */
7620 if (PyLong_Check(x)) {
7621 long value = PyLong_AS_LONG(x);
7622 if (value < 0 || value > 65535) {
7623 PyErr_SetString(PyExc_TypeError,
7624 "character mapping must be in range(65536)");
7625 Py_DECREF(x);
7626 goto onError;
7627 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007628 if (unicode_putchar(&v, &outpos, value) < 0)
7629 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00007630 }
7631 else if (x == Py_None) {
7632 /* undefined mapping */
Benjamin Peterson29060642009-01-31 22:14:21 +00007633 startinpos = s-starts;
7634 endinpos = startinpos+1;
7635 if (unicode_decode_call_errorhandler(
7636 errors, &errorHandler,
7637 "charmap", "character maps to <undefined>",
7638 &starts, &e, &startinpos, &endinpos, &exc, &s,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007639 &v, &outpos)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007640 Py_DECREF(x);
7641 goto onError;
7642 }
7643 Py_DECREF(x);
7644 continue;
7645 }
7646 else if (PyUnicode_Check(x)) {
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007647 Py_ssize_t targetsize;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007648
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007649 if (PyUnicode_READY(x) < 0)
7650 goto onError;
7651 targetsize = PyUnicode_GET_LENGTH(x);
7652
7653 if (targetsize == 1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007654 /* 1-1 mapping */
Victor Stinner62aa4d02011-11-09 00:03:45 +01007655 if (unicode_putchar(&v, &outpos,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007656 PyUnicode_READ_CHAR(x, 0)) < 0)
7657 goto onError;
7658 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007659 else if (targetsize > 1) {
7660 /* 1-n mapping */
7661 if (targetsize > extrachars) {
7662 /* resize first */
Benjamin Peterson29060642009-01-31 22:14:21 +00007663 Py_ssize_t needed = (targetsize - extrachars) + \
7664 (targetsize << 2);
7665 extrachars += needed;
7666 /* XXX overflow detection missing */
Victor Stinner7931d9a2011-11-04 00:22:48 +01007667 if (PyUnicode_Resize(&v,
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007668 PyUnicode_GET_LENGTH(v) + needed) < 0) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007669 Py_DECREF(x);
7670 goto onError;
7671 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007672 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007673 if (unicode_widen(&v, PyUnicode_MAX_CHAR_VALUE(x)) < 0)
7674 goto onError;
7675 PyUnicode_CopyCharacters(v, outpos, x, 0, targetsize);
7676 outpos += targetsize;
Benjamin Peterson29060642009-01-31 22:14:21 +00007677 extrachars -= targetsize;
7678 }
7679 /* 1-0 mapping: skip the character */
7680 }
7681 else {
7682 /* wrong return value */
7683 PyErr_SetString(PyExc_TypeError,
7684 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00007685 Py_DECREF(x);
7686 goto onError;
7687 }
Benjamin Peterson29060642009-01-31 22:14:21 +00007688 Py_DECREF(x);
7689 ++s;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007690 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00007691 }
Martin v. Löwise9b11c12011-11-08 17:35:34 +01007692 if (PyUnicode_Resize(&v, outpos) < 0)
Antoine Pitroua8f63c02011-11-08 18:37:16 +01007693 goto onError;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007694 Py_XDECREF(errorHandler);
7695 Py_XDECREF(exc);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02007696 assert(_PyUnicode_CheckConsistency(v, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +01007697 return v;
Tim Petersced69f82003-09-16 20:30:58 +00007698
Benjamin Peterson29060642009-01-31 22:14:21 +00007699 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007700 Py_XDECREF(errorHandler);
7701 Py_XDECREF(exc);
Guido van Rossumd57fd912000-03-10 22:53:23 +00007702 Py_XDECREF(v);
7703 return NULL;
7704}
7705
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007706/* Charmap encoding: the lookup table */
7707
Alexander Belopolsky40018472011-02-26 01:02:56 +00007708struct encoding_map {
Benjamin Peterson29060642009-01-31 22:14:21 +00007709 PyObject_HEAD
7710 unsigned char level1[32];
7711 int count2, count3;
7712 unsigned char level23[1];
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007713};
7714
7715static PyObject*
7716encoding_map_size(PyObject *obj, PyObject* args)
7717{
7718 struct encoding_map *map = (struct encoding_map*)obj;
Benjamin Peterson14339b62009-01-31 16:36:08 +00007719 return PyLong_FromLong(sizeof(*map) - 1 + 16*map->count2 +
Benjamin Peterson29060642009-01-31 22:14:21 +00007720 128*map->count3);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007721}
7722
7723static PyMethodDef encoding_map_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007724 {"size", encoding_map_size, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +00007725 PyDoc_STR("Return the size (in bytes) of this object") },
7726 { 0 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007727};
7728
7729static void
7730encoding_map_dealloc(PyObject* o)
7731{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007732 PyObject_FREE(o);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007733}
7734
7735static PyTypeObject EncodingMapType = {
Benjamin Peterson14339b62009-01-31 16:36:08 +00007736 PyVarObject_HEAD_INIT(NULL, 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00007737 "EncodingMap", /*tp_name*/
7738 sizeof(struct encoding_map), /*tp_basicsize*/
7739 0, /*tp_itemsize*/
7740 /* methods */
7741 encoding_map_dealloc, /*tp_dealloc*/
7742 0, /*tp_print*/
7743 0, /*tp_getattr*/
7744 0, /*tp_setattr*/
Mark Dickinsone94c6792009-02-02 20:36:42 +00007745 0, /*tp_reserved*/
Benjamin Peterson29060642009-01-31 22:14:21 +00007746 0, /*tp_repr*/
7747 0, /*tp_as_number*/
7748 0, /*tp_as_sequence*/
7749 0, /*tp_as_mapping*/
7750 0, /*tp_hash*/
7751 0, /*tp_call*/
7752 0, /*tp_str*/
7753 0, /*tp_getattro*/
7754 0, /*tp_setattro*/
7755 0, /*tp_as_buffer*/
7756 Py_TPFLAGS_DEFAULT, /*tp_flags*/
7757 0, /*tp_doc*/
7758 0, /*tp_traverse*/
7759 0, /*tp_clear*/
7760 0, /*tp_richcompare*/
7761 0, /*tp_weaklistoffset*/
7762 0, /*tp_iter*/
7763 0, /*tp_iternext*/
7764 encoding_map_methods, /*tp_methods*/
7765 0, /*tp_members*/
7766 0, /*tp_getset*/
7767 0, /*tp_base*/
7768 0, /*tp_dict*/
7769 0, /*tp_descr_get*/
7770 0, /*tp_descr_set*/
7771 0, /*tp_dictoffset*/
7772 0, /*tp_init*/
7773 0, /*tp_alloc*/
7774 0, /*tp_new*/
7775 0, /*tp_free*/
7776 0, /*tp_is_gc*/
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007777};
7778
7779PyObject*
7780PyUnicode_BuildEncodingMap(PyObject* string)
7781{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007782 PyObject *result;
7783 struct encoding_map *mresult;
7784 int i;
7785 int need_dict = 0;
7786 unsigned char level1[32];
7787 unsigned char level2[512];
7788 unsigned char *mlevel1, *mlevel2, *mlevel3;
7789 int count2 = 0, count3 = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007790 int kind;
7791 void *data;
7792 Py_UCS4 ch;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007793
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007794 if (!PyUnicode_Check(string) || PyUnicode_GET_LENGTH(string) != 256) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007795 PyErr_BadArgument();
7796 return NULL;
7797 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007798 kind = PyUnicode_KIND(string);
7799 data = PyUnicode_DATA(string);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007800 memset(level1, 0xFF, sizeof level1);
7801 memset(level2, 0xFF, sizeof level2);
7802
7803 /* If there isn't a one-to-one mapping of NULL to \0,
7804 or if there are non-BMP characters, we need to use
7805 a mapping dictionary. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007806 if (PyUnicode_READ(kind, data, 0) != 0)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007807 need_dict = 1;
7808 for (i = 1; i < 256; i++) {
7809 int l1, l2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007810 ch = PyUnicode_READ(kind, data, i);
7811 if (ch == 0 || ch > 0xFFFF) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007812 need_dict = 1;
7813 break;
7814 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007815 if (ch == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007816 /* unmapped character */
7817 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007818 l1 = ch >> 11;
7819 l2 = ch >> 7;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007820 if (level1[l1] == 0xFF)
7821 level1[l1] = count2++;
7822 if (level2[l2] == 0xFF)
Benjamin Peterson14339b62009-01-31 16:36:08 +00007823 level2[l2] = count3++;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007824 }
7825
7826 if (count2 >= 0xFF || count3 >= 0xFF)
7827 need_dict = 1;
7828
7829 if (need_dict) {
7830 PyObject *result = PyDict_New();
7831 PyObject *key, *value;
7832 if (!result)
7833 return NULL;
7834 for (i = 0; i < 256; i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007835 key = PyLong_FromLong(PyUnicode_READ(kind, data, i));
Christian Heimes217cfd12007-12-02 14:31:20 +00007836 value = PyLong_FromLong(i);
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007837 if (!key || !value)
7838 goto failed1;
7839 if (PyDict_SetItem(result, key, value) == -1)
7840 goto failed1;
7841 Py_DECREF(key);
7842 Py_DECREF(value);
7843 }
7844 return result;
7845 failed1:
7846 Py_XDECREF(key);
7847 Py_XDECREF(value);
7848 Py_DECREF(result);
7849 return NULL;
7850 }
7851
7852 /* Create a three-level trie */
7853 result = PyObject_MALLOC(sizeof(struct encoding_map) +
7854 16*count2 + 128*count3 - 1);
7855 if (!result)
7856 return PyErr_NoMemory();
7857 PyObject_Init(result, &EncodingMapType);
7858 mresult = (struct encoding_map*)result;
7859 mresult->count2 = count2;
7860 mresult->count3 = count3;
7861 mlevel1 = mresult->level1;
7862 mlevel2 = mresult->level23;
7863 mlevel3 = mresult->level23 + 16*count2;
7864 memcpy(mlevel1, level1, 32);
7865 memset(mlevel2, 0xFF, 16*count2);
7866 memset(mlevel3, 0, 128*count3);
7867 count3 = 0;
7868 for (i = 1; i < 256; i++) {
7869 int o1, o2, o3, i2, i3;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007870 if (PyUnicode_READ(kind, data, i) == 0xFFFE)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007871 /* unmapped character */
7872 continue;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007873 o1 = PyUnicode_READ(kind, data, i)>>11;
7874 o2 = (PyUnicode_READ(kind, data, i)>>7) & 0xF;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007875 i2 = 16*mlevel1[o1] + o2;
7876 if (mlevel2[i2] == 0xFF)
7877 mlevel2[i2] = count3++;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02007878 o3 = PyUnicode_READ(kind, data, i) & 0x7F;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007879 i3 = 128*mlevel2[i2] + o3;
7880 mlevel3[i3] = i;
7881 }
7882 return result;
7883}
7884
7885static int
7886encoding_map_lookup(Py_UNICODE c, PyObject *mapping)
7887{
7888 struct encoding_map *map = (struct encoding_map*)mapping;
7889 int l1 = c>>11;
7890 int l2 = (c>>7) & 0xF;
7891 int l3 = c & 0x7F;
7892 int i;
7893
7894#ifdef Py_UNICODE_WIDE
7895 if (c > 0xFFFF) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007896 return -1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007897 }
7898#endif
7899 if (c == 0)
7900 return 0;
7901 /* level 1*/
7902 i = map->level1[l1];
7903 if (i == 0xFF) {
7904 return -1;
7905 }
7906 /* level 2*/
7907 i = map->level23[16*i+l2];
7908 if (i == 0xFF) {
7909 return -1;
7910 }
7911 /* level 3 */
7912 i = map->level23[16*map->count2 + 128*i + l3];
7913 if (i == 0) {
7914 return -1;
7915 }
7916 return i;
7917}
7918
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007919/* Lookup the character ch in the mapping. If the character
7920 can't be found, Py_None is returned (or NULL, if another
Fred Drakedb390c12005-10-28 14:39:47 +00007921 error occurred). */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007922static PyObject *
7923charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00007924{
Christian Heimes217cfd12007-12-02 14:31:20 +00007925 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007926 PyObject *x;
7927
7928 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00007929 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007930 x = PyObject_GetItem(mapping, w);
7931 Py_DECREF(w);
7932 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007933 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
7934 /* No mapping found means: mapping is undefined. */
7935 PyErr_Clear();
7936 x = Py_None;
7937 Py_INCREF(x);
7938 return x;
7939 } else
7940 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007941 }
Walter Dörwaldadc72742003-01-08 22:01:33 +00007942 else if (x == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00007943 return x;
Christian Heimes217cfd12007-12-02 14:31:20 +00007944 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00007945 long value = PyLong_AS_LONG(x);
7946 if (value < 0 || value > 255) {
7947 PyErr_SetString(PyExc_TypeError,
7948 "character mapping must be in range(256)");
7949 Py_DECREF(x);
7950 return NULL;
7951 }
7952 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007953 }
Christian Heimes72b710a2008-05-26 13:28:38 +00007954 else if (PyBytes_Check(x))
Benjamin Peterson29060642009-01-31 22:14:21 +00007955 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007956 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00007957 /* wrong return value */
7958 PyErr_Format(PyExc_TypeError,
7959 "character mapping must return integer, bytes or None, not %.400s",
7960 x->ob_type->tp_name);
7961 Py_DECREF(x);
7962 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00007963 }
7964}
7965
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007966static int
Guido van Rossum98297ee2007-11-06 21:34:58 +00007967charmapencode_resize(PyObject **outobj, Py_ssize_t *outpos, Py_ssize_t requiredsize)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007968{
Benjamin Peterson14339b62009-01-31 16:36:08 +00007969 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
7970 /* exponentially overallocate to minimize reallocations */
7971 if (requiredsize < 2*outsize)
7972 requiredsize = 2*outsize;
7973 if (_PyBytes_Resize(outobj, requiredsize))
7974 return -1;
7975 return 0;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007976}
7977
Benjamin Peterson14339b62009-01-31 16:36:08 +00007978typedef enum charmapencode_result {
Benjamin Peterson29060642009-01-31 22:14:21 +00007979 enc_SUCCESS, enc_FAILED, enc_EXCEPTION
Alexander Belopolsky40018472011-02-26 01:02:56 +00007980} charmapencode_result;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007981/* lookup the character, put the result in the output string and adjust
Walter Dörwald827b0552007-05-12 13:23:53 +00007982 various state variables. Resize the output bytes object if not enough
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007983 space is available. Return a new reference to the object that
7984 was put in the output buffer, or Py_None, if the mapping was undefined
7985 (in which case no character was written) or NULL, if a
Andrew M. Kuchling8294de52005-11-02 16:36:12 +00007986 reallocation error occurred. The caller must decref the result */
Alexander Belopolsky40018472011-02-26 01:02:56 +00007987static charmapencode_result
7988charmapencode_output(Py_UNICODE c, PyObject *mapping,
7989 PyObject **outobj, Py_ssize_t *outpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007990{
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007991 PyObject *rep;
7992 char *outstart;
Christian Heimes72b710a2008-05-26 13:28:38 +00007993 Py_ssize_t outsize = PyBytes_GET_SIZE(*outobj);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00007994
Christian Heimes90aa7642007-12-19 02:45:37 +00007995 if (Py_TYPE(mapping) == &EncodingMapType) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007996 int res = encoding_map_lookup(c, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00007997 Py_ssize_t requiredsize = *outpos+1;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00007998 if (res == -1)
7999 return enc_FAILED;
Benjamin Peterson29060642009-01-31 22:14:21 +00008000 if (outsize<requiredsize)
8001 if (charmapencode_resize(outobj, outpos, requiredsize))
8002 return enc_EXCEPTION;
Christian Heimes72b710a2008-05-26 13:28:38 +00008003 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008004 outstart[(*outpos)++] = (char)res;
8005 return enc_SUCCESS;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008006 }
8007
8008 rep = charmapencode_lookup(c, mapping);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008009 if (rep==NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008010 return enc_EXCEPTION;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008011 else if (rep==Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008012 Py_DECREF(rep);
8013 return enc_FAILED;
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008014 } else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008015 if (PyLong_Check(rep)) {
8016 Py_ssize_t requiredsize = *outpos+1;
8017 if (outsize<requiredsize)
8018 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8019 Py_DECREF(rep);
8020 return enc_EXCEPTION;
8021 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008022 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008023 outstart[(*outpos)++] = (char)PyLong_AS_LONG(rep);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008024 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008025 else {
8026 const char *repchars = PyBytes_AS_STRING(rep);
8027 Py_ssize_t repsize = PyBytes_GET_SIZE(rep);
8028 Py_ssize_t requiredsize = *outpos+repsize;
8029 if (outsize<requiredsize)
8030 if (charmapencode_resize(outobj, outpos, requiredsize)) {
8031 Py_DECREF(rep);
8032 return enc_EXCEPTION;
8033 }
Christian Heimes72b710a2008-05-26 13:28:38 +00008034 outstart = PyBytes_AS_STRING(*outobj);
Benjamin Peterson29060642009-01-31 22:14:21 +00008035 memcpy(outstart + *outpos, repchars, repsize);
8036 *outpos += repsize;
8037 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008038 }
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008039 Py_DECREF(rep);
8040 return enc_SUCCESS;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008041}
8042
8043/* handle an error in PyUnicode_EncodeCharmap
8044 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008045static int
8046charmap_encoding_error(
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008047 PyObject *unicode, Py_ssize_t *inpos, PyObject *mapping,
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008048 PyObject **exceptionObject,
Walter Dörwalde5402fb2003-08-14 20:25:29 +00008049 int *known_errorHandler, PyObject **errorHandler, const char *errors,
Guido van Rossum98297ee2007-11-06 21:34:58 +00008050 PyObject **res, Py_ssize_t *respos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008051{
8052 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008053 Py_ssize_t size, repsize;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008054 Py_ssize_t newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008055 Py_UNICODE *uni2;
8056 /* startpos for collecting unencodable chars */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008057 Py_ssize_t collstartpos = *inpos;
8058 Py_ssize_t collendpos = *inpos+1;
8059 Py_ssize_t collpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008060 char *encoding = "charmap";
8061 char *reason = "character maps to <undefined>";
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008062 charmapencode_result x;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008063 Py_UCS4 ch;
Brian Curtin2787ea42011-11-02 15:09:37 -05008064 int val;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008065
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008066 if (PyUnicode_READY(unicode) < 0)
8067 return -1;
8068 size = PyUnicode_GET_LENGTH(unicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008069 /* find all unencodable characters */
8070 while (collendpos < size) {
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00008071 PyObject *rep;
Christian Heimes90aa7642007-12-19 02:45:37 +00008072 if (Py_TYPE(mapping) == &EncodingMapType) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008073 ch = PyUnicode_READ_CHAR(unicode, collendpos);
Brian Curtin2787ea42011-11-02 15:09:37 -05008074 val = encoding_map_lookup(ch, mapping);
8075 if (val != -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00008076 break;
8077 ++collendpos;
8078 continue;
8079 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008080
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008081 ch = PyUnicode_READ_CHAR(unicode, collendpos);
8082 rep = charmapencode_lookup(ch, mapping);
Benjamin Peterson29060642009-01-31 22:14:21 +00008083 if (rep==NULL)
8084 return -1;
8085 else if (rep!=Py_None) {
8086 Py_DECREF(rep);
8087 break;
8088 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008089 Py_DECREF(rep);
Benjamin Peterson29060642009-01-31 22:14:21 +00008090 ++collendpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008091 }
8092 /* cache callback name lookup
8093 * (if not done yet, i.e. it's the first error) */
8094 if (*known_errorHandler==-1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008095 if ((errors==NULL) || (!strcmp(errors, "strict")))
8096 *known_errorHandler = 1;
8097 else if (!strcmp(errors, "replace"))
8098 *known_errorHandler = 2;
8099 else if (!strcmp(errors, "ignore"))
8100 *known_errorHandler = 3;
8101 else if (!strcmp(errors, "xmlcharrefreplace"))
8102 *known_errorHandler = 4;
8103 else
8104 *known_errorHandler = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008105 }
8106 switch (*known_errorHandler) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008107 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008108 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008109 return -1;
8110 case 2: /* replace */
8111 for (collpos = collstartpos; collpos<collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008112 x = charmapencode_output('?', mapping, res, respos);
8113 if (x==enc_EXCEPTION) {
8114 return -1;
8115 }
8116 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008117 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008118 return -1;
8119 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008120 }
8121 /* fall through */
8122 case 3: /* ignore */
8123 *inpos = collendpos;
8124 break;
8125 case 4: /* xmlcharrefreplace */
8126 /* generate replacement (temporarily (mis)uses p) */
8127 for (collpos = collstartpos; collpos < collendpos; ++collpos) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008128 char buffer[2+29+1+1];
8129 char *cp;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008130 sprintf(buffer, "&#%d;", (int)PyUnicode_READ_CHAR(unicode, collpos));
Benjamin Peterson29060642009-01-31 22:14:21 +00008131 for (cp = buffer; *cp; ++cp) {
8132 x = charmapencode_output(*cp, mapping, res, respos);
8133 if (x==enc_EXCEPTION)
8134 return -1;
8135 else if (x==enc_FAILED) {
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008136 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008137 return -1;
8138 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008139 }
8140 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008141 *inpos = collendpos;
8142 break;
8143 default:
8144 repunicode = unicode_encode_call_errorhandler(errors, errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008145 encoding, reason, unicode, exceptionObject,
Benjamin Peterson29060642009-01-31 22:14:21 +00008146 collstartpos, collendpos, &newpos);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008147 if (repunicode == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008148 return -1;
Martin v. Löwis011e8422009-05-05 04:43:17 +00008149 if (PyBytes_Check(repunicode)) {
8150 /* Directly copy bytes result to output. */
8151 Py_ssize_t outsize = PyBytes_Size(*res);
8152 Py_ssize_t requiredsize;
8153 repsize = PyBytes_Size(repunicode);
8154 requiredsize = *respos + repsize;
8155 if (requiredsize > outsize)
8156 /* Make room for all additional bytes. */
8157 if (charmapencode_resize(res, respos, requiredsize)) {
8158 Py_DECREF(repunicode);
8159 return -1;
8160 }
8161 memcpy(PyBytes_AsString(*res) + *respos,
8162 PyBytes_AsString(repunicode), repsize);
8163 *respos += repsize;
8164 *inpos = newpos;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008165 Py_DECREF(repunicode);
Martin v. Löwis011e8422009-05-05 04:43:17 +00008166 break;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008167 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008168 /* generate replacement */
8169 repsize = PyUnicode_GET_SIZE(repunicode);
8170 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008171 x = charmapencode_output(*uni2, mapping, res, respos);
8172 if (x==enc_EXCEPTION) {
8173 return -1;
8174 }
8175 else if (x==enc_FAILED) {
8176 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008177 raise_encode_exception(exceptionObject, encoding, unicode, collstartpos, collendpos, reason);
Benjamin Peterson29060642009-01-31 22:14:21 +00008178 return -1;
8179 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008180 }
8181 *inpos = newpos;
8182 Py_DECREF(repunicode);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008183 }
8184 return 0;
8185}
8186
Alexander Belopolsky40018472011-02-26 01:02:56 +00008187PyObject *
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008188_PyUnicode_EncodeCharmap(PyObject *unicode,
8189 PyObject *mapping,
8190 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008191{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008192 /* output object */
8193 PyObject *res = NULL;
8194 /* current input position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008195 Py_ssize_t inpos = 0;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008196 Py_ssize_t size;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008197 /* current output position */
Martin v. Löwis18e16552006-02-15 17:27:45 +00008198 Py_ssize_t respos = 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008199 PyObject *errorHandler = NULL;
8200 PyObject *exc = NULL;
8201 /* the following variable is used for caching string comparisons
8202 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8203 * 3=ignore, 4=xmlcharrefreplace */
8204 int known_errorHandler = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008205
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008206 if (PyUnicode_READY(unicode) < 0)
8207 return NULL;
8208 size = PyUnicode_GET_LENGTH(unicode);
8209
Guido van Rossumd57fd912000-03-10 22:53:23 +00008210 /* Default to Latin-1 */
8211 if (mapping == NULL)
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008212 return unicode_encode_ucs1(unicode, errors, 256);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008213
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008214 /* allocate enough for a simple encoding without
8215 replacements, if we need more, we'll resize */
Christian Heimes72b710a2008-05-26 13:28:38 +00008216 res = PyBytes_FromStringAndSize(NULL, size);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008217 if (res == NULL)
8218 goto onError;
Marc-André Lemburgb7520772000-08-14 11:29:19 +00008219 if (size == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008220 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008221
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008222 while (inpos<size) {
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008223 Py_UCS4 ch = PyUnicode_READ_CHAR(unicode, inpos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008224 /* try to encode it */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008225 charmapencode_result x = charmapencode_output(ch, mapping, &res, &respos);
Benjamin Peterson29060642009-01-31 22:14:21 +00008226 if (x==enc_EXCEPTION) /* error */
8227 goto onError;
8228 if (x==enc_FAILED) { /* unencodable character */
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008229 if (charmap_encoding_error(unicode, &inpos, mapping,
Benjamin Peterson29060642009-01-31 22:14:21 +00008230 &exc,
8231 &known_errorHandler, &errorHandler, errors,
8232 &res, &respos)) {
8233 goto onError;
8234 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008235 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008236 else
8237 /* done with this character => adjust input position */
8238 ++inpos;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008239 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008240
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008241 /* Resize if we allocated to much */
Christian Heimes72b710a2008-05-26 13:28:38 +00008242 if (respos<PyBytes_GET_SIZE(res))
Alexandre Vassalotti44531cb2008-12-27 09:16:49 +00008243 if (_PyBytes_Resize(&res, respos) < 0)
8244 goto onError;
Guido van Rossum98297ee2007-11-06 21:34:58 +00008245
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008246 Py_XDECREF(exc);
8247 Py_XDECREF(errorHandler);
8248 return res;
8249
Benjamin Peterson29060642009-01-31 22:14:21 +00008250 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008251 Py_XDECREF(res);
8252 Py_XDECREF(exc);
8253 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008254 return NULL;
8255}
8256
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008257/* Deprecated */
8258PyObject *
8259PyUnicode_EncodeCharmap(const Py_UNICODE *p,
8260 Py_ssize_t size,
8261 PyObject *mapping,
8262 const char *errors)
8263{
8264 PyObject *result;
8265 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8266 if (unicode == NULL)
8267 return NULL;
8268 result = _PyUnicode_EncodeCharmap(unicode, mapping, errors);
8269 Py_DECREF(unicode);
Victor Stinnerfc026c92011-11-04 00:24:51 +01008270 return result;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008271}
8272
Alexander Belopolsky40018472011-02-26 01:02:56 +00008273PyObject *
8274PyUnicode_AsCharmapString(PyObject *unicode,
8275 PyObject *mapping)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008276{
8277 if (!PyUnicode_Check(unicode) || mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008278 PyErr_BadArgument();
8279 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008280 }
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008281 return _PyUnicode_EncodeCharmap(unicode, mapping, NULL);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008282}
8283
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008284/* create or adjust a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008285static void
8286make_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008287 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008288 Py_ssize_t startpos, Py_ssize_t endpos,
8289 const char *reason)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008290{
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008291 if (*exceptionObject == NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008292 *exceptionObject = _PyUnicodeTranslateError_Create(
8293 unicode, startpos, endpos, reason);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008294 }
8295 else {
Benjamin Peterson29060642009-01-31 22:14:21 +00008296 if (PyUnicodeTranslateError_SetStart(*exceptionObject, startpos))
8297 goto onError;
8298 if (PyUnicodeTranslateError_SetEnd(*exceptionObject, endpos))
8299 goto onError;
8300 if (PyUnicodeTranslateError_SetReason(*exceptionObject, reason))
8301 goto onError;
8302 return;
8303 onError:
8304 Py_DECREF(*exceptionObject);
8305 *exceptionObject = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008306 }
8307}
8308
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008309/* raises a UnicodeTranslateError */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008310static void
8311raise_translate_exception(PyObject **exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008312 PyObject *unicode,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008313 Py_ssize_t startpos, Py_ssize_t endpos,
8314 const char *reason)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008315{
8316 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008317 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008318 if (*exceptionObject != NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008319 PyCodec_StrictErrors(*exceptionObject);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008320}
8321
8322/* error handling callback helper:
8323 build arguments, call the callback and check the arguments,
8324 put the result into newpos and return the replacement string, which
8325 has to be freed by the caller */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008326static PyObject *
8327unicode_translate_call_errorhandler(const char *errors,
8328 PyObject **errorHandler,
8329 const char *reason,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008330 PyObject *unicode, PyObject **exceptionObject,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008331 Py_ssize_t startpos, Py_ssize_t endpos,
8332 Py_ssize_t *newpos)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008333{
Benjamin Peterson142957c2008-07-04 19:55:29 +00008334 static char *argparse = "O!n;translating error handler must return (str, int) tuple";
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008335
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00008336 Py_ssize_t i_newpos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008337 PyObject *restuple;
8338 PyObject *resunicode;
8339
8340 if (*errorHandler == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008341 *errorHandler = PyCodec_LookupError(errors);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008342 if (*errorHandler == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008343 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008344 }
8345
8346 make_translate_exception(exceptionObject,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008347 unicode, startpos, endpos, reason);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008348 if (*exceptionObject == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008349 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008350
8351 restuple = PyObject_CallFunctionObjArgs(
Benjamin Peterson29060642009-01-31 22:14:21 +00008352 *errorHandler, *exceptionObject, NULL);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008353 if (restuple == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008354 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008355 if (!PyTuple_Check(restuple)) {
Benjamin Petersond75fcb42009-02-19 04:22:03 +00008356 PyErr_SetString(PyExc_TypeError, &argparse[4]);
Benjamin Peterson29060642009-01-31 22:14:21 +00008357 Py_DECREF(restuple);
8358 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008359 }
8360 if (!PyArg_ParseTuple(restuple, argparse, &PyUnicode_Type,
Benjamin Peterson29060642009-01-31 22:14:21 +00008361 &resunicode, &i_newpos)) {
8362 Py_DECREF(restuple);
8363 return NULL;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008364 }
Martin v. Löwis18e16552006-02-15 17:27:45 +00008365 if (i_newpos<0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008366 *newpos = PyUnicode_GET_LENGTH(unicode)+i_newpos;
Martin v. Löwis18e16552006-02-15 17:27:45 +00008367 else
8368 *newpos = i_newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008369 if (*newpos<0 || *newpos>PyUnicode_GET_LENGTH(unicode)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008370 PyErr_Format(PyExc_IndexError, "position %zd from error handler out of bounds", *newpos);
8371 Py_DECREF(restuple);
8372 return NULL;
Walter Dörwald2e0b18a2003-01-31 17:19:08 +00008373 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008374 Py_INCREF(resunicode);
8375 Py_DECREF(restuple);
8376 return resunicode;
8377}
8378
8379/* Lookup the character ch in the mapping and put the result in result,
8380 which must be decrefed by the caller.
8381 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008382static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008383charmaptranslate_lookup(Py_UCS4 c, PyObject *mapping, PyObject **result)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008384{
Christian Heimes217cfd12007-12-02 14:31:20 +00008385 PyObject *w = PyLong_FromLong((long)c);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008386 PyObject *x;
8387
8388 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008389 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008390 x = PyObject_GetItem(mapping, w);
8391 Py_DECREF(w);
8392 if (x == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008393 if (PyErr_ExceptionMatches(PyExc_LookupError)) {
8394 /* No mapping found means: use 1:1 mapping. */
8395 PyErr_Clear();
8396 *result = NULL;
8397 return 0;
8398 } else
8399 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008400 }
8401 else if (x == Py_None) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008402 *result = x;
8403 return 0;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008404 }
Christian Heimes217cfd12007-12-02 14:31:20 +00008405 else if (PyLong_Check(x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008406 long value = PyLong_AS_LONG(x);
8407 long max = PyUnicode_GetMax();
8408 if (value < 0 || value > max) {
8409 PyErr_Format(PyExc_TypeError,
Guido van Rossum5a2f7e602007-10-24 21:13:09 +00008410 "character mapping must be in range(0x%x)", max+1);
Benjamin Peterson29060642009-01-31 22:14:21 +00008411 Py_DECREF(x);
8412 return -1;
8413 }
8414 *result = x;
8415 return 0;
8416 }
8417 else if (PyUnicode_Check(x)) {
8418 *result = x;
8419 return 0;
8420 }
8421 else {
8422 /* wrong return value */
8423 PyErr_SetString(PyExc_TypeError,
8424 "character mapping must return integer, None or str");
Benjamin Peterson14339b62009-01-31 16:36:08 +00008425 Py_DECREF(x);
8426 return -1;
8427 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008428}
8429/* ensure that *outobj is at least requiredsize characters long,
Benjamin Peterson29060642009-01-31 22:14:21 +00008430 if not reallocate and adjust various state variables.
8431 Return 0 on success, -1 on error */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008432static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008433charmaptranslate_makespace(Py_UCS4 **outobj, Py_ssize_t *psize,
Benjamin Peterson29060642009-01-31 22:14:21 +00008434 Py_ssize_t requiredsize)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008435{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008436 Py_ssize_t oldsize = *psize;
Walter Dörwald4894c302003-10-24 14:25:28 +00008437 if (requiredsize > oldsize) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008438 /* exponentially overallocate to minimize reallocations */
8439 if (requiredsize < 2 * oldsize)
8440 requiredsize = 2 * oldsize;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008441 *outobj = PyMem_Realloc(*outobj, requiredsize * sizeof(Py_UCS4));
8442 if (*outobj == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00008443 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008444 *psize = requiredsize;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008445 }
8446 return 0;
8447}
8448/* lookup the character, put the result in the output string and adjust
8449 various state variables. Return a new reference to the object that
8450 was put in the output buffer in *result, or Py_None, if the mapping was
8451 undefined (in which case no character was written).
8452 The called must decref result.
8453 Return 0 on success, -1 on error. */
Alexander Belopolsky40018472011-02-26 01:02:56 +00008454static int
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008455charmaptranslate_output(PyObject *input, Py_ssize_t ipos,
8456 PyObject *mapping, Py_UCS4 **output,
8457 Py_ssize_t *osize, Py_ssize_t *opos,
Alexander Belopolsky40018472011-02-26 01:02:56 +00008458 PyObject **res)
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008459{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008460 Py_UCS4 curinp = PyUnicode_READ_CHAR(input, ipos);
8461 if (charmaptranslate_lookup(curinp, mapping, res))
Benjamin Peterson29060642009-01-31 22:14:21 +00008462 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008463 if (*res==NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008464 /* not found => default to 1:1 mapping */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008465 (*output)[(*opos)++] = curinp;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008466 }
8467 else if (*res==Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +00008468 ;
Christian Heimes217cfd12007-12-02 14:31:20 +00008469 else if (PyLong_Check(*res)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008470 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008471 (*output)[(*opos)++] = (Py_UCS4)PyLong_AS_LONG(*res);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008472 }
8473 else if (PyUnicode_Check(*res)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008474 Py_ssize_t repsize;
8475 if (PyUnicode_READY(*res) == -1)
8476 return -1;
8477 repsize = PyUnicode_GET_LENGTH(*res);
Benjamin Peterson29060642009-01-31 22:14:21 +00008478 if (repsize==1) {
8479 /* no overflow check, because we know that the space is enough */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008480 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +00008481 }
8482 else if (repsize!=0) {
8483 /* more than one character */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008484 Py_ssize_t requiredsize = *opos +
8485 (PyUnicode_GET_LENGTH(input) - ipos) +
Benjamin Peterson29060642009-01-31 22:14:21 +00008486 repsize - 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008487 Py_ssize_t i;
8488 if (charmaptranslate_makespace(output, osize, requiredsize))
Benjamin Peterson29060642009-01-31 22:14:21 +00008489 return -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008490 for(i = 0; i < repsize; i++)
8491 (*output)[(*opos)++] = PyUnicode_READ_CHAR(*res, i);
Benjamin Peterson29060642009-01-31 22:14:21 +00008492 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008493 }
8494 else
Benjamin Peterson29060642009-01-31 22:14:21 +00008495 return -1;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008496 return 0;
8497}
8498
Alexander Belopolsky40018472011-02-26 01:02:56 +00008499PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008500_PyUnicode_TranslateCharmap(PyObject *input,
8501 PyObject *mapping,
8502 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008503{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008504 /* input object */
8505 char *idata;
8506 Py_ssize_t size, i;
8507 int kind;
8508 /* output buffer */
8509 Py_UCS4 *output = NULL;
8510 Py_ssize_t osize;
8511 PyObject *res;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008512 /* current output position */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008513 Py_ssize_t opos;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008514 char *reason = "character maps to <undefined>";
8515 PyObject *errorHandler = NULL;
8516 PyObject *exc = NULL;
8517 /* the following variable is used for caching string comparisons
8518 * -1=not initialized, 0=unknown, 1=strict, 2=replace,
8519 * 3=ignore, 4=xmlcharrefreplace */
8520 int known_errorHandler = -1;
8521
Guido van Rossumd57fd912000-03-10 22:53:23 +00008522 if (mapping == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008523 PyErr_BadArgument();
8524 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008525 }
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008526
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008527 if (PyUnicode_READY(input) == -1)
8528 return NULL;
8529 idata = (char*)PyUnicode_DATA(input);
8530 kind = PyUnicode_KIND(input);
8531 size = PyUnicode_GET_LENGTH(input);
8532 i = 0;
8533
8534 if (size == 0) {
8535 Py_INCREF(input);
8536 return input;
8537 }
8538
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008539 /* allocate enough for a simple 1:1 translation without
8540 replacements, if we need more, we'll resize */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008541 osize = size;
8542 output = PyMem_Malloc(osize * sizeof(Py_UCS4));
8543 opos = 0;
8544 if (output == NULL) {
8545 PyErr_NoMemory();
Benjamin Peterson29060642009-01-31 22:14:21 +00008546 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008547 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00008548
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008549 while (i<size) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008550 /* try to encode it */
8551 PyObject *x = NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008552 if (charmaptranslate_output(input, i, mapping,
8553 &output, &osize, &opos, &x)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008554 Py_XDECREF(x);
8555 goto onError;
8556 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008557 Py_XDECREF(x);
Benjamin Peterson29060642009-01-31 22:14:21 +00008558 if (x!=Py_None) /* it worked => adjust input pointer */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008559 ++i;
Benjamin Peterson29060642009-01-31 22:14:21 +00008560 else { /* untranslatable character */
8561 PyObject *repunicode = NULL; /* initialize to prevent gcc warning */
8562 Py_ssize_t repsize;
8563 Py_ssize_t newpos;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008564 Py_ssize_t uni2;
Benjamin Peterson29060642009-01-31 22:14:21 +00008565 /* startpos for collecting untranslatable chars */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008566 Py_ssize_t collstart = i;
8567 Py_ssize_t collend = i+1;
8568 Py_ssize_t coll;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008569
Benjamin Peterson29060642009-01-31 22:14:21 +00008570 /* find all untranslatable characters */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008571 while (collend < size) {
8572 if (charmaptranslate_lookup(PyUnicode_READ(kind,idata, collend), mapping, &x))
Benjamin Peterson29060642009-01-31 22:14:21 +00008573 goto onError;
8574 Py_XDECREF(x);
8575 if (x!=Py_None)
8576 break;
8577 ++collend;
8578 }
8579 /* cache callback name lookup
8580 * (if not done yet, i.e. it's the first error) */
8581 if (known_errorHandler==-1) {
8582 if ((errors==NULL) || (!strcmp(errors, "strict")))
8583 known_errorHandler = 1;
8584 else if (!strcmp(errors, "replace"))
8585 known_errorHandler = 2;
8586 else if (!strcmp(errors, "ignore"))
8587 known_errorHandler = 3;
8588 else if (!strcmp(errors, "xmlcharrefreplace"))
8589 known_errorHandler = 4;
8590 else
8591 known_errorHandler = 0;
8592 }
8593 switch (known_errorHandler) {
8594 case 1: /* strict */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008595 raise_translate_exception(&exc, input, collstart,
8596 collend, reason);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008597 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008598 case 2: /* replace */
8599 /* No need to check for space, this is a 1:1 replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008600 for (coll = collstart; coll<collend; coll++)
8601 output[opos++] = '?';
Benjamin Peterson29060642009-01-31 22:14:21 +00008602 /* fall through */
8603 case 3: /* ignore */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008604 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008605 break;
8606 case 4: /* xmlcharrefreplace */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008607 /* generate replacement (temporarily (mis)uses i) */
8608 for (i = collstart; i < collend; ++i) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008609 char buffer[2+29+1+1];
8610 char *cp;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008611 sprintf(buffer, "&#%d;", PyUnicode_READ(kind, idata, i));
8612 if (charmaptranslate_makespace(&output, &osize,
8613 opos+strlen(buffer)+(size-collend)))
Benjamin Peterson29060642009-01-31 22:14:21 +00008614 goto onError;
8615 for (cp = buffer; *cp; ++cp)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008616 output[opos++] = *cp;
Benjamin Peterson29060642009-01-31 22:14:21 +00008617 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008618 i = collend;
Benjamin Peterson29060642009-01-31 22:14:21 +00008619 break;
8620 default:
8621 repunicode = unicode_translate_call_errorhandler(errors, &errorHandler,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008622 reason, input, &exc,
8623 collstart, collend, &newpos);
Victor Stinner1b4f9ce2011-10-03 13:28:14 +02008624 if (repunicode == NULL || _PyUnicode_READY_REPLACE(&repunicode))
Benjamin Peterson29060642009-01-31 22:14:21 +00008625 goto onError;
8626 /* generate replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008627 repsize = PyUnicode_GET_LENGTH(repunicode);
8628 if (charmaptranslate_makespace(&output, &osize,
8629 opos+repsize+(size-collend))) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008630 Py_DECREF(repunicode);
8631 goto onError;
8632 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008633 for (uni2 = 0; repsize-->0; ++uni2)
8634 output[opos++] = PyUnicode_READ_CHAR(repunicode, uni2);
8635 i = newpos;
Benjamin Peterson29060642009-01-31 22:14:21 +00008636 Py_DECREF(repunicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +00008637 }
Benjamin Peterson14339b62009-01-31 16:36:08 +00008638 }
8639 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008640 res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, opos);
8641 if (!res)
8642 goto onError;
8643 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008644 Py_XDECREF(exc);
8645 Py_XDECREF(errorHandler);
8646 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00008647
Benjamin Peterson29060642009-01-31 22:14:21 +00008648 onError:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008649 PyMem_Free(output);
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008650 Py_XDECREF(exc);
8651 Py_XDECREF(errorHandler);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008652 return NULL;
8653}
8654
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008655/* Deprecated. Use PyUnicode_Translate instead. */
8656PyObject *
8657PyUnicode_TranslateCharmap(const Py_UNICODE *p,
8658 Py_ssize_t size,
8659 PyObject *mapping,
8660 const char *errors)
8661{
8662 PyObject *unicode = PyUnicode_FromUnicode(p, size);
8663 if (!unicode)
8664 return NULL;
8665 return _PyUnicode_TranslateCharmap(unicode, mapping, errors);
8666}
8667
Alexander Belopolsky40018472011-02-26 01:02:56 +00008668PyObject *
8669PyUnicode_Translate(PyObject *str,
8670 PyObject *mapping,
8671 const char *errors)
Guido van Rossumd57fd912000-03-10 22:53:23 +00008672{
8673 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +00008674
Guido van Rossumd57fd912000-03-10 22:53:23 +00008675 str = PyUnicode_FromObject(str);
8676 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00008677 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008678 result = _PyUnicode_TranslateCharmap(str, mapping, errors);
Guido van Rossumd57fd912000-03-10 22:53:23 +00008679 Py_DECREF(str);
8680 return result;
Tim Petersced69f82003-09-16 20:30:58 +00008681
Benjamin Peterson29060642009-01-31 22:14:21 +00008682 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +00008683 Py_XDECREF(str);
8684 return NULL;
8685}
Tim Petersced69f82003-09-16 20:30:58 +00008686
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008687static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02008688fix_decimal_and_space_to_ascii(PyObject *self)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008689{
8690 /* No need to call PyUnicode_READY(self) because this function is only
8691 called as a callback from fixup() which does it already. */
8692 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
8693 const int kind = PyUnicode_KIND(self);
8694 void *data = PyUnicode_DATA(self);
8695 Py_UCS4 maxchar = 0, ch, fixed;
8696 Py_ssize_t i;
8697
8698 for (i = 0; i < len; ++i) {
8699 ch = PyUnicode_READ(kind, data, i);
8700 fixed = 0;
8701 if (ch > 127) {
8702 if (Py_UNICODE_ISSPACE(ch))
8703 fixed = ' ';
8704 else {
8705 const int decimal = Py_UNICODE_TODECIMAL(ch);
8706 if (decimal >= 0)
8707 fixed = '0' + decimal;
8708 }
8709 if (fixed != 0) {
8710 if (fixed > maxchar)
8711 maxchar = fixed;
8712 PyUnicode_WRITE(kind, data, i, fixed);
8713 }
8714 else if (ch > maxchar)
8715 maxchar = ch;
8716 }
8717 else if (ch > maxchar)
8718 maxchar = ch;
8719 }
8720
8721 return maxchar;
8722}
8723
8724PyObject *
8725_PyUnicode_TransformDecimalAndSpaceToASCII(PyObject *unicode)
8726{
8727 if (!PyUnicode_Check(unicode)) {
8728 PyErr_BadInternalCall();
8729 return NULL;
8730 }
8731 if (PyUnicode_READY(unicode) == -1)
8732 return NULL;
8733 if (PyUnicode_MAX_CHAR_VALUE(unicode) <= 127) {
8734 /* If the string is already ASCII, just return the same string */
8735 Py_INCREF(unicode);
8736 return unicode;
8737 }
Victor Stinner9310abb2011-10-05 00:59:23 +02008738 return fixup(unicode, fix_decimal_and_space_to_ascii);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008739}
8740
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008741PyObject *
8742PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
8743 Py_ssize_t length)
8744{
8745 PyObject *result;
8746 Py_UNICODE *p; /* write pointer into result */
8747 Py_ssize_t i;
8748 /* Copy to a new string */
8749 result = (PyObject *)_PyUnicode_New(length);
8750 Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
8751 if (result == NULL)
8752 return result;
8753 p = PyUnicode_AS_UNICODE(result);
8754 /* Iterate over code points */
8755 for (i = 0; i < length; i++) {
8756 Py_UNICODE ch =s[i];
8757 if (ch > 127) {
8758 int decimal = Py_UNICODE_TODECIMAL(ch);
8759 if (decimal >= 0)
8760 p[i] = '0' + decimal;
8761 }
8762 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008763#ifndef DONT_MAKE_RESULT_READY
8764 if (_PyUnicode_READY_REPLACE(&result)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008765 Py_DECREF(result);
8766 return NULL;
8767 }
Victor Stinner17efeed2011-10-04 20:05:46 +02008768#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02008769 assert(_PyUnicode_CheckConsistency(result, 1));
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00008770 return result;
8771}
Guido van Rossum9e896b32000-04-05 20:11:21 +00008772/* --- Decimal Encoder ---------------------------------------------------- */
8773
Alexander Belopolsky40018472011-02-26 01:02:56 +00008774int
8775PyUnicode_EncodeDecimal(Py_UNICODE *s,
8776 Py_ssize_t length,
8777 char *output,
8778 const char *errors)
Guido van Rossum9e896b32000-04-05 20:11:21 +00008779{
8780 Py_UNICODE *p, *end;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008781 PyObject *errorHandler = NULL;
8782 PyObject *exc = NULL;
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008783 PyObject *unicode;
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008784 const char *encoding = "decimal";
8785 const char *reason = "invalid decimal Unicode string";
8786 /* the following variable is used for caching string comparisons
8787 * -1=not initialized, 0=unknown, 1=strict, 2=replace, 3=ignore, 4=xmlcharrefreplace */
8788 int known_errorHandler = -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008789
8790 if (output == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008791 PyErr_BadArgument();
8792 return -1;
Guido van Rossum9e896b32000-04-05 20:11:21 +00008793 }
8794
8795 p = s;
8796 end = s + length;
8797 while (p < end) {
Benjamin Peterson29060642009-01-31 22:14:21 +00008798 register Py_UNICODE ch = *p;
8799 int decimal;
8800 PyObject *repunicode;
8801 Py_ssize_t repsize;
8802 Py_ssize_t newpos;
8803 Py_UNICODE *uni2;
8804 Py_UNICODE *collstart;
8805 Py_UNICODE *collend;
Tim Petersced69f82003-09-16 20:30:58 +00008806
Benjamin Peterson29060642009-01-31 22:14:21 +00008807 if (Py_UNICODE_ISSPACE(ch)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00008808 *output++ = ' ';
Benjamin Peterson29060642009-01-31 22:14:21 +00008809 ++p;
8810 continue;
Benjamin Peterson14339b62009-01-31 16:36:08 +00008811 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008812 decimal = Py_UNICODE_TODECIMAL(ch);
8813 if (decimal >= 0) {
8814 *output++ = '0' + decimal;
8815 ++p;
8816 continue;
8817 }
8818 if (0 < ch && ch < 256) {
8819 *output++ = (char)ch;
8820 ++p;
8821 continue;
8822 }
8823 /* All other characters are considered unencodable */
8824 collstart = p;
8825 collend = p+1;
8826 while (collend < end) {
8827 if ((0 < *collend && *collend < 256) ||
8828 !Py_UNICODE_ISSPACE(*collend) ||
8829 Py_UNICODE_TODECIMAL(*collend))
8830 break;
8831 }
8832 /* cache callback name lookup
8833 * (if not done yet, i.e. it's the first error) */
8834 if (known_errorHandler==-1) {
8835 if ((errors==NULL) || (!strcmp(errors, "strict")))
8836 known_errorHandler = 1;
8837 else if (!strcmp(errors, "replace"))
8838 known_errorHandler = 2;
8839 else if (!strcmp(errors, "ignore"))
8840 known_errorHandler = 3;
8841 else if (!strcmp(errors, "xmlcharrefreplace"))
8842 known_errorHandler = 4;
8843 else
8844 known_errorHandler = 0;
8845 }
8846 switch (known_errorHandler) {
8847 case 1: /* strict */
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008848 unicode = PyUnicode_FromUnicode(s, length);
8849 if (unicode == NULL)
8850 goto onError;
8851 raise_encode_exception(&exc, encoding, unicode, collstart-s, collend-s, reason);
8852 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008853 goto onError;
8854 case 2: /* replace */
8855 for (p = collstart; p < collend; ++p)
8856 *output++ = '?';
8857 /* fall through */
8858 case 3: /* ignore */
8859 p = collend;
8860 break;
8861 case 4: /* xmlcharrefreplace */
8862 /* generate replacement (temporarily (mis)uses p) */
8863 for (p = collstart; p < collend; ++p)
8864 output += sprintf(output, "&#%d;", (int)*p);
8865 p = collend;
8866 break;
8867 default:
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008868 unicode = PyUnicode_FromUnicode(s, length);
8869 if (unicode == NULL)
8870 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008871 repunicode = unicode_encode_call_errorhandler(errors, &errorHandler,
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008872 encoding, reason, unicode, &exc,
Benjamin Peterson29060642009-01-31 22:14:21 +00008873 collstart-s, collend-s, &newpos);
Martin v. Löwis23e275b2011-11-02 18:02:51 +01008874 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008875 if (repunicode == NULL)
8876 goto onError;
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008877 if (!PyUnicode_Check(repunicode)) {
Martin v. Löwis011e8422009-05-05 04:43:17 +00008878 /* Byte results not supported, since they have no decimal property. */
Martin v. Löwisdb12d452009-05-02 18:52:14 +00008879 PyErr_SetString(PyExc_TypeError, "error handler should return unicode");
8880 Py_DECREF(repunicode);
8881 goto onError;
8882 }
Benjamin Peterson29060642009-01-31 22:14:21 +00008883 /* generate replacement */
8884 repsize = PyUnicode_GET_SIZE(repunicode);
8885 for (uni2 = PyUnicode_AS_UNICODE(repunicode); repsize-->0; ++uni2) {
8886 Py_UNICODE ch = *uni2;
8887 if (Py_UNICODE_ISSPACE(ch))
8888 *output++ = ' ';
8889 else {
8890 decimal = Py_UNICODE_TODECIMAL(ch);
8891 if (decimal >= 0)
8892 *output++ = '0' + decimal;
8893 else if (0 < ch && ch < 256)
8894 *output++ = (char)ch;
8895 else {
8896 Py_DECREF(repunicode);
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008897 unicode = PyUnicode_FromUnicode(s, length);
8898 if (unicode == NULL)
8899 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +00008900 raise_encode_exception(&exc, encoding,
Martin v. Löwis12be46c2011-11-04 19:04:15 +01008901 unicode, collstart-s, collend-s, reason);
8902 Py_DECREF(unicode);
Benjamin Peterson29060642009-01-31 22:14:21 +00008903 goto onError;
8904 }
8905 }
8906 }
8907 p = s + newpos;
8908 Py_DECREF(repunicode);
8909 }
Guido van Rossum9e896b32000-04-05 20:11:21 +00008910 }
8911 /* 0-terminate the output string */
8912 *output++ = '\0';
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008913 Py_XDECREF(exc);
8914 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008915 return 0;
8916
Benjamin Peterson29060642009-01-31 22:14:21 +00008917 onError:
Walter Dörwald3aeb6322002-09-02 13:14:32 +00008918 Py_XDECREF(exc);
8919 Py_XDECREF(errorHandler);
Guido van Rossum9e896b32000-04-05 20:11:21 +00008920 return -1;
8921}
8922
Guido van Rossumd57fd912000-03-10 22:53:23 +00008923/* --- Helpers ------------------------------------------------------------ */
8924
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008925static Py_ssize_t
Victor Stinner794d5672011-10-10 03:21:36 +02008926any_find_slice(int direction, PyObject* s1, PyObject* s2,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008927 Py_ssize_t start,
8928 Py_ssize_t end)
8929{
8930 int kind1, kind2, kind;
8931 void *buf1, *buf2;
8932 Py_ssize_t len1, len2, result;
8933
8934 kind1 = PyUnicode_KIND(s1);
8935 kind2 = PyUnicode_KIND(s2);
8936 kind = kind1 > kind2 ? kind1 : kind2;
8937 buf1 = PyUnicode_DATA(s1);
8938 buf2 = PyUnicode_DATA(s2);
8939 if (kind1 != kind)
8940 buf1 = _PyUnicode_AsKind(s1, kind);
8941 if (!buf1)
8942 return -2;
8943 if (kind2 != kind)
8944 buf2 = _PyUnicode_AsKind(s2, kind);
8945 if (!buf2) {
8946 if (kind1 != kind) PyMem_Free(buf1);
8947 return -2;
8948 }
8949 len1 = PyUnicode_GET_LENGTH(s1);
8950 len2 = PyUnicode_GET_LENGTH(s2);
8951
Victor Stinner794d5672011-10-10 03:21:36 +02008952 if (direction > 0) {
8953 switch(kind) {
8954 case PyUnicode_1BYTE_KIND:
8955 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8956 result = asciilib_find_slice(buf1, len1, buf2, len2, start, end);
8957 else
8958 result = ucs1lib_find_slice(buf1, len1, buf2, len2, start, end);
8959 break;
8960 case PyUnicode_2BYTE_KIND:
8961 result = ucs2lib_find_slice(buf1, len1, buf2, len2, start, end);
8962 break;
8963 case PyUnicode_4BYTE_KIND:
8964 result = ucs4lib_find_slice(buf1, len1, buf2, len2, start, end);
8965 break;
8966 default:
8967 assert(0); result = -2;
8968 }
8969 }
8970 else {
8971 switch(kind) {
8972 case PyUnicode_1BYTE_KIND:
8973 if (PyUnicode_IS_ASCII(s1) && PyUnicode_IS_ASCII(s2))
8974 result = asciilib_rfind_slice(buf1, len1, buf2, len2, start, end);
8975 else
8976 result = ucs1lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8977 break;
8978 case PyUnicode_2BYTE_KIND:
8979 result = ucs2lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8980 break;
8981 case PyUnicode_4BYTE_KIND:
8982 result = ucs4lib_rfind_slice(buf1, len1, buf2, len2, start, end);
8983 break;
8984 default:
8985 assert(0); result = -2;
8986 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008987 }
8988
8989 if (kind1 != kind)
8990 PyMem_Free(buf1);
8991 if (kind2 != kind)
8992 PyMem_Free(buf2);
8993
8994 return result;
8995}
8996
8997Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +02008998_PyUnicode_InsertThousandsGrouping(PyObject *unicode, int kind, void *data,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02008999 Py_ssize_t n_buffer,
9000 void *digits, Py_ssize_t n_digits,
9001 Py_ssize_t min_width,
9002 const char *grouping,
9003 const char *thousands_sep)
9004{
9005 switch(kind) {
9006 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009007 if (unicode != NULL && PyUnicode_IS_ASCII(unicode))
9008 return _PyUnicode_ascii_InsertThousandsGrouping(
9009 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9010 min_width, grouping, thousands_sep);
9011 else
9012 return _PyUnicode_ucs1_InsertThousandsGrouping(
9013 (Py_UCS1*)data, n_buffer, (Py_UCS1*)digits, n_digits,
9014 min_width, grouping, thousands_sep);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009015 case PyUnicode_2BYTE_KIND:
9016 return _PyUnicode_ucs2_InsertThousandsGrouping(
9017 (Py_UCS2*)data, n_buffer, (Py_UCS2*)digits, n_digits,
9018 min_width, grouping, thousands_sep);
9019 case PyUnicode_4BYTE_KIND:
9020 return _PyUnicode_ucs4_InsertThousandsGrouping(
9021 (Py_UCS4*)data, n_buffer, (Py_UCS4*)digits, n_digits,
9022 min_width, grouping, thousands_sep);
9023 }
9024 assert(0);
9025 return -1;
9026}
9027
9028
Thomas Wouters477c8d52006-05-27 19:21:47 +00009029/* helper macro to fixup start/end slice values */
Antoine Pitrouf2c54842010-01-13 08:07:53 +00009030#define ADJUST_INDICES(start, end, len) \
9031 if (end > len) \
9032 end = len; \
9033 else if (end < 0) { \
9034 end += len; \
9035 if (end < 0) \
9036 end = 0; \
9037 } \
9038 if (start < 0) { \
9039 start += len; \
9040 if (start < 0) \
9041 start = 0; \
9042 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009043
Alexander Belopolsky40018472011-02-26 01:02:56 +00009044Py_ssize_t
9045PyUnicode_Count(PyObject *str,
9046 PyObject *substr,
9047 Py_ssize_t start,
9048 Py_ssize_t end)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009049{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009050 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009051 PyObject* str_obj;
9052 PyObject* sub_obj;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009053 int kind1, kind2, kind;
9054 void *buf1 = NULL, *buf2 = NULL;
9055 Py_ssize_t len1, len2;
Tim Petersced69f82003-09-16 20:30:58 +00009056
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009057 str_obj = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009058 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009059 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009060 sub_obj = PyUnicode_FromObject(substr);
Victor Stinnere9a29352011-10-01 02:14:59 +02009061 if (!sub_obj || PyUnicode_READY(sub_obj) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009062 Py_DECREF(str_obj);
9063 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009064 }
Tim Petersced69f82003-09-16 20:30:58 +00009065
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009066 kind1 = PyUnicode_KIND(str_obj);
9067 kind2 = PyUnicode_KIND(sub_obj);
9068 kind = kind1 > kind2 ? kind1 : kind2;
9069 buf1 = PyUnicode_DATA(str_obj);
9070 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009071 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009072 if (!buf1)
9073 goto onError;
9074 buf2 = PyUnicode_DATA(sub_obj);
9075 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009076 buf2 = _PyUnicode_AsKind(sub_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009077 if (!buf2)
9078 goto onError;
9079 len1 = PyUnicode_GET_LENGTH(str_obj);
9080 len2 = PyUnicode_GET_LENGTH(sub_obj);
9081
9082 ADJUST_INDICES(start, end, len1);
9083 switch(kind) {
9084 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009085 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sub_obj))
9086 result = asciilib_count(
9087 ((Py_UCS1*)buf1) + start, end - start,
9088 buf2, len2, PY_SSIZE_T_MAX
9089 );
9090 else
9091 result = ucs1lib_count(
9092 ((Py_UCS1*)buf1) + start, end - start,
9093 buf2, len2, PY_SSIZE_T_MAX
9094 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009095 break;
9096 case PyUnicode_2BYTE_KIND:
9097 result = ucs2lib_count(
9098 ((Py_UCS2*)buf1) + start, end - start,
9099 buf2, len2, PY_SSIZE_T_MAX
9100 );
9101 break;
9102 case PyUnicode_4BYTE_KIND:
9103 result = ucs4lib_count(
9104 ((Py_UCS4*)buf1) + start, end - start,
9105 buf2, len2, PY_SSIZE_T_MAX
9106 );
9107 break;
9108 default:
9109 assert(0); result = 0;
9110 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00009111
9112 Py_DECREF(sub_obj);
9113 Py_DECREF(str_obj);
9114
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009115 if (kind1 != kind)
9116 PyMem_Free(buf1);
9117 if (kind2 != kind)
9118 PyMem_Free(buf2);
9119
Guido van Rossumd57fd912000-03-10 22:53:23 +00009120 return result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009121 onError:
9122 Py_DECREF(sub_obj);
9123 Py_DECREF(str_obj);
9124 if (kind1 != kind && buf1)
9125 PyMem_Free(buf1);
9126 if (kind2 != kind && buf2)
9127 PyMem_Free(buf2);
9128 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009129}
9130
Alexander Belopolsky40018472011-02-26 01:02:56 +00009131Py_ssize_t
9132PyUnicode_Find(PyObject *str,
9133 PyObject *sub,
9134 Py_ssize_t start,
9135 Py_ssize_t end,
9136 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009137{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009138 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009139
Guido van Rossumd57fd912000-03-10 22:53:23 +00009140 str = PyUnicode_FromObject(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009141 if (!str || PyUnicode_READY(str) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009142 return -2;
Thomas Wouters477c8d52006-05-27 19:21:47 +00009143 sub = PyUnicode_FromObject(sub);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009144 if (!sub || PyUnicode_READY(sub) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009145 Py_DECREF(str);
9146 return -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009147 }
Tim Petersced69f82003-09-16 20:30:58 +00009148
Victor Stinner794d5672011-10-10 03:21:36 +02009149 result = any_find_slice(direction,
9150 str, sub, start, end
9151 );
Thomas Wouters477c8d52006-05-27 19:21:47 +00009152
Guido van Rossumd57fd912000-03-10 22:53:23 +00009153 Py_DECREF(str);
Thomas Wouters477c8d52006-05-27 19:21:47 +00009154 Py_DECREF(sub);
9155
Guido van Rossumd57fd912000-03-10 22:53:23 +00009156 return result;
9157}
9158
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009159Py_ssize_t
9160PyUnicode_FindChar(PyObject *str, Py_UCS4 ch,
9161 Py_ssize_t start, Py_ssize_t end,
9162 int direction)
9163{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009164 int kind;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009165 Py_ssize_t result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009166 if (PyUnicode_READY(str) == -1)
9167 return -2;
Victor Stinner267aa242011-10-02 01:08:37 +02009168 if (start < 0 || end < 0) {
9169 PyErr_SetString(PyExc_IndexError, "string index out of range");
9170 return -2;
9171 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009172 if (end > PyUnicode_GET_LENGTH(str))
9173 end = PyUnicode_GET_LENGTH(str);
9174 kind = PyUnicode_KIND(str);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009175 result = findchar(PyUnicode_1BYTE_DATA(str) + kind*start,
9176 kind, end-start, ch, direction);
9177 if (result == -1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009178 return -1;
Antoine Pitrouf0b934b2011-10-13 18:55:09 +02009179 else
9180 return start + result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009181}
9182
Alexander Belopolsky40018472011-02-26 01:02:56 +00009183static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009184tailmatch(PyObject *self,
9185 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009186 Py_ssize_t start,
9187 Py_ssize_t end,
9188 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009189{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009190 int kind_self;
9191 int kind_sub;
9192 void *data_self;
9193 void *data_sub;
9194 Py_ssize_t offset;
9195 Py_ssize_t i;
9196 Py_ssize_t end_sub;
9197
9198 if (PyUnicode_READY(self) == -1 ||
9199 PyUnicode_READY(substring) == -1)
9200 return 0;
9201
9202 if (PyUnicode_GET_LENGTH(substring) == 0)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009203 return 1;
9204
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009205 ADJUST_INDICES(start, end, PyUnicode_GET_LENGTH(self));
9206 end -= PyUnicode_GET_LENGTH(substring);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009207 if (end < start)
Benjamin Peterson29060642009-01-31 22:14:21 +00009208 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009209
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009210 kind_self = PyUnicode_KIND(self);
9211 data_self = PyUnicode_DATA(self);
9212 kind_sub = PyUnicode_KIND(substring);
9213 data_sub = PyUnicode_DATA(substring);
9214 end_sub = PyUnicode_GET_LENGTH(substring) - 1;
9215
9216 if (direction > 0)
9217 offset = end;
9218 else
9219 offset = start;
9220
9221 if (PyUnicode_READ(kind_self, data_self, offset) ==
9222 PyUnicode_READ(kind_sub, data_sub, 0) &&
9223 PyUnicode_READ(kind_self, data_self, offset + end_sub) ==
9224 PyUnicode_READ(kind_sub, data_sub, end_sub)) {
9225 /* If both are of the same kind, memcmp is sufficient */
9226 if (kind_self == kind_sub) {
9227 return ! memcmp((char *)data_self +
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009228 (offset * PyUnicode_KIND(substring)),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009229 data_sub,
9230 PyUnicode_GET_LENGTH(substring) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009231 PyUnicode_KIND(substring));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009232 }
9233 /* otherwise we have to compare each character by first accesing it */
9234 else {
9235 /* We do not need to compare 0 and len(substring)-1 because
9236 the if statement above ensured already that they are equal
9237 when we end up here. */
9238 // TODO: honor direction and do a forward or backwards search
9239 for (i = 1; i < end_sub; ++i) {
9240 if (PyUnicode_READ(kind_self, data_self, offset + i) !=
9241 PyUnicode_READ(kind_sub, data_sub, i))
9242 return 0;
9243 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009244 return 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009245 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009246 }
9247
9248 return 0;
9249}
9250
Alexander Belopolsky40018472011-02-26 01:02:56 +00009251Py_ssize_t
9252PyUnicode_Tailmatch(PyObject *str,
9253 PyObject *substr,
9254 Py_ssize_t start,
9255 Py_ssize_t end,
9256 int direction)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009257{
Martin v. Löwis18e16552006-02-15 17:27:45 +00009258 Py_ssize_t result;
Tim Petersced69f82003-09-16 20:30:58 +00009259
Guido van Rossumd57fd912000-03-10 22:53:23 +00009260 str = PyUnicode_FromObject(str);
9261 if (str == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009262 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009263 substr = PyUnicode_FromObject(substr);
9264 if (substr == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009265 Py_DECREF(str);
9266 return -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009267 }
Tim Petersced69f82003-09-16 20:30:58 +00009268
Victor Stinner9db1a8b2011-10-23 20:04:37 +02009269 result = tailmatch(str, substr,
Benjamin Peterson29060642009-01-31 22:14:21 +00009270 start, end, direction);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009271 Py_DECREF(str);
9272 Py_DECREF(substr);
9273 return result;
9274}
9275
Guido van Rossumd57fd912000-03-10 22:53:23 +00009276/* Apply fixfct filter to the Unicode object self and return a
9277 reference to the modified object */
9278
Alexander Belopolsky40018472011-02-26 01:02:56 +00009279static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009280fixup(PyObject *self,
9281 Py_UCS4 (*fixfct)(PyObject *s))
Guido van Rossumd57fd912000-03-10 22:53:23 +00009282{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009283 PyObject *u;
9284 Py_UCS4 maxchar_old, maxchar_new = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009285
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009286 if (PyUnicode_READY(self) == -1)
9287 return NULL;
9288 maxchar_old = PyUnicode_MAX_CHAR_VALUE(self);
9289 u = PyUnicode_New(PyUnicode_GET_LENGTH(self),
9290 maxchar_old);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009291 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +00009292 return NULL;
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009293
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009294 Py_MEMCPY(PyUnicode_1BYTE_DATA(u), PyUnicode_1BYTE_DATA(self),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009295 PyUnicode_GET_LENGTH(u) * PyUnicode_KIND(u));
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +00009296
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009297 /* fix functions return the new maximum character in a string,
9298 if the kind of the resulting unicode object does not change,
9299 everything is fine. Otherwise we need to change the string kind
9300 and re-run the fix function. */
Victor Stinner9310abb2011-10-05 00:59:23 +02009301 maxchar_new = fixfct(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009302 if (maxchar_new == 0)
9303 /* do nothing, keep maxchar_new at 0 which means no changes. */;
9304 else if (maxchar_new <= 127)
9305 maxchar_new = 127;
9306 else if (maxchar_new <= 255)
9307 maxchar_new = 255;
9308 else if (maxchar_new <= 65535)
9309 maxchar_new = 65535;
9310 else
9311 maxchar_new = 1114111; /* 0x10ffff */
9312
9313 if (!maxchar_new && PyUnicode_CheckExact(self)) {
Benjamin Peterson29060642009-01-31 22:14:21 +00009314 /* fixfct should return TRUE if it modified the buffer. If
9315 FALSE, return a reference to the original buffer instead
9316 (to save space, not time) */
9317 Py_INCREF(self);
9318 Py_DECREF(u);
Victor Stinner7931d9a2011-11-04 00:22:48 +01009319 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009320 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009321 else if (maxchar_new == maxchar_old) {
9322 return u;
9323 }
9324 else {
9325 /* In case the maximum character changed, we need to
9326 convert the string to the new category. */
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009327 PyObject *v = PyUnicode_New(PyUnicode_GET_LENGTH(self), maxchar_new);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009328 if (v == NULL) {
9329 Py_DECREF(u);
9330 return NULL;
9331 }
9332 if (maxchar_new > maxchar_old) {
9333 /* If the maxchar increased so that the kind changed, not all
9334 characters are representable anymore and we need to fix the
9335 string again. This only happens in very few cases. */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009336 copy_characters(v, 0, self, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner9310abb2011-10-05 00:59:23 +02009337 maxchar_old = fixfct(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009338 assert(maxchar_old > 0 && maxchar_old <= maxchar_new);
9339 }
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009340 else {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009341 copy_characters(v, 0, u, 0, PyUnicode_GET_LENGTH(self));
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009342 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009343
9344 Py_DECREF(u);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009345 assert(_PyUnicode_CheckConsistency(v, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009346 return v;
9347 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009348}
9349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009350static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009351fixupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009352{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009353 /* No need to call PyUnicode_READY(self) because this function is only
9354 called as a callback from fixup() which does it already. */
9355 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9356 const int kind = PyUnicode_KIND(self);
9357 void *data = PyUnicode_DATA(self);
9358 int touched = 0;
9359 Py_UCS4 maxchar = 0;
9360 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009361
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009362 for (i = 0; i < len; ++i) {
9363 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9364 const Py_UCS4 up = Py_UNICODE_TOUPPER(ch);
9365 if (up != ch) {
9366 if (up > maxchar)
9367 maxchar = up;
9368 PyUnicode_WRITE(kind, data, i, up);
9369 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009370 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009371 else if (ch > maxchar)
9372 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009373 }
9374
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009375 if (touched)
9376 return maxchar;
9377 else
9378 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009379}
9380
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009381static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009382fixlower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009383{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009384 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9385 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9386 const int kind = PyUnicode_KIND(self);
9387 void *data = PyUnicode_DATA(self);
9388 int touched = 0;
9389 Py_UCS4 maxchar = 0;
9390 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009391
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009392 for(i = 0; i < len; ++i) {
9393 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9394 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9395 if (lo != ch) {
9396 if (lo > maxchar)
9397 maxchar = lo;
9398 PyUnicode_WRITE(kind, data, i, lo);
9399 touched = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +00009400 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009401 else if (ch > maxchar)
9402 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009403 }
9404
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009405 if (touched)
9406 return maxchar;
9407 else
9408 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009409}
9410
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009411static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009412fixswapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009413{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009414 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9415 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9416 const int kind = PyUnicode_KIND(self);
9417 void *data = PyUnicode_DATA(self);
9418 int touched = 0;
9419 Py_UCS4 maxchar = 0;
9420 Py_ssize_t i;
Tim Petersced69f82003-09-16 20:30:58 +00009421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009422 for(i = 0; i < len; ++i) {
9423 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9424 Py_UCS4 nu = 0;
9425
9426 if (Py_UNICODE_ISUPPER(ch))
9427 nu = Py_UNICODE_TOLOWER(ch);
9428 else if (Py_UNICODE_ISLOWER(ch))
9429 nu = Py_UNICODE_TOUPPER(ch);
9430
9431 if (nu != 0) {
9432 if (nu > maxchar)
9433 maxchar = nu;
9434 PyUnicode_WRITE(kind, data, i, nu);
9435 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009436 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009437 else if (ch > maxchar)
9438 maxchar = ch;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009439 }
9440
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009441 if (touched)
9442 return maxchar;
9443 else
9444 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009445}
9446
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009447static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009448fixcapitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009449{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009450 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9451 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9452 const int kind = PyUnicode_KIND(self);
9453 void *data = PyUnicode_DATA(self);
9454 int touched = 0;
9455 Py_UCS4 maxchar = 0;
9456 Py_ssize_t i = 0;
9457 Py_UCS4 ch;
Tim Petersced69f82003-09-16 20:30:58 +00009458
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009459 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +00009460 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009461
9462 ch = PyUnicode_READ(kind, data, i);
9463 if (!Py_UNICODE_ISUPPER(ch)) {
9464 maxchar = Py_UNICODE_TOUPPER(ch);
9465 PyUnicode_WRITE(kind, data, i, maxchar);
9466 touched = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009467 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009468 ++i;
9469 for(; i < len; ++i) {
9470 ch = PyUnicode_READ(kind, data, i);
9471 if (!Py_UNICODE_ISLOWER(ch)) {
9472 const Py_UCS4 lo = Py_UNICODE_TOLOWER(ch);
9473 if (lo > maxchar)
9474 maxchar = lo;
9475 PyUnicode_WRITE(kind, data, i, lo);
9476 touched = 1;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009477 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009478 else if (ch > maxchar)
9479 maxchar = ch;
Marc-André Lemburgfde66e12001-01-29 11:14:16 +00009480 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009481
9482 if (touched)
9483 return maxchar;
9484 else
9485 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009486}
9487
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009488static Py_UCS4
Victor Stinner9310abb2011-10-05 00:59:23 +02009489fixtitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009490{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009491 /* No need to call PyUnicode_READY(self) because fixup() which does it. */
9492 const Py_ssize_t len = PyUnicode_GET_LENGTH(self);
9493 const int kind = PyUnicode_KIND(self);
9494 void *data = PyUnicode_DATA(self);
9495 Py_UCS4 maxchar = 0;
9496 Py_ssize_t i = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009497 int previous_is_cased;
9498
9499 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009500 if (len == 1) {
9501 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9502 const Py_UCS4 ti = Py_UNICODE_TOTITLE(ch);
9503 if (ti != ch) {
9504 PyUnicode_WRITE(kind, data, i, ti);
9505 return ti;
Benjamin Peterson29060642009-01-31 22:14:21 +00009506 }
9507 else
9508 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009509 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009510 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009511 for(; i < len; ++i) {
9512 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
9513 Py_UCS4 nu;
Tim Petersced69f82003-09-16 20:30:58 +00009514
Benjamin Peterson29060642009-01-31 22:14:21 +00009515 if (previous_is_cased)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009516 nu = Py_UNICODE_TOLOWER(ch);
Benjamin Peterson29060642009-01-31 22:14:21 +00009517 else
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009518 nu = Py_UNICODE_TOTITLE(ch);
9519
9520 if (nu > maxchar)
9521 maxchar = nu;
9522 PyUnicode_WRITE(kind, data, i, nu);
Tim Petersced69f82003-09-16 20:30:58 +00009523
Benjamin Peterson29060642009-01-31 22:14:21 +00009524 if (Py_UNICODE_ISLOWER(ch) ||
9525 Py_UNICODE_ISUPPER(ch) ||
9526 Py_UNICODE_ISTITLE(ch))
9527 previous_is_cased = 1;
9528 else
9529 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009530 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009531 return maxchar;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009532}
9533
Tim Peters8ce9f162004-08-27 01:49:32 +00009534PyObject *
9535PyUnicode_Join(PyObject *separator, PyObject *seq)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009536{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009537 PyObject *sep = NULL;
Victor Stinnerdd077322011-10-07 17:02:31 +02009538 Py_ssize_t seplen;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009539 PyObject *res = NULL; /* the result */
Tim Peters05eba1f2004-08-27 21:32:02 +00009540 PyObject *fseq; /* PySequence_Fast(seq) */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009541 Py_ssize_t seqlen; /* len(fseq) -- number of items in sequence */
9542 PyObject **items;
Tim Peters8ce9f162004-08-27 01:49:32 +00009543 PyObject *item;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009544 Py_ssize_t sz, i, res_offset;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009545 Py_UCS4 maxchar;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009546 Py_UCS4 item_maxchar;
Victor Stinnerdd077322011-10-07 17:02:31 +02009547 int use_memcpy;
9548 unsigned char *res_data = NULL, *sep_data = NULL;
9549 PyObject *last_obj;
9550 unsigned int kind = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009551
Tim Peters05eba1f2004-08-27 21:32:02 +00009552 fseq = PySequence_Fast(seq, "");
9553 if (fseq == NULL) {
Benjamin Peterson14339b62009-01-31 16:36:08 +00009554 return NULL;
Tim Peters8ce9f162004-08-27 01:49:32 +00009555 }
9556
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009557 /* NOTE: the following code can't call back into Python code,
9558 * so we are sure that fseq won't be mutated.
Tim Peters91879ab2004-08-27 22:35:44 +00009559 */
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009560
Tim Peters05eba1f2004-08-27 21:32:02 +00009561 seqlen = PySequence_Fast_GET_SIZE(fseq);
9562 /* If empty sequence, return u"". */
9563 if (seqlen == 0) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009564 Py_DECREF(fseq);
9565 Py_INCREF(unicode_empty);
9566 res = unicode_empty;
9567 return res;
Tim Peters05eba1f2004-08-27 21:32:02 +00009568 }
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009569
Tim Peters05eba1f2004-08-27 21:32:02 +00009570 /* If singleton sequence with an exact Unicode, return that. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009571 last_obj = NULL;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009572 items = PySequence_Fast_ITEMS(fseq);
Victor Stinneracf47b82011-10-06 12:32:37 +02009573 if (seqlen == 1) {
9574 if (PyUnicode_CheckExact(items[0])) {
9575 res = items[0];
9576 Py_INCREF(res);
9577 Py_DECREF(fseq);
9578 return res;
9579 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009580 seplen = 0;
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009581 maxchar = 0;
Tim Peters8ce9f162004-08-27 01:49:32 +00009582 }
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009583 else {
Victor Stinneracf47b82011-10-06 12:32:37 +02009584 /* Set up sep and seplen */
9585 if (separator == NULL) {
9586 /* fall back to a blank space separator */
9587 sep = PyUnicode_FromOrdinal(' ');
9588 if (!sep)
9589 goto onError;
Victor Stinnerdd077322011-10-07 17:02:31 +02009590 seplen = 1;
Victor Stinneracf47b82011-10-06 12:32:37 +02009591 maxchar = 32;
Tim Peters05eba1f2004-08-27 21:32:02 +00009592 }
Victor Stinneracf47b82011-10-06 12:32:37 +02009593 else {
9594 if (!PyUnicode_Check(separator)) {
9595 PyErr_Format(PyExc_TypeError,
9596 "separator: expected str instance,"
9597 " %.80s found",
9598 Py_TYPE(separator)->tp_name);
9599 goto onError;
9600 }
9601 if (PyUnicode_READY(separator))
9602 goto onError;
9603 sep = separator;
9604 seplen = PyUnicode_GET_LENGTH(separator);
9605 maxchar = PyUnicode_MAX_CHAR_VALUE(separator);
9606 /* inc refcount to keep this code path symmetric with the
9607 above case of a blank separator */
9608 Py_INCREF(sep);
9609 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009610 last_obj = sep;
Tim Peters05eba1f2004-08-27 21:32:02 +00009611 }
9612
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009613 /* There are at least two things to join, or else we have a subclass
9614 * of str in the sequence.
9615 * Do a pre-pass to figure out the total amount of space we'll
9616 * need (sz), and see whether all argument are strings.
9617 */
9618 sz = 0;
Victor Stinnerdd077322011-10-07 17:02:31 +02009619#ifdef Py_DEBUG
9620 use_memcpy = 0;
9621#else
9622 use_memcpy = 1;
9623#endif
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009624 for (i = 0; i < seqlen; i++) {
9625 const Py_ssize_t old_sz = sz;
9626 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009627 if (!PyUnicode_Check(item)) {
9628 PyErr_Format(PyExc_TypeError,
9629 "sequence item %zd: expected str instance,"
9630 " %.80s found",
9631 i, Py_TYPE(item)->tp_name);
9632 goto onError;
9633 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009634 if (PyUnicode_READY(item) == -1)
9635 goto onError;
9636 sz += PyUnicode_GET_LENGTH(item);
9637 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);
Victor Stinnerc6f0df72011-10-06 15:58:54 +02009638 maxchar = Py_MAX(maxchar, item_maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009639 if (i != 0)
9640 sz += seplen;
9641 if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
9642 PyErr_SetString(PyExc_OverflowError,
Benjamin Peterson29060642009-01-31 22:14:21 +00009643 "join() result is too long for a Python string");
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009644 goto onError;
9645 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009646 if (use_memcpy && last_obj != NULL) {
9647 if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))
9648 use_memcpy = 0;
9649 }
9650 last_obj = item;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009651 }
Tim Petersced69f82003-09-16 20:30:58 +00009652
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009653 res = PyUnicode_New(sz, maxchar);
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009654 if (res == NULL)
9655 goto onError;
Tim Peters91879ab2004-08-27 22:35:44 +00009656
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009657 /* Catenate everything. */
Victor Stinnerdd077322011-10-07 17:02:31 +02009658#ifdef Py_DEBUG
9659 use_memcpy = 0;
9660#else
9661 if (use_memcpy) {
9662 res_data = PyUnicode_1BYTE_DATA(res);
9663 kind = PyUnicode_KIND(res);
9664 if (seplen != 0)
9665 sep_data = PyUnicode_1BYTE_DATA(sep);
9666 }
9667#endif
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009668 for (i = 0, res_offset = 0; i < seqlen; ++i) {
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009669 Py_ssize_t itemlen;
Antoine Pitrouaf14b792008-08-07 21:50:41 +00009670 item = items[i];
Benjamin Peterson29060642009-01-31 22:14:21 +00009671 /* Copy item, and maybe the separator. */
Victor Stinner9ce5a832011-10-03 23:36:02 +02009672 if (i && seplen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009673 if (use_memcpy) {
9674 Py_MEMCPY(res_data,
9675 sep_data,
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009676 kind * seplen);
9677 res_data += kind * seplen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009678 }
9679 else {
9680 copy_characters(res, res_offset, sep, 0, seplen);
9681 res_offset += seplen;
9682 }
Benjamin Peterson29060642009-01-31 22:14:21 +00009683 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009684 itemlen = PyUnicode_GET_LENGTH(item);
9685 if (itemlen != 0) {
Victor Stinnerdd077322011-10-07 17:02:31 +02009686 if (use_memcpy) {
9687 Py_MEMCPY(res_data,
9688 PyUnicode_DATA(item),
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009689 kind * itemlen);
9690 res_data += kind * itemlen;
Victor Stinnerdd077322011-10-07 17:02:31 +02009691 }
9692 else {
9693 copy_characters(res, res_offset, item, 0, itemlen);
9694 res_offset += itemlen;
9695 }
Victor Stinner9ce5a832011-10-03 23:36:02 +02009696 }
Tim Peters05eba1f2004-08-27 21:32:02 +00009697 }
Victor Stinnerdd077322011-10-07 17:02:31 +02009698 if (use_memcpy)
9699 assert(res_data == PyUnicode_1BYTE_DATA(res)
Martin v. Löwisc47adb02011-10-07 20:55:35 +02009700 + kind * PyUnicode_GET_LENGTH(res));
Victor Stinnerdd077322011-10-07 17:02:31 +02009701 else
9702 assert(res_offset == PyUnicode_GET_LENGTH(res));
Tim Peters8ce9f162004-08-27 01:49:32 +00009703
Tim Peters05eba1f2004-08-27 21:32:02 +00009704 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009705 Py_XDECREF(sep);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009706 assert(_PyUnicode_CheckConsistency(res, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009707 return res;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009708
Benjamin Peterson29060642009-01-31 22:14:21 +00009709 onError:
Tim Peters05eba1f2004-08-27 21:32:02 +00009710 Py_DECREF(fseq);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009711 Py_XDECREF(sep);
Tim Peters8ce9f162004-08-27 01:49:32 +00009712 Py_XDECREF(res);
Guido van Rossumd57fd912000-03-10 22:53:23 +00009713 return NULL;
9714}
9715
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009716#define FILL(kind, data, value, start, length) \
9717 do { \
9718 Py_ssize_t i_ = 0; \
9719 assert(kind != PyUnicode_WCHAR_KIND); \
9720 switch ((kind)) { \
9721 case PyUnicode_1BYTE_KIND: { \
9722 unsigned char * to_ = (unsigned char *)((data)) + (start); \
9723 memset(to_, (unsigned char)value, length); \
9724 break; \
9725 } \
9726 case PyUnicode_2BYTE_KIND: { \
9727 Py_UCS2 * to_ = (Py_UCS2 *)((data)) + (start); \
9728 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9729 break; \
9730 } \
9731 default: { \
9732 Py_UCS4 * to_ = (Py_UCS4 *)((data)) + (start); \
9733 for (; i_ < (length); ++i_, ++to_) *to_ = (value); \
9734 break; \
9735 } \
9736 } \
9737 } while (0)
9738
Victor Stinner9310abb2011-10-05 00:59:23 +02009739static PyObject *
9740pad(PyObject *self,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009741 Py_ssize_t left,
9742 Py_ssize_t right,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009743 Py_UCS4 fill)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009744{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009745 PyObject *u;
9746 Py_UCS4 maxchar;
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009747 int kind;
9748 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009749
9750 if (left < 0)
9751 left = 0;
9752 if (right < 0)
9753 right = 0;
9754
Tim Peters7a29bd52001-09-12 03:03:31 +00009755 if (left == 0 && right == 0 && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +00009756 Py_INCREF(self);
9757 return self;
9758 }
9759
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009760 if (left > PY_SSIZE_T_MAX - _PyUnicode_LENGTH(self) ||
9761 right > PY_SSIZE_T_MAX - (left + _PyUnicode_LENGTH(self))) {
Neal Norwitz3ce5d922008-08-24 07:08:55 +00009762 PyErr_SetString(PyExc_OverflowError, "padded string is too long");
9763 return NULL;
9764 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009765 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
9766 if (fill > maxchar)
9767 maxchar = fill;
9768 u = PyUnicode_New(left + _PyUnicode_LENGTH(self) + right, maxchar);
Victor Stinner6c7a52a2011-09-28 21:39:17 +02009769 if (!u)
9770 return NULL;
9771
9772 kind = PyUnicode_KIND(u);
9773 data = PyUnicode_DATA(u);
9774 if (left)
9775 FILL(kind, data, fill, 0, left);
9776 if (right)
9777 FILL(kind, data, fill, left + _PyUnicode_LENGTH(self), right);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +02009778 copy_characters(u, left, self, 0, _PyUnicode_LENGTH(self));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +02009779 assert(_PyUnicode_CheckConsistency(u, 1));
9780 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009781}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009782#undef FILL
Guido van Rossumd57fd912000-03-10 22:53:23 +00009783
Alexander Belopolsky40018472011-02-26 01:02:56 +00009784PyObject *
9785PyUnicode_Splitlines(PyObject *string, int keepends)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009786{
Guido van Rossumd57fd912000-03-10 22:53:23 +00009787 PyObject *list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009788
9789 string = PyUnicode_FromObject(string);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009790 if (string == NULL || PyUnicode_READY(string) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +00009791 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009792
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009793 switch(PyUnicode_KIND(string)) {
9794 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009795 if (PyUnicode_IS_ASCII(string))
9796 list = asciilib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009797 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009798 PyUnicode_GET_LENGTH(string), keepends);
9799 else
9800 list = ucs1lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009801 string, PyUnicode_1BYTE_DATA(string),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009802 PyUnicode_GET_LENGTH(string), keepends);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009803 break;
9804 case PyUnicode_2BYTE_KIND:
9805 list = ucs2lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009806 string, PyUnicode_2BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009807 PyUnicode_GET_LENGTH(string), keepends);
9808 break;
9809 case PyUnicode_4BYTE_KIND:
9810 list = ucs4lib_splitlines(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009811 string, PyUnicode_4BYTE_DATA(string),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009812 PyUnicode_GET_LENGTH(string), keepends);
9813 break;
9814 default:
9815 assert(0);
9816 list = 0;
9817 }
Guido van Rossumd57fd912000-03-10 22:53:23 +00009818 Py_DECREF(string);
9819 return list;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009820}
9821
Alexander Belopolsky40018472011-02-26 01:02:56 +00009822static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009823split(PyObject *self,
9824 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009825 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +00009826{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009827 int kind1, kind2, kind;
9828 void *buf1, *buf2;
9829 Py_ssize_t len1, len2;
9830 PyObject* out;
9831
Guido van Rossumd57fd912000-03-10 22:53:23 +00009832 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009833 maxcount = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009834
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009835 if (PyUnicode_READY(self) == -1)
9836 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009837
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009838 if (substring == NULL)
9839 switch(PyUnicode_KIND(self)) {
9840 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009841 if (PyUnicode_IS_ASCII(self))
9842 return asciilib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009843 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009844 PyUnicode_GET_LENGTH(self), maxcount
9845 );
9846 else
9847 return ucs1lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009848 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009849 PyUnicode_GET_LENGTH(self), maxcount
9850 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009851 case PyUnicode_2BYTE_KIND:
9852 return ucs2lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009853 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009854 PyUnicode_GET_LENGTH(self), maxcount
9855 );
9856 case PyUnicode_4BYTE_KIND:
9857 return ucs4lib_split_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009858 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009859 PyUnicode_GET_LENGTH(self), maxcount
9860 );
9861 default:
9862 assert(0);
9863 return NULL;
9864 }
9865
9866 if (PyUnicode_READY(substring) == -1)
9867 return NULL;
9868
9869 kind1 = PyUnicode_KIND(self);
9870 kind2 = PyUnicode_KIND(substring);
9871 kind = kind1 > kind2 ? kind1 : kind2;
9872 buf1 = PyUnicode_DATA(self);
9873 buf2 = PyUnicode_DATA(substring);
9874 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009875 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009876 if (!buf1)
9877 return NULL;
9878 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009879 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009880 if (!buf2) {
9881 if (kind1 != kind) PyMem_Free(buf1);
9882 return NULL;
9883 }
9884 len1 = PyUnicode_GET_LENGTH(self);
9885 len2 = PyUnicode_GET_LENGTH(substring);
9886
9887 switch(kind) {
9888 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009889 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9890 out = asciilib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009891 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009892 else
9893 out = ucs1lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009894 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009895 break;
9896 case PyUnicode_2BYTE_KIND:
9897 out = ucs2lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009898 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009899 break;
9900 case PyUnicode_4BYTE_KIND:
9901 out = ucs4lib_split(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009902 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009903 break;
9904 default:
9905 out = NULL;
9906 }
9907 if (kind1 != kind)
9908 PyMem_Free(buf1);
9909 if (kind2 != kind)
9910 PyMem_Free(buf2);
9911 return out;
Guido van Rossumd57fd912000-03-10 22:53:23 +00009912}
9913
Alexander Belopolsky40018472011-02-26 01:02:56 +00009914static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +02009915rsplit(PyObject *self,
9916 PyObject *substring,
Alexander Belopolsky40018472011-02-26 01:02:56 +00009917 Py_ssize_t maxcount)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009918{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009919 int kind1, kind2, kind;
9920 void *buf1, *buf2;
9921 Py_ssize_t len1, len2;
9922 PyObject* out;
9923
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009924 if (maxcount < 0)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00009925 maxcount = PY_SSIZE_T_MAX;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009926
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009927 if (PyUnicode_READY(self) == -1)
9928 return NULL;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +00009929
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009930 if (substring == NULL)
9931 switch(PyUnicode_KIND(self)) {
9932 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009933 if (PyUnicode_IS_ASCII(self))
9934 return asciilib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009935 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009936 PyUnicode_GET_LENGTH(self), maxcount
9937 );
9938 else
9939 return ucs1lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009940 self, PyUnicode_1BYTE_DATA(self),
Victor Stinnerc3cec782011-10-05 21:24:08 +02009941 PyUnicode_GET_LENGTH(self), maxcount
9942 );
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009943 case PyUnicode_2BYTE_KIND:
9944 return ucs2lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009945 self, PyUnicode_2BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009946 PyUnicode_GET_LENGTH(self), maxcount
9947 );
9948 case PyUnicode_4BYTE_KIND:
9949 return ucs4lib_rsplit_whitespace(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009950 self, PyUnicode_4BYTE_DATA(self),
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009951 PyUnicode_GET_LENGTH(self), maxcount
9952 );
9953 default:
9954 assert(0);
9955 return NULL;
9956 }
9957
9958 if (PyUnicode_READY(substring) == -1)
9959 return NULL;
9960
9961 kind1 = PyUnicode_KIND(self);
9962 kind2 = PyUnicode_KIND(substring);
9963 kind = kind1 > kind2 ? kind1 : kind2;
9964 buf1 = PyUnicode_DATA(self);
9965 buf2 = PyUnicode_DATA(substring);
9966 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009967 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009968 if (!buf1)
9969 return NULL;
9970 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +01009971 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009972 if (!buf2) {
9973 if (kind1 != kind) PyMem_Free(buf1);
9974 return NULL;
9975 }
9976 len1 = PyUnicode_GET_LENGTH(self);
9977 len2 = PyUnicode_GET_LENGTH(substring);
9978
9979 switch(kind) {
9980 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +02009981 if (PyUnicode_IS_ASCII(self) && PyUnicode_IS_ASCII(substring))
9982 out = asciilib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009983 self, buf1, len1, buf2, len2, maxcount);
Victor Stinnerc3cec782011-10-05 21:24:08 +02009984 else
9985 out = ucs1lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009986 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009987 break;
9988 case PyUnicode_2BYTE_KIND:
9989 out = ucs2lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009990 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009991 break;
9992 case PyUnicode_4BYTE_KIND:
9993 out = ucs4lib_rsplit(
Victor Stinner7931d9a2011-11-04 00:22:48 +01009994 self, buf1, len1, buf2, len2, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02009995 break;
9996 default:
9997 out = NULL;
9998 }
9999 if (kind1 != kind)
10000 PyMem_Free(buf1);
10001 if (kind2 != kind)
10002 PyMem_Free(buf2);
10003 return out;
10004}
10005
10006static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010007anylib_find(int kind, PyObject *str1, void *buf1, Py_ssize_t len1,
10008 PyObject *str2, void *buf2, Py_ssize_t len2, Py_ssize_t offset)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010009{
10010 switch(kind) {
10011 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010012 if (PyUnicode_IS_ASCII(str1) && PyUnicode_IS_ASCII(str2))
10013 return asciilib_find(buf1, len1, buf2, len2, offset);
10014 else
10015 return ucs1lib_find(buf1, len1, buf2, len2, offset);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010016 case PyUnicode_2BYTE_KIND:
10017 return ucs2lib_find(buf1, len1, buf2, len2, offset);
10018 case PyUnicode_4BYTE_KIND:
10019 return ucs4lib_find(buf1, len1, buf2, len2, offset);
10020 }
10021 assert(0);
10022 return -1;
10023}
10024
10025static Py_ssize_t
Victor Stinnerc3cec782011-10-05 21:24:08 +020010026anylib_count(int kind, PyObject *sstr, void* sbuf, Py_ssize_t slen,
10027 PyObject *str1, void *buf1, Py_ssize_t len1, Py_ssize_t maxcount)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010028{
10029 switch(kind) {
10030 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020010031 if (PyUnicode_IS_ASCII(sstr) && PyUnicode_IS_ASCII(str1))
10032 return asciilib_count(sbuf, slen, buf1, len1, maxcount);
10033 else
10034 return ucs1lib_count(sbuf, slen, buf1, len1, maxcount);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010035 case PyUnicode_2BYTE_KIND:
10036 return ucs2lib_count(sbuf, slen, buf1, len1, maxcount);
10037 case PyUnicode_4BYTE_KIND:
10038 return ucs4lib_count(sbuf, slen, buf1, len1, maxcount);
10039 }
10040 assert(0);
10041 return 0;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000010042}
10043
Alexander Belopolsky40018472011-02-26 01:02:56 +000010044static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010045replace(PyObject *self, PyObject *str1,
10046 PyObject *str2, Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010047{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010048 PyObject *u;
10049 char *sbuf = PyUnicode_DATA(self);
10050 char *buf1 = PyUnicode_DATA(str1);
10051 char *buf2 = PyUnicode_DATA(str2);
10052 int srelease = 0, release1 = 0, release2 = 0;
10053 int skind = PyUnicode_KIND(self);
10054 int kind1 = PyUnicode_KIND(str1);
10055 int kind2 = PyUnicode_KIND(str2);
10056 Py_ssize_t slen = PyUnicode_GET_LENGTH(self);
10057 Py_ssize_t len1 = PyUnicode_GET_LENGTH(str1);
10058 Py_ssize_t len2 = PyUnicode_GET_LENGTH(str2);
Victor Stinner49a0a212011-10-12 23:46:10 +020010059 int mayshrink;
10060 Py_UCS4 maxchar, maxchar_str2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010061
10062 if (maxcount < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000010063 maxcount = PY_SSIZE_T_MAX;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010064 else if (maxcount == 0 || slen == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010065 goto nothing;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010066
Victor Stinner59de0ee2011-10-07 10:01:28 +020010067 if (str1 == str2)
10068 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010069 if (skind < kind1)
10070 /* substring too wide to be present */
10071 goto nothing;
10072
Victor Stinner49a0a212011-10-12 23:46:10 +020010073 maxchar = PyUnicode_MAX_CHAR_VALUE(self);
10074 maxchar_str2 = PyUnicode_MAX_CHAR_VALUE(str2);
10075 /* Replacing str1 with str2 may cause a maxchar reduction in the
10076 result string. */
10077 mayshrink = (maxchar_str2 < maxchar);
10078 maxchar = Py_MAX(maxchar, maxchar_str2);
10079
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010080 if (len1 == len2) {
Antoine Pitroucbfdee32010-01-13 08:58:08 +000010081 Py_ssize_t i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010082 /* same length */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010083 if (len1 == 0)
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010084 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010085 if (len1 == 1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010086 /* replace characters */
Victor Stinner49a0a212011-10-12 23:46:10 +020010087 Py_UCS4 u1, u2;
10088 int rkind;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010089 u1 = PyUnicode_READ_CHAR(str1, 0);
Antoine Pitrouf0b934b2011-10-13 18:55:09 +020010090 if (findchar(sbuf, PyUnicode_KIND(self),
10091 slen, u1, 1) < 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010092 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010093 u2 = PyUnicode_READ_CHAR(str2, 0);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010094 u = PyUnicode_New(slen, maxchar);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010095 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010096 goto error;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010097 copy_characters(u, 0, self, 0, slen);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010098 rkind = PyUnicode_KIND(u);
10099 for (i = 0; i < PyUnicode_GET_LENGTH(u); i++)
10100 if (PyUnicode_READ(rkind, PyUnicode_DATA(u), i) == u1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010101 if (--maxcount < 0)
10102 break;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010103 PyUnicode_WRITE(rkind, PyUnicode_DATA(u), i, u2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010104 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010105 }
10106 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010107 int rkind = skind;
10108 char *res;
Victor Stinner25a4b292011-10-06 12:31:55 +020010109
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010110 if (kind1 < rkind) {
10111 /* widen substring */
10112 buf1 = _PyUnicode_AsKind(str1, rkind);
10113 if (!buf1) goto error;
10114 release1 = 1;
10115 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010116 i = anylib_find(rkind, self, sbuf, slen, str1, buf1, len1, 0);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010117 if (i < 0)
10118 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010119 if (rkind > kind2) {
10120 /* widen replacement */
10121 buf2 = _PyUnicode_AsKind(str2, rkind);
10122 if (!buf2) goto error;
10123 release2 = 1;
10124 }
10125 else if (rkind < kind2) {
10126 /* widen self and buf1 */
10127 rkind = kind2;
10128 if (release1) PyMem_Free(buf1);
10129 sbuf = _PyUnicode_AsKind(self, rkind);
10130 if (!sbuf) goto error;
10131 srelease = 1;
10132 buf1 = _PyUnicode_AsKind(str1, rkind);
10133 if (!buf1) goto error;
10134 release1 = 1;
10135 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010136 u = PyUnicode_New(slen, maxchar);
10137 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010138 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010139 assert(PyUnicode_KIND(u) == rkind);
10140 res = PyUnicode_DATA(u);
Victor Stinner25a4b292011-10-06 12:31:55 +020010141
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010142 memcpy(res, sbuf, rkind * slen);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010143 /* change everything in-place, starting with this one */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010144 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010145 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010146 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010147 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010148
10149 while ( --maxcount > 0) {
Victor Stinnerc3cec782011-10-05 21:24:08 +020010150 i = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010151 sbuf+rkind*i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010152 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010153 if (i == -1)
10154 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010155 memcpy(res + rkind * i,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010156 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010157 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010158 i += len1;
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010159 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010160 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010161 }
10162 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010163 Py_ssize_t n, i, j, ires;
10164 Py_ssize_t product, new_size;
10165 int rkind = skind;
10166 char *res;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010167
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010168 if (kind1 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010169 /* widen substring */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010170 buf1 = _PyUnicode_AsKind(str1, rkind);
10171 if (!buf1) goto error;
10172 release1 = 1;
10173 }
Victor Stinnerc3cec782011-10-05 21:24:08 +020010174 n = anylib_count(rkind, self, sbuf, slen, str1, buf1, len1, maxcount);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010175 if (n == 0)
10176 goto nothing;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010177 if (kind2 < rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010178 /* widen replacement */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010179 buf2 = _PyUnicode_AsKind(str2, rkind);
10180 if (!buf2) goto error;
10181 release2 = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010182 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010183 else if (kind2 > rkind) {
Victor Stinner49a0a212011-10-12 23:46:10 +020010184 /* widen self and buf1 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010185 rkind = kind2;
10186 sbuf = _PyUnicode_AsKind(self, rkind);
10187 if (!sbuf) goto error;
10188 srelease = 1;
10189 if (release1) PyMem_Free(buf1);
10190 buf1 = _PyUnicode_AsKind(str1, rkind);
10191 if (!buf1) goto error;
10192 release1 = 1;
10193 }
10194 /* new_size = PyUnicode_GET_LENGTH(self) + n * (PyUnicode_GET_LENGTH(str2) -
10195 PyUnicode_GET_LENGTH(str1))); */
10196 product = n * (len2-len1);
10197 if ((product / (len2-len1)) != n) {
10198 PyErr_SetString(PyExc_OverflowError,
10199 "replace string is too long");
10200 goto error;
10201 }
10202 new_size = slen + product;
Victor Stinner49a0a212011-10-12 23:46:10 +020010203 if (new_size == 0) {
10204 Py_INCREF(unicode_empty);
10205 u = unicode_empty;
10206 goto done;
10207 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010208 if (new_size < 0 || new_size > (PY_SSIZE_T_MAX >> (rkind-1))) {
10209 PyErr_SetString(PyExc_OverflowError,
10210 "replace string is too long");
10211 goto error;
10212 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010213 u = PyUnicode_New(new_size, maxchar);
10214 if (!u)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010215 goto error;
Victor Stinner49a0a212011-10-12 23:46:10 +020010216 assert(PyUnicode_KIND(u) == rkind);
10217 res = PyUnicode_DATA(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010218 ires = i = 0;
10219 if (len1 > 0) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010220 while (n-- > 0) {
10221 /* look for next match */
Victor Stinnerc3cec782011-10-05 21:24:08 +020010222 j = anylib_find(rkind, self,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010223 sbuf + rkind * i, slen-i,
Victor Stinnerc3cec782011-10-05 21:24:08 +020010224 str1, buf1, len1, i);
Antoine Pitrouf2c54842010-01-13 08:07:53 +000010225 if (j == -1)
10226 break;
10227 else if (j > i) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010228 /* copy unchanged part [i:j] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010229 memcpy(res + rkind * ires,
10230 sbuf + rkind * i,
10231 rkind * (j-i));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010232 ires += j - i;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010233 }
10234 /* copy substitution string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010235 if (len2 > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010236 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010237 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010238 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010239 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010240 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010241 i = j + len1;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010242 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010243 if (i < slen)
Thomas Wouters477c8d52006-05-27 19:21:47 +000010244 /* copy tail [i:] */
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010245 memcpy(res + rkind * ires,
10246 sbuf + rkind * i,
10247 rkind * (slen-i));
Victor Stinner49a0a212011-10-12 23:46:10 +020010248 }
10249 else {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010250 /* interleave */
10251 while (n > 0) {
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010252 memcpy(res + rkind * ires,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010253 buf2,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010254 rkind * len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010255 ires += len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010256 if (--n <= 0)
10257 break;
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010258 memcpy(res + rkind * ires,
10259 sbuf + rkind * i,
10260 rkind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010261 ires++;
10262 i++;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010263 }
Martin v. Löwisc47adb02011-10-07 20:55:35 +020010264 memcpy(res + rkind * ires,
10265 sbuf + rkind * i,
10266 rkind * (slen-i));
Thomas Wouters477c8d52006-05-27 19:21:47 +000010267 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010268 }
10269
10270 if (mayshrink) {
Victor Stinner25a4b292011-10-06 12:31:55 +020010271 unicode_adjust_maxchar(&u);
10272 if (u == NULL)
10273 goto error;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010274 }
Victor Stinner49a0a212011-10-12 23:46:10 +020010275
10276 done:
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010277 if (srelease)
10278 PyMem_FREE(sbuf);
10279 if (release1)
10280 PyMem_FREE(buf1);
10281 if (release2)
10282 PyMem_FREE(buf2);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010283 assert(_PyUnicode_CheckConsistency(u, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010284 return u;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010285
Benjamin Peterson29060642009-01-31 22:14:21 +000010286 nothing:
Thomas Wouters477c8d52006-05-27 19:21:47 +000010287 /* nothing to replace; return original string (when possible) */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010288 if (srelease)
10289 PyMem_FREE(sbuf);
10290 if (release1)
10291 PyMem_FREE(buf1);
10292 if (release2)
10293 PyMem_FREE(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010294 if (PyUnicode_CheckExact(self)) {
10295 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010296 return self;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010297 }
Victor Stinner034f6cf2011-09-30 02:26:44 +020010298 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010299 error:
10300 if (srelease && sbuf)
10301 PyMem_FREE(sbuf);
10302 if (release1 && buf1)
10303 PyMem_FREE(buf1);
10304 if (release2 && buf2)
10305 PyMem_FREE(buf2);
10306 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010307}
10308
10309/* --- Unicode Object Methods --------------------------------------------- */
10310
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010311PyDoc_STRVAR(title__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010312 "S.title() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010313\n\
10314Return a titlecased version of S, i.e. words start with title case\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010315characters, all remaining cased characters have lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010316
10317static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010318unicode_title(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010319{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010320 return fixup(self, fixtitle);
10321}
10322
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010323PyDoc_STRVAR(capitalize__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010324 "S.capitalize() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010325\n\
10326Return a capitalized version of S, i.e. make the first character\n\
Senthil Kumarane51ee8a2010-07-05 12:00:56 +000010327have upper case and the rest lower case.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010328
10329static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020010330unicode_capitalize(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010331{
Guido van Rossumd57fd912000-03-10 22:53:23 +000010332 return fixup(self, fixcapitalize);
10333}
10334
10335#if 0
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010336PyDoc_STRVAR(capwords__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010337 "S.capwords() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010338\n\
10339Apply .capitalize() to all words in S and return the result with\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010340normalized whitespace (all whitespace strings are replaced by ' ').");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010341
10342static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010343unicode_capwords(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010344{
10345 PyObject *list;
10346 PyObject *item;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010347 Py_ssize_t i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010348
Guido van Rossumd57fd912000-03-10 22:53:23 +000010349 /* Split into words */
10350 list = split(self, NULL, -1);
10351 if (!list)
10352 return NULL;
10353
10354 /* Capitalize each word */
10355 for (i = 0; i < PyList_GET_SIZE(list); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010356 item = fixup(PyList_GET_ITEM(list, i),
Benjamin Peterson29060642009-01-31 22:14:21 +000010357 fixcapitalize);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010358 if (item == NULL)
10359 goto onError;
10360 Py_DECREF(PyList_GET_ITEM(list, i));
10361 PyList_SET_ITEM(list, i, item);
10362 }
10363
10364 /* Join the words to form a new string */
10365 item = PyUnicode_Join(NULL, list);
10366
Benjamin Peterson29060642009-01-31 22:14:21 +000010367 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010368 Py_DECREF(list);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010369 return item;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010370}
10371#endif
10372
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010373/* Argument converter. Coerces to a single unicode character */
10374
10375static int
10376convert_uc(PyObject *obj, void *addr)
10377{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010378 Py_UCS4 *fillcharloc = (Py_UCS4 *)addr;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010379 PyObject *uniobj;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010380
Benjamin Peterson14339b62009-01-31 16:36:08 +000010381 uniobj = PyUnicode_FromObject(obj);
10382 if (uniobj == NULL) {
10383 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010384 "The fill character cannot be converted to Unicode");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010385 return 0;
10386 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010387 if (PyUnicode_GET_LENGTH(uniobj) != 1) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000010388 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000010389 "The fill character must be exactly one character long");
Benjamin Peterson14339b62009-01-31 16:36:08 +000010390 Py_DECREF(uniobj);
10391 return 0;
10392 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010393 *fillcharloc = PyUnicode_READ_CHAR(uniobj, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010394 Py_DECREF(uniobj);
10395 return 1;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010396}
10397
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010398PyDoc_STRVAR(center__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010399 "S.center(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010400\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010401Return S centered in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000010402done using the specified fill character (default is a space)");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010403
10404static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020010405unicode_center(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010406{
Martin v. Löwis18e16552006-02-15 17:27:45 +000010407 Py_ssize_t marg, left;
10408 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010409 Py_UCS4 fillchar = ' ';
10410
Victor Stinnere9a29352011-10-01 02:14:59 +020010411 if (!PyArg_ParseTuple(args, "n|O&:center", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010412 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010413
Victor Stinnere9a29352011-10-01 02:14:59 +020010414 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010415 return NULL;
10416
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010417 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000010418 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010010419 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010420 }
10421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010422 marg = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010423 left = marg / 2 + (marg & width & 1);
10424
Victor Stinner9310abb2011-10-05 00:59:23 +020010425 return pad(self, left, marg - left, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010426}
10427
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010428/* This function assumes that str1 and str2 are readied by the caller. */
10429
Marc-André Lemburge5034372000-08-08 08:04:29 +000010430static int
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010431unicode_compare(PyObject *str1, PyObject *str2)
Marc-André Lemburge5034372000-08-08 08:04:29 +000010432{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010433 int kind1, kind2;
10434 void *data1, *data2;
10435 Py_ssize_t len1, len2, i;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010436
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010437 kind1 = PyUnicode_KIND(str1);
10438 kind2 = PyUnicode_KIND(str2);
10439 data1 = PyUnicode_DATA(str1);
10440 data2 = PyUnicode_DATA(str2);
10441 len1 = PyUnicode_GET_LENGTH(str1);
10442 len2 = PyUnicode_GET_LENGTH(str2);
Marc-André Lemburge5034372000-08-08 08:04:29 +000010443
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010444 for (i = 0; i < len1 && i < len2; ++i) {
10445 Py_UCS4 c1, c2;
10446 c1 = PyUnicode_READ(kind1, data1, i);
10447 c2 = PyUnicode_READ(kind2, data2, i);
Fredrik Lundh45714e92001-06-26 16:39:36 +000010448
10449 if (c1 != c2)
10450 return (c1 < c2) ? -1 : 1;
Marc-André Lemburge5034372000-08-08 08:04:29 +000010451 }
10452
10453 return (len1 < len2) ? -1 : (len1 != len2);
10454}
10455
Alexander Belopolsky40018472011-02-26 01:02:56 +000010456int
10457PyUnicode_Compare(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010458{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010459 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10460 if (PyUnicode_READY(left) == -1 ||
10461 PyUnicode_READY(right) == -1)
10462 return -1;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010463 return unicode_compare(left, right);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010464 }
Guido van Rossum09dc34f2007-05-04 04:17:33 +000010465 PyErr_Format(PyExc_TypeError,
10466 "Can't compare %.100s and %.100s",
10467 left->ob_type->tp_name,
10468 right->ob_type->tp_name);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010469 return -1;
10470}
10471
Martin v. Löwis5b222132007-06-10 09:51:05 +000010472int
10473PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str)
10474{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010475 Py_ssize_t i;
10476 int kind;
10477 void *data;
10478 Py_UCS4 chr;
10479
Victor Stinner910337b2011-10-03 03:20:16 +020010480 assert(_PyUnicode_CHECK(uni));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010481 if (PyUnicode_READY(uni) == -1)
10482 return -1;
10483 kind = PyUnicode_KIND(uni);
10484 data = PyUnicode_DATA(uni);
Martin v. Löwis5b222132007-06-10 09:51:05 +000010485 /* Compare Unicode string and source character set string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010486 for (i = 0; (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++)
10487 if (chr != str[i])
10488 return (chr < (unsigned char)(str[i])) ? -1 : 1;
Benjamin Peterson8667a9b2010-01-09 21:45:28 +000010489 /* This check keeps Python strings that end in '\0' from comparing equal
10490 to C strings identical up to that point. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010491 if (PyUnicode_GET_LENGTH(uni) != i || chr)
Benjamin Peterson29060642009-01-31 22:14:21 +000010492 return 1; /* uni is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010493 if (str[i])
Benjamin Peterson29060642009-01-31 22:14:21 +000010494 return -1; /* str is longer */
Martin v. Löwis5b222132007-06-10 09:51:05 +000010495 return 0;
10496}
10497
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010498
Benjamin Peterson29060642009-01-31 22:14:21 +000010499#define TEST_COND(cond) \
Benjamin Peterson14339b62009-01-31 16:36:08 +000010500 ((cond) ? Py_True : Py_False)
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010501
Alexander Belopolsky40018472011-02-26 01:02:56 +000010502PyObject *
10503PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010504{
10505 int result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000010506
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010507 if (PyUnicode_Check(left) && PyUnicode_Check(right)) {
10508 PyObject *v;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010509 if (PyUnicode_READY(left) == -1 ||
10510 PyUnicode_READY(right) == -1)
10511 return NULL;
10512 if (PyUnicode_GET_LENGTH(left) != PyUnicode_GET_LENGTH(right) ||
10513 PyUnicode_KIND(left) != PyUnicode_KIND(right)) {
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010514 if (op == Py_EQ) {
10515 Py_INCREF(Py_False);
10516 return Py_False;
10517 }
10518 if (op == Py_NE) {
10519 Py_INCREF(Py_True);
10520 return Py_True;
10521 }
10522 }
10523 if (left == right)
10524 result = 0;
10525 else
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010526 result = unicode_compare(left, right);
Benjamin Peterson14339b62009-01-31 16:36:08 +000010527
Antoine Pitrou51f3ef92008-12-20 13:14:23 +000010528 /* Convert the return value to a Boolean */
10529 switch (op) {
10530 case Py_EQ:
10531 v = TEST_COND(result == 0);
10532 break;
10533 case Py_NE:
10534 v = TEST_COND(result != 0);
10535 break;
10536 case Py_LE:
10537 v = TEST_COND(result <= 0);
10538 break;
10539 case Py_GE:
10540 v = TEST_COND(result >= 0);
10541 break;
10542 case Py_LT:
10543 v = TEST_COND(result == -1);
10544 break;
10545 case Py_GT:
10546 v = TEST_COND(result == 1);
10547 break;
10548 default:
10549 PyErr_BadArgument();
10550 return NULL;
10551 }
10552 Py_INCREF(v);
10553 return v;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010554 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010555
Brian Curtindfc80e32011-08-10 20:28:54 -050010556 Py_RETURN_NOTIMPLEMENTED;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000010557}
10558
Alexander Belopolsky40018472011-02-26 01:02:56 +000010559int
10560PyUnicode_Contains(PyObject *container, PyObject *element)
Guido van Rossum403d68b2000-03-13 15:55:09 +000010561{
Thomas Wouters477c8d52006-05-27 19:21:47 +000010562 PyObject *str, *sub;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010563 int kind1, kind2, kind;
10564 void *buf1, *buf2;
10565 Py_ssize_t len1, len2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010566 int result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010567
10568 /* Coerce the two arguments */
Thomas Wouters477c8d52006-05-27 19:21:47 +000010569 sub = PyUnicode_FromObject(element);
10570 if (!sub) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010571 PyErr_Format(PyExc_TypeError,
10572 "'in <string>' requires string as left operand, not %s",
10573 element->ob_type->tp_name);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010574 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010575 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010576 if (PyUnicode_READY(sub) == -1)
10577 return -1;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010578
Thomas Wouters477c8d52006-05-27 19:21:47 +000010579 str = PyUnicode_FromObject(container);
Victor Stinnere9a29352011-10-01 02:14:59 +020010580 if (!str || PyUnicode_READY(str) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000010581 Py_DECREF(sub);
10582 return -1;
10583 }
10584
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010585 kind1 = PyUnicode_KIND(str);
10586 kind2 = PyUnicode_KIND(sub);
10587 kind = kind1 > kind2 ? kind1 : kind2;
10588 buf1 = PyUnicode_DATA(str);
10589 buf2 = PyUnicode_DATA(sub);
10590 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010591 buf1 = _PyUnicode_AsKind(str, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010592 if (!buf1) {
10593 Py_DECREF(sub);
10594 return -1;
10595 }
10596 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010597 buf2 = _PyUnicode_AsKind(sub, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010598 if (!buf2) {
10599 Py_DECREF(sub);
10600 if (kind1 != kind) PyMem_Free(buf1);
10601 return -1;
10602 }
10603 len1 = PyUnicode_GET_LENGTH(str);
10604 len2 = PyUnicode_GET_LENGTH(sub);
10605
10606 switch(kind) {
10607 case PyUnicode_1BYTE_KIND:
10608 result = ucs1lib_find(buf1, len1, buf2, len2, 0) != -1;
10609 break;
10610 case PyUnicode_2BYTE_KIND:
10611 result = ucs2lib_find(buf1, len1, buf2, len2, 0) != -1;
10612 break;
10613 case PyUnicode_4BYTE_KIND:
10614 result = ucs4lib_find(buf1, len1, buf2, len2, 0) != -1;
10615 break;
10616 default:
10617 result = -1;
10618 assert(0);
10619 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000010620
10621 Py_DECREF(str);
10622 Py_DECREF(sub);
10623
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010624 if (kind1 != kind)
10625 PyMem_Free(buf1);
10626 if (kind2 != kind)
10627 PyMem_Free(buf2);
10628
Guido van Rossum403d68b2000-03-13 15:55:09 +000010629 return result;
Guido van Rossum403d68b2000-03-13 15:55:09 +000010630}
10631
Guido van Rossumd57fd912000-03-10 22:53:23 +000010632/* Concat to string or Unicode object giving a new Unicode object. */
10633
Alexander Belopolsky40018472011-02-26 01:02:56 +000010634PyObject *
10635PyUnicode_Concat(PyObject *left, PyObject *right)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010636{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010637 PyObject *u = NULL, *v = NULL, *w;
Victor Stinner127226b2011-10-13 01:12:34 +020010638 Py_UCS4 maxchar, maxchar2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010639
10640 /* Coerce the two arguments */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010641 u = PyUnicode_FromObject(left);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010642 if (u == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010643 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010644 v = PyUnicode_FromObject(right);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010645 if (v == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010646 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010647
10648 /* Shortcuts */
Victor Stinnera464fc12011-10-02 20:39:30 +020010649 if (v == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010650 Py_DECREF(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010651 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010652 }
Victor Stinnera464fc12011-10-02 20:39:30 +020010653 if (u == unicode_empty) {
Benjamin Peterson29060642009-01-31 22:14:21 +000010654 Py_DECREF(u);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010655 return v;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010656 }
10657
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010658 maxchar = PyUnicode_MAX_CHAR_VALUE(u);
Victor Stinner127226b2011-10-13 01:12:34 +020010659 maxchar2 = PyUnicode_MAX_CHAR_VALUE(v);
10660 maxchar = Py_MAX(maxchar, maxchar2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010661
Guido van Rossumd57fd912000-03-10 22:53:23 +000010662 /* Concat the two Unicode strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010663 w = PyUnicode_New(
10664 PyUnicode_GET_LENGTH(u) + PyUnicode_GET_LENGTH(v),
10665 maxchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010666 if (w == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000010667 goto onError;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010668 copy_characters(w, 0, u, 0, PyUnicode_GET_LENGTH(u));
10669 copy_characters(w, PyUnicode_GET_LENGTH(u), v, 0, PyUnicode_GET_LENGTH(v));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010670 Py_DECREF(u);
10671 Py_DECREF(v);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010672 assert(_PyUnicode_CheckConsistency(w, 1));
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010673 return w;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010674
Benjamin Peterson29060642009-01-31 22:14:21 +000010675 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000010676 Py_XDECREF(u);
10677 Py_XDECREF(v);
10678 return NULL;
10679}
10680
Victor Stinnerb0923652011-10-04 01:17:31 +020010681static void
10682unicode_append_inplace(PyObject **p_left, PyObject *right)
10683{
10684 Py_ssize_t left_len, right_len, new_len;
Victor Stinnerb0923652011-10-04 01:17:31 +020010685
10686 assert(PyUnicode_IS_READY(*p_left));
10687 assert(PyUnicode_IS_READY(right));
10688
10689 left_len = PyUnicode_GET_LENGTH(*p_left);
10690 right_len = PyUnicode_GET_LENGTH(right);
10691 if (left_len > PY_SSIZE_T_MAX - right_len) {
10692 PyErr_SetString(PyExc_OverflowError,
10693 "strings are too large to concat");
10694 goto error;
10695 }
10696 new_len = left_len + right_len;
10697
10698 /* Now we own the last reference to 'left', so we can resize it
10699 * in-place.
10700 */
10701 if (unicode_resize(p_left, new_len) != 0) {
10702 /* XXX if _PyUnicode_Resize() fails, 'left' has been
10703 * deallocated so it cannot be put back into
10704 * 'variable'. The MemoryError is raised when there
10705 * is no value in 'variable', which might (very
10706 * remotely) be a cause of incompatibilities.
10707 */
10708 goto error;
10709 }
10710 /* copy 'right' into the newly allocated area of 'left' */
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020010711 copy_characters(*p_left, left_len, right, 0, right_len);
10712 _PyUnicode_DIRTY(*p_left);
Victor Stinnerb0923652011-10-04 01:17:31 +020010713 return;
10714
10715error:
10716 Py_DECREF(*p_left);
10717 *p_left = NULL;
10718}
10719
Walter Dörwald1ab83302007-05-18 17:15:44 +000010720void
Victor Stinner23e56682011-10-03 03:54:37 +020010721PyUnicode_Append(PyObject **p_left, PyObject *right)
Walter Dörwald1ab83302007-05-18 17:15:44 +000010722{
Victor Stinner23e56682011-10-03 03:54:37 +020010723 PyObject *left, *res;
10724
10725 if (p_left == NULL) {
10726 if (!PyErr_Occurred())
10727 PyErr_BadInternalCall();
Benjamin Peterson14339b62009-01-31 16:36:08 +000010728 return;
10729 }
Victor Stinner23e56682011-10-03 03:54:37 +020010730 left = *p_left;
10731 if (right == NULL || !PyUnicode_Check(left)) {
10732 if (!PyErr_Occurred())
10733 PyErr_BadInternalCall();
10734 goto error;
10735 }
10736
Victor Stinnere1335c72011-10-04 20:53:03 +020010737 if (PyUnicode_READY(left))
10738 goto error;
10739 if (PyUnicode_READY(right))
10740 goto error;
10741
Victor Stinner23e56682011-10-03 03:54:37 +020010742 if (PyUnicode_CheckExact(left) && left != unicode_empty
10743 && PyUnicode_CheckExact(right) && right != unicode_empty
10744 && unicode_resizable(left)
10745 && (_PyUnicode_KIND(right) <= _PyUnicode_KIND(left)
10746 || _PyUnicode_WSTR(left) != NULL))
10747 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010748 /* Don't resize for ascii += latin1. Convert ascii to latin1 requires
10749 to change the structure size, but characters are stored just after
Georg Brandl7597add2011-10-05 16:36:47 +020010750 the structure, and so it requires to move all characters which is
Victor Stinnerb0923652011-10-04 01:17:31 +020010751 not so different than duplicating the string. */
10752 if (!(PyUnicode_IS_ASCII(left) && !PyUnicode_IS_ASCII(right)))
Victor Stinner23e56682011-10-03 03:54:37 +020010753 {
Victor Stinnerb0923652011-10-04 01:17:31 +020010754 unicode_append_inplace(p_left, right);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010755 if (p_left != NULL)
10756 assert(_PyUnicode_CheckConsistency(*p_left, 1));
Victor Stinner23e56682011-10-03 03:54:37 +020010757 return;
10758 }
10759 }
10760
10761 res = PyUnicode_Concat(left, right);
10762 if (res == NULL)
10763 goto error;
10764 Py_DECREF(left);
10765 *p_left = res;
10766 return;
10767
10768error:
10769 Py_DECREF(*p_left);
10770 *p_left = NULL;
Walter Dörwald1ab83302007-05-18 17:15:44 +000010771}
10772
10773void
10774PyUnicode_AppendAndDel(PyObject **pleft, PyObject *right)
10775{
Benjamin Peterson14339b62009-01-31 16:36:08 +000010776 PyUnicode_Append(pleft, right);
10777 Py_XDECREF(right);
Walter Dörwald1ab83302007-05-18 17:15:44 +000010778}
10779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010780PyDoc_STRVAR(count__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010781 "S.count(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010782\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000010783Return the number of non-overlapping occurrences of substring sub in\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000010784string S[start:end]. Optional arguments start and end are\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010785interpreted as in slice notation.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010786
10787static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010788unicode_count(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010789{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010790 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000010791 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000010792 Py_ssize_t end = PY_SSIZE_T_MAX;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010793 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010794 int kind1, kind2, kind;
10795 void *buf1, *buf2;
10796 Py_ssize_t len1, len2, iresult;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010797
Jesus Ceaac451502011-04-20 17:09:23 +020010798 if (!stringlib_parse_args_finds_unicode("count", args, &substring,
10799 &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000010800 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000010801
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010802 kind1 = PyUnicode_KIND(self);
10803 kind2 = PyUnicode_KIND(substring);
10804 kind = kind1 > kind2 ? kind1 : kind2;
10805 buf1 = PyUnicode_DATA(self);
10806 buf2 = PyUnicode_DATA(substring);
10807 if (kind1 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010808 buf1 = _PyUnicode_AsKind(self, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010809 if (!buf1) {
10810 Py_DECREF(substring);
10811 return NULL;
10812 }
10813 if (kind2 != kind)
Victor Stinner7931d9a2011-11-04 00:22:48 +010010814 buf2 = _PyUnicode_AsKind(substring, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010815 if (!buf2) {
10816 Py_DECREF(substring);
10817 if (kind1 != kind) PyMem_Free(buf1);
10818 return NULL;
10819 }
10820 len1 = PyUnicode_GET_LENGTH(self);
10821 len2 = PyUnicode_GET_LENGTH(substring);
10822
10823 ADJUST_INDICES(start, end, len1);
10824 switch(kind) {
10825 case PyUnicode_1BYTE_KIND:
10826 iresult = ucs1lib_count(
10827 ((Py_UCS1*)buf1) + start, end - start,
10828 buf2, len2, PY_SSIZE_T_MAX
10829 );
10830 break;
10831 case PyUnicode_2BYTE_KIND:
10832 iresult = ucs2lib_count(
10833 ((Py_UCS2*)buf1) + start, end - start,
10834 buf2, len2, PY_SSIZE_T_MAX
10835 );
10836 break;
10837 case PyUnicode_4BYTE_KIND:
10838 iresult = ucs4lib_count(
10839 ((Py_UCS4*)buf1) + start, end - start,
10840 buf2, len2, PY_SSIZE_T_MAX
10841 );
10842 break;
10843 default:
10844 assert(0); iresult = 0;
10845 }
10846
10847 result = PyLong_FromSsize_t(iresult);
10848
10849 if (kind1 != kind)
10850 PyMem_Free(buf1);
10851 if (kind2 != kind)
10852 PyMem_Free(buf2);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010853
10854 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000010855
Guido van Rossumd57fd912000-03-10 22:53:23 +000010856 return result;
10857}
10858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010859PyDoc_STRVAR(encode__doc__,
Victor Stinnerc911bbf2010-11-07 19:04:46 +000010860 "S.encode(encoding='utf-8', errors='strict') -> bytes\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010861\n\
Victor Stinnere14e2122010-11-07 18:41:46 +000010862Encode S using the codec registered for encoding. Default encoding\n\
10863is 'utf-8'. errors may be given to set a different error\n\
Fred Drakee4315f52000-05-09 19:53:39 +000010864handling scheme. Default is 'strict' meaning that encoding errors raise\n\
Walter Dörwald3aeb6322002-09-02 13:14:32 +000010865a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n\
10866'xmlcharrefreplace' as well as any other name registered with\n\
10867codecs.register_error that can handle UnicodeEncodeErrors.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010868
10869static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010870unicode_encode(PyObject *self, PyObject *args, PyObject *kwargs)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010871{
Benjamin Peterson308d6372009-09-18 21:42:35 +000010872 static char *kwlist[] = {"encoding", "errors", 0};
Guido van Rossumd57fd912000-03-10 22:53:23 +000010873 char *encoding = NULL;
10874 char *errors = NULL;
Guido van Rossum35d94282007-08-27 18:20:11 +000010875
Benjamin Peterson308d6372009-09-18 21:42:35 +000010876 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
10877 kwlist, &encoding, &errors))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010878 return NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010879 return PyUnicode_AsEncodedString(self, encoding, errors);
Marc-André Lemburgd2d45982004-07-08 17:57:32 +000010880}
10881
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010882PyDoc_STRVAR(expandtabs__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010883 "S.expandtabs([tabsize]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010884\n\
10885Return a copy of S where all tab characters are expanded using spaces.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010886If tabsize is not given, a tab size of 8 characters is assumed.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010887
10888static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010889unicode_expandtabs(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010890{
Antoine Pitroue71d5742011-10-04 15:55:09 +020010891 Py_ssize_t i, j, line_pos, src_len, incr;
10892 Py_UCS4 ch;
10893 PyObject *u;
10894 void *src_data, *dest_data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010895 int tabsize = 8;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010896 int kind;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010897 int found;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010898
10899 if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
Benjamin Peterson29060642009-01-31 22:14:21 +000010900 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010901
Antoine Pitrou22425222011-10-04 19:10:51 +020010902 if (PyUnicode_READY(self) == -1)
10903 return NULL;
10904
Thomas Wouters7e474022000-07-16 12:04:32 +000010905 /* First pass: determine size of output string */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010906 src_len = PyUnicode_GET_LENGTH(self);
10907 i = j = line_pos = 0;
10908 kind = PyUnicode_KIND(self);
10909 src_data = PyUnicode_DATA(self);
Antoine Pitroue19aa382011-10-04 16:04:01 +020010910 found = 0;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010911 for (; i < src_len; i++) {
10912 ch = PyUnicode_READ(kind, src_data, i);
10913 if (ch == '\t') {
Antoine Pitroue19aa382011-10-04 16:04:01 +020010914 found = 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000010915 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010916 incr = tabsize - (line_pos % tabsize); /* cannot overflow */
Benjamin Peterson29060642009-01-31 22:14:21 +000010917 if (j > PY_SSIZE_T_MAX - incr)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010918 goto overflow;
10919 line_pos += incr;
Benjamin Peterson29060642009-01-31 22:14:21 +000010920 j += incr;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010921 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010922 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000010923 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000010924 if (j > PY_SSIZE_T_MAX - 1)
Antoine Pitroue71d5742011-10-04 15:55:09 +020010925 goto overflow;
10926 line_pos++;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010927 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010928 if (ch == '\n' || ch == '\r')
10929 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010930 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010931 }
Antoine Pitroue19aa382011-10-04 16:04:01 +020010932 if (!found && PyUnicode_CheckExact(self)) {
Victor Stinner7931d9a2011-11-04 00:22:48 +010010933 Py_INCREF(self);
10934 return self;
Antoine Pitroue19aa382011-10-04 16:04:01 +020010935 }
Guido van Rossumcd16bf62007-06-13 18:07:49 +000010936
Guido van Rossumd57fd912000-03-10 22:53:23 +000010937 /* Second pass: create output string and fill it */
Antoine Pitroue71d5742011-10-04 15:55:09 +020010938 u = PyUnicode_New(j, PyUnicode_MAX_CHAR_VALUE(self));
Guido van Rossumd57fd912000-03-10 22:53:23 +000010939 if (!u)
10940 return NULL;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010941 dest_data = PyUnicode_DATA(u);
Guido van Rossumd57fd912000-03-10 22:53:23 +000010942
Antoine Pitroue71d5742011-10-04 15:55:09 +020010943 i = j = line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010944
Antoine Pitroue71d5742011-10-04 15:55:09 +020010945 for (; i < src_len; i++) {
10946 ch = PyUnicode_READ(kind, src_data, i);
10947 if (ch == '\t') {
Benjamin Peterson29060642009-01-31 22:14:21 +000010948 if (tabsize > 0) {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010949 incr = tabsize - (line_pos % tabsize);
10950 line_pos += incr;
10951 while (incr--) {
10952 PyUnicode_WRITE(kind, dest_data, j, ' ');
10953 j++;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010954 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010955 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000010956 }
Benjamin Peterson29060642009-01-31 22:14:21 +000010957 else {
Antoine Pitroue71d5742011-10-04 15:55:09 +020010958 line_pos++;
10959 PyUnicode_WRITE(kind, dest_data, j, ch);
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010960 j++;
Antoine Pitroue71d5742011-10-04 15:55:09 +020010961 if (ch == '\n' || ch == '\r')
10962 line_pos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010963 }
Antoine Pitroue71d5742011-10-04 15:55:09 +020010964 }
10965 assert (j == PyUnicode_GET_LENGTH(u));
Victor Stinner17efeed2011-10-04 20:05:46 +020010966#ifndef DONT_MAKE_RESULT_READY
10967 if (_PyUnicode_READY_REPLACE(&u)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010968 Py_DECREF(u);
10969 return NULL;
10970 }
Victor Stinner17efeed2011-10-04 20:05:46 +020010971#endif
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020010972 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010010973 return u;
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010974
Antoine Pitroue71d5742011-10-04 15:55:09 +020010975 overflow:
Christian Heimesdd15f6c2008-03-16 00:07:10 +000010976 PyErr_SetString(PyExc_OverflowError, "new string is too long");
10977 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010978}
10979
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010980PyDoc_STRVAR(find__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000010981 "S.find(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010982\n\
10983Return the lowest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080010984such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000010985arguments start and end are interpreted as in slice notation.\n\
10986\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000010987Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000010988
10989static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020010990unicode_find(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000010991{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020010992 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000010993 Py_ssize_t start;
10994 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000010995 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000010996
Jesus Ceaac451502011-04-20 17:09:23 +020010997 if (!stringlib_parse_args_finds_unicode("find", args, &substring,
10998 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000010999 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011000
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011001 if (PyUnicode_READY(self) == -1)
11002 return NULL;
11003 if (PyUnicode_READY(substring) == -1)
11004 return NULL;
11005
Victor Stinner7931d9a2011-11-04 00:22:48 +010011006 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011007
11008 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011009
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011010 if (result == -2)
11011 return NULL;
11012
Christian Heimes217cfd12007-12-02 14:31:20 +000011013 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011014}
11015
11016static PyObject *
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011017unicode_getitem(PyObject *self, Py_ssize_t index)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011018{
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011019 Py_UCS4 ch = PyUnicode_ReadChar(self, index);
11020 if (ch == (Py_UCS4)-1)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011021 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011022 return PyUnicode_FromOrdinal(ch);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011023}
11024
Guido van Rossumc2504932007-09-18 19:42:40 +000011025/* Believe it or not, this produces the same value for ASCII strings
Mark Dickinson57e683e2011-09-24 18:18:40 +010011026 as bytes_hash(). */
Benjamin Peterson8f67d082010-10-17 20:54:53 +000011027static Py_hash_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011028unicode_hash(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011029{
Guido van Rossumc2504932007-09-18 19:42:40 +000011030 Py_ssize_t len;
Mark Dickinson57e683e2011-09-24 18:18:40 +010011031 Py_uhash_t x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011032
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011033 if (_PyUnicode_HASH(self) != -1)
11034 return _PyUnicode_HASH(self);
11035 if (PyUnicode_READY(self) == -1)
11036 return -1;
11037 len = PyUnicode_GET_LENGTH(self);
11038
11039 /* The hash function as a macro, gets expanded three times below. */
11040#define HASH(P) \
11041 x = (Py_uhash_t)*P << 7; \
11042 while (--len >= 0) \
11043 x = (1000003*x) ^ (Py_uhash_t)*P++;
11044
11045 switch (PyUnicode_KIND(self)) {
11046 case PyUnicode_1BYTE_KIND: {
11047 const unsigned char *c = PyUnicode_1BYTE_DATA(self);
11048 HASH(c);
11049 break;
11050 }
11051 case PyUnicode_2BYTE_KIND: {
11052 const Py_UCS2 *s = PyUnicode_2BYTE_DATA(self);
11053 HASH(s);
11054 break;
11055 }
11056 default: {
11057 Py_UCS4 *l;
11058 assert(PyUnicode_KIND(self) == PyUnicode_4BYTE_KIND &&
11059 "Impossible switch case in unicode_hash");
11060 l = PyUnicode_4BYTE_DATA(self);
11061 HASH(l);
11062 break;
11063 }
11064 }
11065 x ^= (Py_uhash_t)PyUnicode_GET_LENGTH(self);
11066
Guido van Rossumc2504932007-09-18 19:42:40 +000011067 if (x == -1)
11068 x = -2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011069 _PyUnicode_HASH(self) = x;
Guido van Rossumc2504932007-09-18 19:42:40 +000011070 return x;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011071}
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011072#undef HASH
Guido van Rossumd57fd912000-03-10 22:53:23 +000011073
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011074PyDoc_STRVAR(index__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011075 "S.index(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011076\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011077Like S.find() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011078
11079static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011080unicode_index(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011081{
Martin v. Löwis18e16552006-02-15 17:27:45 +000011082 Py_ssize_t result;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011083 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000011084 Py_ssize_t start;
11085 Py_ssize_t end;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011086
Jesus Ceaac451502011-04-20 17:09:23 +020011087 if (!stringlib_parse_args_finds_unicode("index", args, &substring,
11088 &start, &end))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011089 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011090
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011091 if (PyUnicode_READY(self) == -1)
11092 return NULL;
11093 if (PyUnicode_READY(substring) == -1)
11094 return NULL;
11095
Victor Stinner7931d9a2011-11-04 00:22:48 +010011096 result = any_find_slice(1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011097
11098 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011100 if (result == -2)
11101 return NULL;
11102
Guido van Rossumd57fd912000-03-10 22:53:23 +000011103 if (result < 0) {
11104 PyErr_SetString(PyExc_ValueError, "substring not found");
11105 return NULL;
11106 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000011107
Christian Heimes217cfd12007-12-02 14:31:20 +000011108 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011109}
11110
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011111PyDoc_STRVAR(islower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011112 "S.islower() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011113\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011114Return True if all cased characters in S are lowercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011115at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011116
11117static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011118unicode_islower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011119{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011120 Py_ssize_t i, length;
11121 int kind;
11122 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011123 int cased;
11124
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011125 if (PyUnicode_READY(self) == -1)
11126 return NULL;
11127 length = PyUnicode_GET_LENGTH(self);
11128 kind = PyUnicode_KIND(self);
11129 data = PyUnicode_DATA(self);
11130
Guido van Rossumd57fd912000-03-10 22:53:23 +000011131 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011132 if (length == 1)
11133 return PyBool_FromLong(
11134 Py_UNICODE_ISLOWER(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011135
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011136 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011137 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011138 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011139
Guido van Rossumd57fd912000-03-10 22:53:23 +000011140 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011141 for (i = 0; i < length; i++) {
11142 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011143
Benjamin Peterson29060642009-01-31 22:14:21 +000011144 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch))
11145 return PyBool_FromLong(0);
11146 else if (!cased && Py_UNICODE_ISLOWER(ch))
11147 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011148 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011149 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011150}
11151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011152PyDoc_STRVAR(isupper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011153 "S.isupper() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011154\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011155Return True if all cased characters in S are uppercase and there is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011156at least one cased character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011157
11158static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011159unicode_isupper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011160{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011161 Py_ssize_t i, length;
11162 int kind;
11163 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011164 int cased;
11165
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011166 if (PyUnicode_READY(self) == -1)
11167 return NULL;
11168 length = PyUnicode_GET_LENGTH(self);
11169 kind = PyUnicode_KIND(self);
11170 data = PyUnicode_DATA(self);
11171
Guido van Rossumd57fd912000-03-10 22:53:23 +000011172 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011173 if (length == 1)
11174 return PyBool_FromLong(
11175 Py_UNICODE_ISUPPER(PyUnicode_READ(kind, data, 0)) != 0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011176
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011177 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011178 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011179 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011180
Guido van Rossumd57fd912000-03-10 22:53:23 +000011181 cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011182 for (i = 0; i < length; i++) {
11183 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011184
Benjamin Peterson29060642009-01-31 22:14:21 +000011185 if (Py_UNICODE_ISLOWER(ch) || Py_UNICODE_ISTITLE(ch))
11186 return PyBool_FromLong(0);
11187 else if (!cased && Py_UNICODE_ISUPPER(ch))
11188 cased = 1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011189 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011190 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011191}
11192
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011193PyDoc_STRVAR(istitle__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011194 "S.istitle() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011195\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011196Return True if S is a titlecased string and there is at least one\n\
11197character in S, i.e. upper- and titlecase characters may only\n\
11198follow uncased characters and lowercase characters only cased ones.\n\
11199Return False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011200
11201static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011202unicode_istitle(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011203{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011204 Py_ssize_t i, length;
11205 int kind;
11206 void *data;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011207 int cased, previous_is_cased;
11208
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011209 if (PyUnicode_READY(self) == -1)
11210 return NULL;
11211 length = PyUnicode_GET_LENGTH(self);
11212 kind = PyUnicode_KIND(self);
11213 data = PyUnicode_DATA(self);
11214
Guido van Rossumd57fd912000-03-10 22:53:23 +000011215 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011216 if (length == 1) {
11217 Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11218 return PyBool_FromLong((Py_UNICODE_ISTITLE(ch) != 0) ||
11219 (Py_UNICODE_ISUPPER(ch) != 0));
11220 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011221
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011222 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011223 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011224 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011225
Guido van Rossumd57fd912000-03-10 22:53:23 +000011226 cased = 0;
11227 previous_is_cased = 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011228 for (i = 0; i < length; i++) {
11229 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Tim Petersced69f82003-09-16 20:30:58 +000011230
Benjamin Peterson29060642009-01-31 22:14:21 +000011231 if (Py_UNICODE_ISUPPER(ch) || Py_UNICODE_ISTITLE(ch)) {
11232 if (previous_is_cased)
11233 return PyBool_FromLong(0);
11234 previous_is_cased = 1;
11235 cased = 1;
11236 }
11237 else if (Py_UNICODE_ISLOWER(ch)) {
11238 if (!previous_is_cased)
11239 return PyBool_FromLong(0);
11240 previous_is_cased = 1;
11241 cased = 1;
11242 }
11243 else
11244 previous_is_cased = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011245 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011246 return PyBool_FromLong(cased);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011247}
11248
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011249PyDoc_STRVAR(isspace__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011250 "S.isspace() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011251\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011252Return True if all characters in S are whitespace\n\
11253and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011254
11255static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011256unicode_isspace(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011257{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011258 Py_ssize_t i, length;
11259 int kind;
11260 void *data;
11261
11262 if (PyUnicode_READY(self) == -1)
11263 return NULL;
11264 length = PyUnicode_GET_LENGTH(self);
11265 kind = PyUnicode_KIND(self);
11266 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011267
Guido van Rossumd57fd912000-03-10 22:53:23 +000011268 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011269 if (length == 1)
11270 return PyBool_FromLong(
11271 Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011272
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011273 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011274 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011275 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011276
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011277 for (i = 0; i < length; i++) {
11278 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011279 if (!Py_UNICODE_ISSPACE(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011280 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011281 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011282 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011283}
11284
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011285PyDoc_STRVAR(isalpha__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011286 "S.isalpha() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011287\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011288Return True if all characters in S are alphabetic\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011289and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011290
11291static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011292unicode_isalpha(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011293{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011294 Py_ssize_t i, length;
11295 int kind;
11296 void *data;
11297
11298 if (PyUnicode_READY(self) == -1)
11299 return NULL;
11300 length = PyUnicode_GET_LENGTH(self);
11301 kind = PyUnicode_KIND(self);
11302 data = PyUnicode_DATA(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011303
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011304 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011305 if (length == 1)
11306 return PyBool_FromLong(
11307 Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, 0)));
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011308
11309 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011310 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011311 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011312
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011313 for (i = 0; i < length; i++) {
11314 if (!Py_UNICODE_ISALPHA(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011315 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011316 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011317 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011318}
11319
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011320PyDoc_STRVAR(isalnum__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011321 "S.isalnum() -> bool\n\
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011322\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011323Return True if all characters in S are alphanumeric\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011324and there is at least one character in S, False otherwise.");
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011325
11326static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011327unicode_isalnum(PyObject *self)
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011328{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011329 int kind;
11330 void *data;
11331 Py_ssize_t len, i;
11332
11333 if (PyUnicode_READY(self) == -1)
11334 return NULL;
11335
11336 kind = PyUnicode_KIND(self);
11337 data = PyUnicode_DATA(self);
11338 len = PyUnicode_GET_LENGTH(self);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011339
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011340 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011341 if (len == 1) {
11342 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11343 return PyBool_FromLong(Py_UNICODE_ISALNUM(ch));
11344 }
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011345
11346 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011347 if (len == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011348 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011349
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011350 for (i = 0; i < len; i++) {
11351 const Py_UCS4 ch = PyUnicode_READ(kind, data, i);
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011352 if (!Py_UNICODE_ISALNUM(ch))
Benjamin Peterson29060642009-01-31 22:14:21 +000011353 return PyBool_FromLong(0);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011354 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011355 return PyBool_FromLong(1);
Marc-André Lemburga7acf422000-07-05 09:49:44 +000011356}
11357
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011358PyDoc_STRVAR(isdecimal__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011359 "S.isdecimal() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011360\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011361Return True if there are only decimal characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011362False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011363
11364static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011365unicode_isdecimal(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011366{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011367 Py_ssize_t i, length;
11368 int kind;
11369 void *data;
11370
11371 if (PyUnicode_READY(self) == -1)
11372 return NULL;
11373 length = PyUnicode_GET_LENGTH(self);
11374 kind = PyUnicode_KIND(self);
11375 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011376
Guido van Rossumd57fd912000-03-10 22:53:23 +000011377 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011378 if (length == 1)
11379 return PyBool_FromLong(
11380 Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011381
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011382 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011383 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011384 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011385
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011386 for (i = 0; i < length; i++) {
11387 if (!Py_UNICODE_ISDECIMAL(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011388 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011389 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011390 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011391}
11392
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011393PyDoc_STRVAR(isdigit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011394 "S.isdigit() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011395\n\
Martin v. Löwis6828e182003-10-18 09:55:08 +000011396Return True if all characters in S are digits\n\
11397and there is at least one character in S, False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011398
11399static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011400unicode_isdigit(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011401{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011402 Py_ssize_t i, length;
11403 int kind;
11404 void *data;
11405
11406 if (PyUnicode_READY(self) == -1)
11407 return NULL;
11408 length = PyUnicode_GET_LENGTH(self);
11409 kind = PyUnicode_KIND(self);
11410 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011411
Guido van Rossumd57fd912000-03-10 22:53:23 +000011412 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011413 if (length == 1) {
11414 const Py_UCS4 ch = PyUnicode_READ(kind, data, 0);
11415 return PyBool_FromLong(Py_UNICODE_ISDIGIT(ch));
11416 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011417
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011418 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011419 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011420 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011421
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011422 for (i = 0; i < length; i++) {
11423 if (!Py_UNICODE_ISDIGIT(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011424 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011425 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011426 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011427}
11428
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011429PyDoc_STRVAR(isnumeric__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011430 "S.isnumeric() -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011431\n\
Guido van Rossum77f6a652002-04-03 22:41:51 +000011432Return True if there are only numeric characters in S,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011433False otherwise.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011434
11435static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011436unicode_isnumeric(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011437{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011438 Py_ssize_t i, length;
11439 int kind;
11440 void *data;
11441
11442 if (PyUnicode_READY(self) == -1)
11443 return NULL;
11444 length = PyUnicode_GET_LENGTH(self);
11445 kind = PyUnicode_KIND(self);
11446 data = PyUnicode_DATA(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011447
Guido van Rossumd57fd912000-03-10 22:53:23 +000011448 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011449 if (length == 1)
11450 return PyBool_FromLong(
11451 Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, 0)));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011452
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011453 /* Special case for empty strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011454 if (length == 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000011455 return PyBool_FromLong(0);
Marc-André Lemburg60bc8092000-06-14 09:18:32 +000011456
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011457 for (i = 0; i < length; i++) {
11458 if (!Py_UNICODE_ISNUMERIC(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011459 return PyBool_FromLong(0);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011460 }
Guido van Rossum77f6a652002-04-03 22:41:51 +000011461 return PyBool_FromLong(1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011462}
11463
Martin v. Löwis47383402007-08-15 07:32:56 +000011464int
11465PyUnicode_IsIdentifier(PyObject *self)
11466{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011467 int kind;
11468 void *data;
11469 Py_ssize_t i;
Ezio Melotti93e7afc2011-08-22 14:08:38 +030011470 Py_UCS4 first;
Martin v. Löwis47383402007-08-15 07:32:56 +000011471
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011472 if (PyUnicode_READY(self) == -1) {
11473 Py_FatalError("identifier not ready");
Benjamin Peterson29060642009-01-31 22:14:21 +000011474 return 0;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011475 }
11476
11477 /* Special case for empty strings */
11478 if (PyUnicode_GET_LENGTH(self) == 0)
11479 return 0;
11480 kind = PyUnicode_KIND(self);
11481 data = PyUnicode_DATA(self);
Martin v. Löwis47383402007-08-15 07:32:56 +000011482
11483 /* PEP 3131 says that the first character must be in
11484 XID_Start and subsequent characters in XID_Continue,
11485 and for the ASCII range, the 2.x rules apply (i.e
Benjamin Peterson14339b62009-01-31 16:36:08 +000011486 start with letters and underscore, continue with
Martin v. Löwis47383402007-08-15 07:32:56 +000011487 letters, digits, underscore). However, given the current
11488 definition of XID_Start and XID_Continue, it is sufficient
11489 to check just for these, except that _ must be allowed
11490 as starting an identifier. */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011491 first = PyUnicode_READ(kind, data, 0);
Benjamin Petersonf413b802011-08-12 22:17:18 -050011492 if (!_PyUnicode_IsXidStart(first) && first != 0x5F /* LOW LINE */)
Martin v. Löwis47383402007-08-15 07:32:56 +000011493 return 0;
11494
Benjamin Peterson9c6e6a02011-09-28 08:09:05 -040011495 for (i = 1; i < PyUnicode_GET_LENGTH(self); i++)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011496 if (!_PyUnicode_IsXidContinue(PyUnicode_READ(kind, data, i)))
Benjamin Peterson29060642009-01-31 22:14:21 +000011497 return 0;
Martin v. Löwis47383402007-08-15 07:32:56 +000011498 return 1;
11499}
11500
11501PyDoc_STRVAR(isidentifier__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011502 "S.isidentifier() -> bool\n\
Martin v. Löwis47383402007-08-15 07:32:56 +000011503\n\
11504Return True if S is a valid identifier according\n\
11505to the language definition.");
11506
11507static PyObject*
11508unicode_isidentifier(PyObject *self)
11509{
11510 return PyBool_FromLong(PyUnicode_IsIdentifier(self));
11511}
11512
Georg Brandl559e5d72008-06-11 18:37:52 +000011513PyDoc_STRVAR(isprintable__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011514 "S.isprintable() -> bool\n\
Georg Brandl559e5d72008-06-11 18:37:52 +000011515\n\
11516Return True if all characters in S are considered\n\
11517printable in repr() or S is empty, False otherwise.");
11518
11519static PyObject*
11520unicode_isprintable(PyObject *self)
11521{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011522 Py_ssize_t i, length;
11523 int kind;
11524 void *data;
11525
11526 if (PyUnicode_READY(self) == -1)
11527 return NULL;
11528 length = PyUnicode_GET_LENGTH(self);
11529 kind = PyUnicode_KIND(self);
11530 data = PyUnicode_DATA(self);
Georg Brandl559e5d72008-06-11 18:37:52 +000011531
11532 /* Shortcut for single character strings */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011533 if (length == 1)
11534 return PyBool_FromLong(
11535 Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, 0)));
Georg Brandl559e5d72008-06-11 18:37:52 +000011536
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011537 for (i = 0; i < length; i++) {
11538 if (!Py_UNICODE_ISPRINTABLE(PyUnicode_READ(kind, data, i))) {
Georg Brandl559e5d72008-06-11 18:37:52 +000011539 Py_RETURN_FALSE;
11540 }
11541 }
11542 Py_RETURN_TRUE;
11543}
11544
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011545PyDoc_STRVAR(join__doc__,
Georg Brandl495f7b52009-10-27 15:28:25 +000011546 "S.join(iterable) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011547\n\
11548Return a string which is the concatenation of the strings in the\n\
Georg Brandl495f7b52009-10-27 15:28:25 +000011549iterable. The separator between elements is S.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011550
11551static PyObject*
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011552unicode_join(PyObject *self, PyObject *data)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011553{
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000011554 return PyUnicode_Join(self, data);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011555}
11556
Martin v. Löwis18e16552006-02-15 17:27:45 +000011557static Py_ssize_t
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011558unicode_length(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011559{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011560 if (PyUnicode_READY(self) == -1)
11561 return -1;
11562 return PyUnicode_GET_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011563}
11564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011565PyDoc_STRVAR(ljust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011566 "S.ljust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011567\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000011568Return S left-justified in a Unicode string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011569done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011570
11571static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020011572unicode_ljust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011573{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011574 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011575 Py_UCS4 fillchar = ' ';
11576
11577 if (PyUnicode_READY(self) == -1)
11578 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000011579
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000011580 if (!PyArg_ParseTuple(args, "n|O&:ljust", &width, convert_uc, &fillchar))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011581 return NULL;
11582
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011583 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011584 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011585 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011586 }
11587
Victor Stinner7931d9a2011-11-04 00:22:48 +010011588 return pad(self, 0, width - _PyUnicode_LENGTH(self), fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011589}
11590
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011591PyDoc_STRVAR(lower__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011592 "S.lower() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011593\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011594Return a copy of the string S converted to lowercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011595
11596static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020011597unicode_lower(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011598{
Guido van Rossumd57fd912000-03-10 22:53:23 +000011599 return fixup(self, fixlower);
11600}
11601
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011602#define LEFTSTRIP 0
11603#define RIGHTSTRIP 1
11604#define BOTHSTRIP 2
11605
11606/* Arrays indexed by above */
11607static const char *stripformat[] = {"|O:lstrip", "|O:rstrip", "|O:strip"};
11608
11609#define STRIPNAME(i) (stripformat[i]+3)
11610
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011611/* externally visible for str.strip(unicode) */
11612PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011613_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011614{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011615 void *data;
11616 int kind;
11617 Py_ssize_t i, j, len;
11618 BLOOM_MASK sepmask;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011619
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011620 if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
11621 return NULL;
11622
11623 kind = PyUnicode_KIND(self);
11624 data = PyUnicode_DATA(self);
11625 len = PyUnicode_GET_LENGTH(self);
11626 sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
11627 PyUnicode_DATA(sepobj),
11628 PyUnicode_GET_LENGTH(sepobj));
Thomas Wouters477c8d52006-05-27 19:21:47 +000011629
Benjamin Peterson14339b62009-01-31 16:36:08 +000011630 i = 0;
11631 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011632 while (i < len &&
11633 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, i), sepobj)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011634 i++;
11635 }
Benjamin Peterson14339b62009-01-31 16:36:08 +000011636 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011637
Benjamin Peterson14339b62009-01-31 16:36:08 +000011638 j = len;
11639 if (striptype != LEFTSTRIP) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011640 do {
11641 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011642 } while (j >= i &&
11643 BLOOM_MEMBER(sepmask, PyUnicode_READ(kind, data, j), sepobj));
Benjamin Peterson29060642009-01-31 22:14:21 +000011644 j++;
Benjamin Peterson14339b62009-01-31 16:36:08 +000011645 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011646
Victor Stinner7931d9a2011-11-04 00:22:48 +010011647 return PyUnicode_Substring(self, i, j);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011648}
11649
11650PyObject*
11651PyUnicode_Substring(PyObject *self, Py_ssize_t start, Py_ssize_t end)
11652{
11653 unsigned char *data;
11654 int kind;
Victor Stinner12bab6d2011-10-01 01:53:49 +020011655 Py_ssize_t length;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011656
Victor Stinnerde636f32011-10-01 03:55:54 +020011657 if (PyUnicode_READY(self) == -1)
11658 return NULL;
11659
11660 end = Py_MIN(end, PyUnicode_GET_LENGTH(self));
11661
Victor Stinner12bab6d2011-10-01 01:53:49 +020011662 if (start == 0 && end == PyUnicode_GET_LENGTH(self))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011663 {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011664 if (PyUnicode_CheckExact(self)) {
11665 Py_INCREF(self);
11666 return self;
11667 }
11668 else
11669 return PyUnicode_Copy(self);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011670 }
11671
Victor Stinner12bab6d2011-10-01 01:53:49 +020011672 length = end - start;
11673 if (length == 1)
Victor Stinner2fe5ced2011-10-02 00:25:40 +020011674 return unicode_getitem(self, start);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011675
Victor Stinnerde636f32011-10-01 03:55:54 +020011676 if (start < 0 || end < 0) {
Victor Stinner12bab6d2011-10-01 01:53:49 +020011677 PyErr_SetString(PyExc_IndexError, "string index out of range");
11678 return NULL;
11679 }
11680
Victor Stinnerb9275c12011-10-05 14:01:42 +020011681 if (PyUnicode_IS_ASCII(self)) {
11682 kind = PyUnicode_KIND(self);
11683 data = PyUnicode_1BYTE_DATA(self);
11684 return unicode_fromascii(data + start, length);
11685 }
11686 else {
11687 kind = PyUnicode_KIND(self);
11688 data = PyUnicode_1BYTE_DATA(self);
11689 return PyUnicode_FromKindAndData(kind,
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011690 data + kind * start,
Victor Stinnerb9275c12011-10-05 14:01:42 +020011691 length);
11692 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011693}
Guido van Rossumd57fd912000-03-10 22:53:23 +000011694
11695static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011696do_strip(PyObject *self, int striptype)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011697{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011698 int kind;
11699 void *data;
11700 Py_ssize_t len, i, j;
11701
11702 if (PyUnicode_READY(self) == -1)
11703 return NULL;
11704
11705 kind = PyUnicode_KIND(self);
11706 data = PyUnicode_DATA(self);
11707 len = PyUnicode_GET_LENGTH(self);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011708
Benjamin Peterson14339b62009-01-31 16:36:08 +000011709 i = 0;
11710 if (striptype != RIGHTSTRIP) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011711 while (i < len && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, i))) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000011712 i++;
11713 }
11714 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011715
Benjamin Peterson14339b62009-01-31 16:36:08 +000011716 j = len;
11717 if (striptype != LEFTSTRIP) {
11718 do {
11719 j--;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011720 } while (j >= i && Py_UNICODE_ISSPACE(PyUnicode_READ(kind, data, j)));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011721 j++;
11722 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011723
Victor Stinner7931d9a2011-11-04 00:22:48 +010011724 return PyUnicode_Substring(self, i, j);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011725}
11726
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011727
11728static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011729do_argstrip(PyObject *self, int striptype, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011730{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011731 PyObject *sep = NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011732
Benjamin Peterson14339b62009-01-31 16:36:08 +000011733 if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
11734 return NULL;
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011735
Benjamin Peterson14339b62009-01-31 16:36:08 +000011736 if (sep != NULL && sep != Py_None) {
11737 if (PyUnicode_Check(sep))
11738 return _PyUnicode_XStrip(self, striptype, sep);
11739 else {
11740 PyErr_Format(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000011741 "%s arg must be None or str",
11742 STRIPNAME(striptype));
Benjamin Peterson14339b62009-01-31 16:36:08 +000011743 return NULL;
11744 }
11745 }
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011746
Benjamin Peterson14339b62009-01-31 16:36:08 +000011747 return do_strip(self, striptype);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011748}
11749
11750
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011751PyDoc_STRVAR(strip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011752 "S.strip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011753\n\
11754Return a copy of the string S with leading and trailing\n\
11755whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011756If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011757
11758static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011759unicode_strip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011760{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011761 if (PyTuple_GET_SIZE(args) == 0)
11762 return do_strip(self, BOTHSTRIP); /* Common case */
11763 else
11764 return do_argstrip(self, BOTHSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011765}
11766
11767
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011768PyDoc_STRVAR(lstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011769 "S.lstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011770\n\
11771Return a copy of the string S with leading whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011772If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011773
11774static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011775unicode_lstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011776{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011777 if (PyTuple_GET_SIZE(args) == 0)
11778 return do_strip(self, LEFTSTRIP); /* Common case */
11779 else
11780 return do_argstrip(self, LEFTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011781}
11782
11783
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011784PyDoc_STRVAR(rstrip__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000011785 "S.rstrip([chars]) -> str\n\
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011786\n\
11787Return a copy of the string S with trailing whitespace removed.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000011788If chars is given and not None, remove characters in chars instead.");
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011789
11790static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011791unicode_rstrip(PyObject *self, PyObject *args)
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011792{
Benjamin Peterson14339b62009-01-31 16:36:08 +000011793 if (PyTuple_GET_SIZE(args) == 0)
11794 return do_strip(self, RIGHTSTRIP); /* Common case */
11795 else
11796 return do_argstrip(self, RIGHTSTRIP, args);
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000011797}
11798
11799
Guido van Rossumd57fd912000-03-10 22:53:23 +000011800static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011801unicode_repeat(PyObject *str, Py_ssize_t len)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011802{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011803 PyObject *u;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011804 Py_ssize_t nchars, n;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011805
Georg Brandl222de0f2009-04-12 12:01:50 +000011806 if (len < 1) {
11807 Py_INCREF(unicode_empty);
Victor Stinnera464fc12011-10-02 20:39:30 +020011808 return unicode_empty;
Georg Brandl222de0f2009-04-12 12:01:50 +000011809 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011810
Tim Peters7a29bd52001-09-12 03:03:31 +000011811 if (len == 1 && PyUnicode_CheckExact(str)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000011812 /* no repeat, return original string */
11813 Py_INCREF(str);
Victor Stinner7931d9a2011-11-04 00:22:48 +010011814 return str;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011815 }
Tim Peters8f422462000-09-09 06:13:41 +000011816
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011817 if (PyUnicode_READY(str) == -1)
11818 return NULL;
11819
Victor Stinnerc759f3e2011-10-01 03:09:58 +020011820 if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
Victor Stinner67ca64c2011-10-01 02:47:29 +020011821 PyErr_SetString(PyExc_OverflowError,
11822 "repeated string is too long");
11823 return NULL;
11824 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011825 nchars = len * PyUnicode_GET_LENGTH(str);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011826
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011827 u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011828 if (!u)
11829 return NULL;
Victor Stinner67ca64c2011-10-01 02:47:29 +020011830 assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));
Guido van Rossumd57fd912000-03-10 22:53:23 +000011831
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011832 if (PyUnicode_GET_LENGTH(str) == 1) {
11833 const int kind = PyUnicode_KIND(str);
11834 const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
11835 void *to = PyUnicode_DATA(u);
Victor Stinner67ca64c2011-10-01 02:47:29 +020011836 if (kind == PyUnicode_1BYTE_KIND)
11837 memset(to, (unsigned char)fill_char, len);
11838 else {
11839 for (n = 0; n < len; ++n)
11840 PyUnicode_WRITE(kind, to, n, fill_char);
11841 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011842 }
11843 else {
11844 /* number of characters copied this far */
11845 Py_ssize_t done = PyUnicode_GET_LENGTH(str);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020011846 const Py_ssize_t char_size = PyUnicode_KIND(str);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011847 char *to = (char *) PyUnicode_DATA(u);
11848 Py_MEMCPY(to, PyUnicode_DATA(str),
11849 PyUnicode_GET_LENGTH(str) * char_size);
Benjamin Peterson29060642009-01-31 22:14:21 +000011850 while (done < nchars) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011851 n = (done <= nchars-done) ? done : nchars-done;
11852 Py_MEMCPY(to + (done * char_size), to, n * char_size);
Thomas Wouters477c8d52006-05-27 19:21:47 +000011853 done += n;
Benjamin Peterson29060642009-01-31 22:14:21 +000011854 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011855 }
11856
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020011857 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner9db1a8b2011-10-23 20:04:37 +020011858 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011859}
11860
Alexander Belopolsky40018472011-02-26 01:02:56 +000011861PyObject *
11862PyUnicode_Replace(PyObject *obj,
11863 PyObject *subobj,
11864 PyObject *replobj,
11865 Py_ssize_t maxcount)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011866{
11867 PyObject *self;
11868 PyObject *str1;
11869 PyObject *str2;
11870 PyObject *result;
11871
11872 self = PyUnicode_FromObject(obj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011873 if (self == NULL || PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011874 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011875 str1 = PyUnicode_FromObject(subobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011876 if (str1 == NULL || PyUnicode_READY(str1) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011877 Py_DECREF(self);
11878 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011879 }
11880 str2 = PyUnicode_FromObject(replobj);
Victor Stinnere9a29352011-10-01 02:14:59 +020011881 if (str2 == NULL || PyUnicode_READY(str2)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011882 Py_DECREF(self);
11883 Py_DECREF(str1);
11884 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011885 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011886 result = replace(self, str1, str2, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000011887 Py_DECREF(self);
11888 Py_DECREF(str1);
11889 Py_DECREF(str2);
11890 return result;
11891}
11892
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000011893PyDoc_STRVAR(replace__doc__,
Ezio Melottic1897e72010-06-26 18:50:39 +000011894 "S.replace(old, new[, count]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000011895\n\
11896Return a copy of S with all occurrences of substring\n\
Georg Brandlf08a9dd2008-06-10 16:57:31 +000011897old replaced by new. If the optional argument count is\n\
11898given, only the first count occurrences are replaced.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000011899
11900static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011901unicode_replace(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011902{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011903 PyObject *str1;
11904 PyObject *str2;
Martin v. Löwis18e16552006-02-15 17:27:45 +000011905 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000011906 PyObject *result;
11907
Martin v. Löwis18e16552006-02-15 17:27:45 +000011908 if (!PyArg_ParseTuple(args, "OO|n:replace", &str1, &str2, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000011909 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011910 if (!PyUnicode_READY(self) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000011911 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011912 str1 = PyUnicode_FromObject(str1);
11913 if (str1 == NULL || PyUnicode_READY(str1) == -1)
11914 return NULL;
11915 str2 = PyUnicode_FromObject(str2);
Victor Stinnere9a29352011-10-01 02:14:59 +020011916 if (str2 == NULL || PyUnicode_READY(str2) == -1) {
Benjamin Peterson29060642009-01-31 22:14:21 +000011917 Py_DECREF(str1);
11918 return NULL;
Walter Dörwaldf6b56ae2003-02-09 23:42:56 +000011919 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000011920
11921 result = replace(self, str1, str2, maxcount);
11922
11923 Py_DECREF(str1);
11924 Py_DECREF(str2);
11925 return result;
11926}
11927
Alexander Belopolsky40018472011-02-26 01:02:56 +000011928static PyObject *
11929unicode_repr(PyObject *unicode)
Guido van Rossumd57fd912000-03-10 22:53:23 +000011930{
Walter Dörwald79e913e2007-05-12 11:08:06 +000011931 PyObject *repr;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011932 Py_ssize_t isize;
11933 Py_ssize_t osize, squote, dquote, i, o;
11934 Py_UCS4 max, quote;
11935 int ikind, okind;
11936 void *idata, *odata;
Walter Dörwald79e913e2007-05-12 11:08:06 +000011937
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011938 if (PyUnicode_READY(unicode) == -1)
Walter Dörwald79e913e2007-05-12 11:08:06 +000011939 return NULL;
11940
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011941 isize = PyUnicode_GET_LENGTH(unicode);
11942 idata = PyUnicode_DATA(unicode);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011943
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011944 /* Compute length of output, quote characters, and
11945 maximum character */
11946 osize = 2; /* quotes */
11947 max = 127;
11948 squote = dquote = 0;
11949 ikind = PyUnicode_KIND(unicode);
11950 for (i = 0; i < isize; i++) {
11951 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
11952 switch (ch) {
11953 case '\'': squote++; osize++; break;
11954 case '"': dquote++; osize++; break;
11955 case '\\': case '\t': case '\r': case '\n':
11956 osize += 2; break;
11957 default:
11958 /* Fast-path ASCII */
11959 if (ch < ' ' || ch == 0x7f)
11960 osize += 4; /* \xHH */
11961 else if (ch < 0x7f)
11962 osize++;
11963 else if (Py_UNICODE_ISPRINTABLE(ch)) {
11964 osize++;
11965 max = ch > max ? ch : max;
11966 }
11967 else if (ch < 0x100)
11968 osize += 4; /* \xHH */
11969 else if (ch < 0x10000)
11970 osize += 6; /* \uHHHH */
11971 else
11972 osize += 10; /* \uHHHHHHHH */
11973 }
11974 }
11975
11976 quote = '\'';
11977 if (squote) {
11978 if (dquote)
11979 /* Both squote and dquote present. Use squote,
11980 and escape them */
11981 osize += squote;
11982 else
11983 quote = '"';
11984 }
11985
11986 repr = PyUnicode_New(osize, max);
11987 if (repr == NULL)
11988 return NULL;
11989 okind = PyUnicode_KIND(repr);
11990 odata = PyUnicode_DATA(repr);
11991
11992 PyUnicode_WRITE(okind, odata, 0, quote);
11993 PyUnicode_WRITE(okind, odata, osize-1, quote);
11994
11995 for (i = 0, o = 1; i < isize; i++) {
11996 Py_UCS4 ch = PyUnicode_READ(ikind, idata, i);
Walter Dörwald79e913e2007-05-12 11:08:06 +000011997
11998 /* Escape quotes and backslashes */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020011999 if ((ch == quote) || (ch == '\\')) {
12000 PyUnicode_WRITE(okind, odata, o++, '\\');
12001 PyUnicode_WRITE(okind, odata, o++, ch);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012002 continue;
12003 }
12004
Benjamin Peterson29060642009-01-31 22:14:21 +000012005 /* Map special whitespace to '\t', \n', '\r' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012006 if (ch == '\t') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012007 PyUnicode_WRITE(okind, odata, o++, '\\');
12008 PyUnicode_WRITE(okind, odata, o++, 't');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012009 }
12010 else if (ch == '\n') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012011 PyUnicode_WRITE(okind, odata, o++, '\\');
12012 PyUnicode_WRITE(okind, odata, o++, 'n');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012013 }
12014 else if (ch == '\r') {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012015 PyUnicode_WRITE(okind, odata, o++, '\\');
12016 PyUnicode_WRITE(okind, odata, o++, 'r');
Walter Dörwald79e913e2007-05-12 11:08:06 +000012017 }
12018
12019 /* Map non-printable US ASCII to '\xhh' */
Georg Brandl559e5d72008-06-11 18:37:52 +000012020 else if (ch < ' ' || ch == 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012021 PyUnicode_WRITE(okind, odata, o++, '\\');
12022 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012023 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12024 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Walter Dörwald79e913e2007-05-12 11:08:06 +000012025 }
12026
Georg Brandl559e5d72008-06-11 18:37:52 +000012027 /* Copy ASCII characters as-is */
12028 else if (ch < 0x7F) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012029 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012030 }
12031
Benjamin Peterson29060642009-01-31 22:14:21 +000012032 /* Non-ASCII characters */
Georg Brandl559e5d72008-06-11 18:37:52 +000012033 else {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012034 /* Map Unicode whitespace and control characters
Georg Brandl559e5d72008-06-11 18:37:52 +000012035 (categories Z* and C* except ASCII space)
12036 */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012037 if (!Py_UNICODE_ISPRINTABLE(ch)) {
Georg Brandl559e5d72008-06-11 18:37:52 +000012038 /* Map 8-bit characters to '\xhh' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012039 if (ch <= 0xff) {
12040 PyUnicode_WRITE(okind, odata, o++, '\\');
12041 PyUnicode_WRITE(okind, odata, o++, 'x');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012042 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0x000F]);
12043 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0x000F]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012044 }
12045 /* Map 21-bit characters to '\U00xxxxxx' */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012046 else if (ch >= 0x10000) {
12047 PyUnicode_WRITE(okind, odata, o++, '\\');
12048 PyUnicode_WRITE(okind, odata, o++, 'U');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012049 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 28) & 0xF]);
12050 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 24) & 0xF]);
12051 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 20) & 0xF]);
12052 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 16) & 0xF]);
12053 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12054 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12055 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12056 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012057 }
12058 /* Map 16-bit characters to '\uxxxx' */
12059 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012060 PyUnicode_WRITE(okind, odata, o++, '\\');
12061 PyUnicode_WRITE(okind, odata, o++, 'u');
Victor Stinnerf5cff562011-10-14 02:13:11 +020012062 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 12) & 0xF]);
12063 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 8) & 0xF]);
12064 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[(ch >> 4) & 0xF]);
12065 PyUnicode_WRITE(okind, odata, o++, Py_hexdigits[ch & 0xF]);
Georg Brandl559e5d72008-06-11 18:37:52 +000012066 }
12067 }
12068 /* Copy characters as-is */
12069 else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012070 PyUnicode_WRITE(okind, odata, o++, ch);
Georg Brandl559e5d72008-06-11 18:37:52 +000012071 }
12072 }
Walter Dörwald79e913e2007-05-12 11:08:06 +000012073 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012074 /* Closing quote already added at the beginning */
Victor Stinner05d11892011-10-06 01:13:58 +020012075 assert(_PyUnicode_CheckConsistency(repr, 1));
Walter Dörwald79e913e2007-05-12 11:08:06 +000012076 return repr;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012077}
12078
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012079PyDoc_STRVAR(rfind__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012080 "S.rfind(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012081\n\
12082Return the highest index in S where substring sub is found,\n\
Senthil Kumaran53516a82011-07-27 23:33:54 +080012083such that sub is contained within S[start:end]. Optional\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012084arguments start and end are interpreted as in slice notation.\n\
12085\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012086Return -1 on failure.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012087
12088static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012089unicode_rfind(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012090{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012091 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012092 Py_ssize_t start;
12093 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012094 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012095
Jesus Ceaac451502011-04-20 17:09:23 +020012096 if (!stringlib_parse_args_finds_unicode("rfind", args, &substring,
12097 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012098 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012099
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012100 if (PyUnicode_READY(self) == -1)
12101 return NULL;
12102 if (PyUnicode_READY(substring) == -1)
12103 return NULL;
12104
Victor Stinner7931d9a2011-11-04 00:22:48 +010012105 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012106
12107 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012108
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012109 if (result == -2)
12110 return NULL;
12111
Christian Heimes217cfd12007-12-02 14:31:20 +000012112 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012113}
12114
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012115PyDoc_STRVAR(rindex__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012116 "S.rindex(sub[, start[, end]]) -> int\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012117\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012118Like S.rfind() but raise ValueError when the substring is not found.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012119
12120static PyObject *
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012121unicode_rindex(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012122{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012123 PyObject *substring;
Christian Heimes9cd17752007-11-18 19:35:23 +000012124 Py_ssize_t start;
12125 Py_ssize_t end;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012126 Py_ssize_t result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012127
Jesus Ceaac451502011-04-20 17:09:23 +020012128 if (!stringlib_parse_args_finds_unicode("rindex", args, &substring,
12129 &start, &end))
Benjamin Peterson14339b62009-01-31 16:36:08 +000012130 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012131
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012132 if (PyUnicode_READY(self) == -1)
12133 return NULL;
12134 if (PyUnicode_READY(substring) == -1)
12135 return NULL;
12136
Victor Stinner7931d9a2011-11-04 00:22:48 +010012137 result = any_find_slice(-1, self, substring, start, end);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012138
12139 Py_DECREF(substring);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012140
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012141 if (result == -2)
12142 return NULL;
12143
Guido van Rossumd57fd912000-03-10 22:53:23 +000012144 if (result < 0) {
12145 PyErr_SetString(PyExc_ValueError, "substring not found");
12146 return NULL;
12147 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012148
Christian Heimes217cfd12007-12-02 14:31:20 +000012149 return PyLong_FromSsize_t(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012150}
12151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012152PyDoc_STRVAR(rjust__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012153 "S.rjust(width[, fillchar]) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012154\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012155Return S right-justified in a string of length width. Padding is\n\
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012156done using the specified fill character (default is a space).");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012157
12158static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012159unicode_rjust(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012160{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012161 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012162 Py_UCS4 fillchar = ' ';
12163
Victor Stinnere9a29352011-10-01 02:14:59 +020012164 if (!PyArg_ParseTuple(args, "n|O&:rjust", &width, convert_uc, &fillchar))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012165 return NULL;
Raymond Hettinger4f8f9762003-11-26 08:21:35 +000012166
Victor Stinnere9a29352011-10-01 02:14:59 +020012167 if (PyUnicode_READY(self) == -1)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012168 return NULL;
12169
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012170 if (_PyUnicode_LENGTH(self) >= width && PyUnicode_CheckExact(self)) {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012171 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012172 return self;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012173 }
12174
Victor Stinner7931d9a2011-11-04 00:22:48 +010012175 return pad(self, width - _PyUnicode_LENGTH(self), 0, fillchar);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012176}
12177
Alexander Belopolsky40018472011-02-26 01:02:56 +000012178PyObject *
12179PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012180{
12181 PyObject *result;
Tim Petersced69f82003-09-16 20:30:58 +000012182
Guido van Rossumd57fd912000-03-10 22:53:23 +000012183 s = PyUnicode_FromObject(s);
12184 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012185 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012186 if (sep != NULL) {
12187 sep = PyUnicode_FromObject(sep);
12188 if (sep == NULL) {
12189 Py_DECREF(s);
12190 return NULL;
12191 }
Guido van Rossumd57fd912000-03-10 22:53:23 +000012192 }
12193
Victor Stinner9310abb2011-10-05 00:59:23 +020012194 result = split(s, sep, maxsplit);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012195
12196 Py_DECREF(s);
12197 Py_XDECREF(sep);
12198 return result;
12199}
12200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012201PyDoc_STRVAR(split__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012202 "S.split([sep[, maxsplit]]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012203\n\
12204Return a list of the words in S, using sep as the\n\
12205delimiter string. If maxsplit is given, at most maxsplit\n\
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +000012206splits are done. If sep is not specified or is None, any\n\
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +000012207whitespace string is a separator and empty strings are\n\
12208removed from the result.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012209
12210static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012211unicode_split(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012212{
12213 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012214 Py_ssize_t maxcount = -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012215
Martin v. Löwis18e16552006-02-15 17:27:45 +000012216 if (!PyArg_ParseTuple(args, "|On:split", &substring, &maxcount))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012217 return NULL;
12218
12219 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012220 return split(self, NULL, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012221 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012222 return split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012223 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012224 return PyUnicode_Split(self, substring, maxcount);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012225}
12226
Thomas Wouters477c8d52006-05-27 19:21:47 +000012227PyObject *
12228PyUnicode_Partition(PyObject *str_in, PyObject *sep_in)
12229{
12230 PyObject* str_obj;
12231 PyObject* sep_obj;
12232 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012233 int kind1, kind2, kind;
12234 void *buf1 = NULL, *buf2 = NULL;
12235 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012236
12237 str_obj = PyUnicode_FromObject(str_in);
Victor Stinnere9a29352011-10-01 02:14:59 +020012238 if (!str_obj || PyUnicode_READY(str_obj) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000012239 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012240 sep_obj = PyUnicode_FromObject(sep_in);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012241 if (!sep_obj || PyUnicode_READY(sep_obj) == -1) {
Thomas Wouters477c8d52006-05-27 19:21:47 +000012242 Py_DECREF(str_obj);
12243 return NULL;
12244 }
12245
Victor Stinner14f8f022011-10-05 20:58:25 +020012246 kind1 = PyUnicode_KIND(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012247 kind2 = PyUnicode_KIND(sep_obj);
Victor Stinner14f8f022011-10-05 20:58:25 +020012248 kind = Py_MAX(kind1, kind2);
12249 buf1 = PyUnicode_DATA(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012250 if (kind1 != kind)
Victor Stinner14f8f022011-10-05 20:58:25 +020012251 buf1 = _PyUnicode_AsKind(str_obj, kind);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012252 if (!buf1)
12253 goto onError;
12254 buf2 = PyUnicode_DATA(sep_obj);
12255 if (kind2 != kind)
12256 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12257 if (!buf2)
12258 goto onError;
12259 len1 = PyUnicode_GET_LENGTH(str_obj);
12260 len2 = PyUnicode_GET_LENGTH(sep_obj);
12261
Victor Stinner14f8f022011-10-05 20:58:25 +020012262 switch(PyUnicode_KIND(str_obj)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012263 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012264 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12265 out = asciilib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12266 else
12267 out = ucs1lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012268 break;
12269 case PyUnicode_2BYTE_KIND:
12270 out = ucs2lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12271 break;
12272 case PyUnicode_4BYTE_KIND:
12273 out = ucs4lib_partition(str_obj, buf1, len1, sep_obj, buf2, len2);
12274 break;
12275 default:
12276 assert(0);
12277 out = 0;
12278 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012279
12280 Py_DECREF(sep_obj);
12281 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012282 if (kind1 != kind)
12283 PyMem_Free(buf1);
12284 if (kind2 != kind)
12285 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012286
12287 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012288 onError:
12289 Py_DECREF(sep_obj);
12290 Py_DECREF(str_obj);
12291 if (kind1 != kind && buf1)
12292 PyMem_Free(buf1);
12293 if (kind2 != kind && buf2)
12294 PyMem_Free(buf2);
12295 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012296}
12297
12298
12299PyObject *
12300PyUnicode_RPartition(PyObject *str_in, PyObject *sep_in)
12301{
12302 PyObject* str_obj;
12303 PyObject* sep_obj;
12304 PyObject* out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012305 int kind1, kind2, kind;
12306 void *buf1 = NULL, *buf2 = NULL;
12307 Py_ssize_t len1, len2;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012308
12309 str_obj = PyUnicode_FromObject(str_in);
12310 if (!str_obj)
Benjamin Peterson29060642009-01-31 22:14:21 +000012311 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012312 sep_obj = PyUnicode_FromObject(sep_in);
12313 if (!sep_obj) {
12314 Py_DECREF(str_obj);
12315 return NULL;
12316 }
12317
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012318 kind1 = PyUnicode_KIND(str_in);
12319 kind2 = PyUnicode_KIND(sep_obj);
Georg Brandl4cb0de22011-09-28 21:49:49 +020012320 kind = Py_MAX(kind1, kind2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012321 buf1 = PyUnicode_DATA(str_in);
12322 if (kind1 != kind)
12323 buf1 = _PyUnicode_AsKind(str_in, kind);
12324 if (!buf1)
12325 goto onError;
12326 buf2 = PyUnicode_DATA(sep_obj);
12327 if (kind2 != kind)
12328 buf2 = _PyUnicode_AsKind(sep_obj, kind);
12329 if (!buf2)
12330 goto onError;
12331 len1 = PyUnicode_GET_LENGTH(str_obj);
12332 len2 = PyUnicode_GET_LENGTH(sep_obj);
12333
12334 switch(PyUnicode_KIND(str_in)) {
12335 case PyUnicode_1BYTE_KIND:
Victor Stinnerc3cec782011-10-05 21:24:08 +020012336 if (PyUnicode_IS_ASCII(str_obj) && PyUnicode_IS_ASCII(sep_obj))
12337 out = asciilib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12338 else
12339 out = ucs1lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012340 break;
12341 case PyUnicode_2BYTE_KIND:
12342 out = ucs2lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12343 break;
12344 case PyUnicode_4BYTE_KIND:
12345 out = ucs4lib_rpartition(str_obj, buf1, len1, sep_obj, buf2, len2);
12346 break;
12347 default:
12348 assert(0);
12349 out = 0;
12350 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000012351
12352 Py_DECREF(sep_obj);
12353 Py_DECREF(str_obj);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012354 if (kind1 != kind)
12355 PyMem_Free(buf1);
12356 if (kind2 != kind)
12357 PyMem_Free(buf2);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012358
12359 return out;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012360 onError:
12361 Py_DECREF(sep_obj);
12362 Py_DECREF(str_obj);
12363 if (kind1 != kind && buf1)
12364 PyMem_Free(buf1);
12365 if (kind2 != kind && buf2)
12366 PyMem_Free(buf2);
12367 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +000012368}
12369
12370PyDoc_STRVAR(partition__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012371 "S.partition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012372\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012373Search for the separator sep in S, and return the part before it,\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012374the separator itself, and the part after it. If the separator is not\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012375found, return S and two empty strings.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012376
12377static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012378unicode_partition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012379{
Victor Stinner9310abb2011-10-05 00:59:23 +020012380 return PyUnicode_Partition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012381}
12382
12383PyDoc_STRVAR(rpartition__doc__,
Ezio Melotti5b2b2422010-01-25 11:58:28 +000012384 "S.rpartition(sep) -> (head, sep, tail)\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012385\n\
Georg Brandl17cb8a82008-05-30 08:20:09 +000012386Search for the separator sep in S, starting at the end of S, and return\n\
Thomas Wouters477c8d52006-05-27 19:21:47 +000012387the part before it, the separator itself, and the part after it. If the\n\
Benjamin Petersonf10a79a2008-10-11 00:49:57 +000012388separator is not found, return two empty strings and S.");
Thomas Wouters477c8d52006-05-27 19:21:47 +000012389
12390static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012391unicode_rpartition(PyObject *self, PyObject *separator)
Thomas Wouters477c8d52006-05-27 19:21:47 +000012392{
Victor Stinner9310abb2011-10-05 00:59:23 +020012393 return PyUnicode_RPartition(self, separator);
Thomas Wouters477c8d52006-05-27 19:21:47 +000012394}
12395
Alexander Belopolsky40018472011-02-26 01:02:56 +000012396PyObject *
12397PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012398{
12399 PyObject *result;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012400
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012401 s = PyUnicode_FromObject(s);
12402 if (s == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000012403 return NULL;
Benjamin Peterson29060642009-01-31 22:14:21 +000012404 if (sep != NULL) {
12405 sep = PyUnicode_FromObject(sep);
12406 if (sep == NULL) {
12407 Py_DECREF(s);
12408 return NULL;
12409 }
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012410 }
12411
Victor Stinner9310abb2011-10-05 00:59:23 +020012412 result = rsplit(s, sep, maxsplit);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012413
12414 Py_DECREF(s);
12415 Py_XDECREF(sep);
12416 return result;
12417}
12418
12419PyDoc_STRVAR(rsplit__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012420 "S.rsplit([sep[, maxsplit]]) -> list of strings\n\
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012421\n\
12422Return a list of the words in S, using sep as the\n\
12423delimiter string, starting at the end of the string and\n\
12424working to the front. If maxsplit is given, at most maxsplit\n\
12425splits are done. If sep is not specified, any whitespace string\n\
12426is a separator.");
12427
12428static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012429unicode_rsplit(PyObject *self, PyObject *args)
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012430{
12431 PyObject *substring = Py_None;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012432 Py_ssize_t maxcount = -1;
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012433
Martin v. Löwis18e16552006-02-15 17:27:45 +000012434 if (!PyArg_ParseTuple(args, "|On:rsplit", &substring, &maxcount))
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012435 return NULL;
12436
12437 if (substring == Py_None)
Benjamin Peterson29060642009-01-31 22:14:21 +000012438 return rsplit(self, NULL, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012439 else if (PyUnicode_Check(substring))
Victor Stinner9310abb2011-10-05 00:59:23 +020012440 return rsplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012441 else
Victor Stinner9310abb2011-10-05 00:59:23 +020012442 return PyUnicode_RSplit(self, substring, maxcount);
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012443}
12444
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012445PyDoc_STRVAR(splitlines__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012446 "S.splitlines([keepends]) -> list of strings\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012447\n\
12448Return a list of the lines in S, breaking at line boundaries.\n\
Guido van Rossum86662912000-04-11 15:38:46 +000012449Line breaks are not included in the resulting list unless keepends\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012450is given and true.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012451
12452static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012453unicode_splitlines(PyObject *self, PyObject *args, PyObject *kwds)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012454{
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012455 static char *kwlist[] = {"keepends", 0};
Guido van Rossum86662912000-04-11 15:38:46 +000012456 int keepends = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012457
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012458 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:splitlines",
12459 kwlist, &keepends))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012460 return NULL;
12461
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012462 return PyUnicode_Splitlines(self, keepends);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012463}
12464
12465static
Guido van Rossumf15a29f2007-05-04 00:41:39 +000012466PyObject *unicode_str(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012467{
Walter Dörwald346737f2007-05-31 10:44:43 +000012468 if (PyUnicode_CheckExact(self)) {
12469 Py_INCREF(self);
12470 return self;
12471 } else
12472 /* Subtype -- return genuine unicode string with the same value. */
Victor Stinner034f6cf2011-09-30 02:26:44 +020012473 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012474}
12475
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012476PyDoc_STRVAR(swapcase__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012477 "S.swapcase() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012478\n\
12479Return a copy of S with uppercase characters converted to lowercase\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012480and vice versa.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012481
12482static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012483unicode_swapcase(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012484{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012485 return fixup(self, fixswapcase);
12486}
12487
Georg Brandlceee0772007-11-27 23:48:05 +000012488PyDoc_STRVAR(maketrans__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012489 "str.maketrans(x[, y[, z]]) -> dict (static method)\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012490\n\
12491Return a translation table usable for str.translate().\n\
12492If there is only one argument, it must be a dictionary mapping Unicode\n\
12493ordinals (integers) or characters to Unicode ordinals, strings or None.\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012494Character keys will be then converted to ordinals.\n\
Georg Brandlceee0772007-11-27 23:48:05 +000012495If there are two arguments, they must be strings of equal length, and\n\
12496in the resulting dictionary, each character in x will be mapped to the\n\
12497character at the same position in y. If there is a third argument, it\n\
12498must be a string, whose characters will be mapped to None in the result.");
12499
12500static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012501unicode_maketrans(PyObject *null, PyObject *args)
Georg Brandlceee0772007-11-27 23:48:05 +000012502{
12503 PyObject *x, *y = NULL, *z = NULL;
12504 PyObject *new = NULL, *key, *value;
12505 Py_ssize_t i = 0;
12506 int res;
Benjamin Peterson14339b62009-01-31 16:36:08 +000012507
Georg Brandlceee0772007-11-27 23:48:05 +000012508 if (!PyArg_ParseTuple(args, "O|UU:maketrans", &x, &y, &z))
12509 return NULL;
12510 new = PyDict_New();
12511 if (!new)
12512 return NULL;
12513 if (y != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012514 int x_kind, y_kind, z_kind;
12515 void *x_data, *y_data, *z_data;
12516
Georg Brandlceee0772007-11-27 23:48:05 +000012517 /* x must be a string too, of equal length */
Georg Brandlceee0772007-11-27 23:48:05 +000012518 if (!PyUnicode_Check(x)) {
12519 PyErr_SetString(PyExc_TypeError, "first maketrans argument must "
12520 "be a string if there is a second argument");
12521 goto err;
12522 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012523 if (PyUnicode_GET_LENGTH(x) != PyUnicode_GET_LENGTH(y)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012524 PyErr_SetString(PyExc_ValueError, "the first two maketrans "
12525 "arguments must have equal length");
12526 goto err;
12527 }
12528 /* create entries for translating chars in x to those in y */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012529 x_kind = PyUnicode_KIND(x);
12530 y_kind = PyUnicode_KIND(y);
12531 x_data = PyUnicode_DATA(x);
12532 y_data = PyUnicode_DATA(y);
12533 for (i = 0; i < PyUnicode_GET_LENGTH(x); i++) {
12534 key = PyLong_FromLong(PyUnicode_READ(x_kind, x_data, i));
12535 value = PyLong_FromLong(PyUnicode_READ(y_kind, y_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012536 if (!key || !value)
12537 goto err;
12538 res = PyDict_SetItem(new, key, value);
12539 Py_DECREF(key);
12540 Py_DECREF(value);
12541 if (res < 0)
12542 goto err;
12543 }
12544 /* create entries for deleting chars in z */
12545 if (z != NULL) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012546 z_kind = PyUnicode_KIND(z);
12547 z_data = PyUnicode_DATA(z);
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012548 for (i = 0; i < PyUnicode_GET_LENGTH(z); i++) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012549 key = PyLong_FromLong(PyUnicode_READ(z_kind, z_data, i));
Georg Brandlceee0772007-11-27 23:48:05 +000012550 if (!key)
12551 goto err;
12552 res = PyDict_SetItem(new, key, Py_None);
12553 Py_DECREF(key);
12554 if (res < 0)
12555 goto err;
12556 }
12557 }
12558 } else {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012559 int kind;
12560 void *data;
12561
Georg Brandlceee0772007-11-27 23:48:05 +000012562 /* x must be a dict */
Raymond Hettinger3ad05762009-05-29 22:11:22 +000012563 if (!PyDict_CheckExact(x)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012564 PyErr_SetString(PyExc_TypeError, "if you give only one argument "
12565 "to maketrans it must be a dict");
12566 goto err;
12567 }
12568 /* copy entries into the new dict, converting string keys to int keys */
12569 while (PyDict_Next(x, &i, &key, &value)) {
12570 if (PyUnicode_Check(key)) {
12571 /* convert string keys to integer keys */
12572 PyObject *newkey;
Victor Stinnerc4f281e2011-10-11 22:11:42 +020012573 if (PyUnicode_GET_LENGTH(key) != 1) {
Georg Brandlceee0772007-11-27 23:48:05 +000012574 PyErr_SetString(PyExc_ValueError, "string keys in translate "
12575 "table must be of length 1");
12576 goto err;
12577 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012578 kind = PyUnicode_KIND(key);
12579 data = PyUnicode_DATA(key);
12580 newkey = PyLong_FromLong(PyUnicode_READ(kind, data, 0));
Georg Brandlceee0772007-11-27 23:48:05 +000012581 if (!newkey)
12582 goto err;
12583 res = PyDict_SetItem(new, newkey, value);
12584 Py_DECREF(newkey);
12585 if (res < 0)
12586 goto err;
Christian Heimes217cfd12007-12-02 14:31:20 +000012587 } else if (PyLong_Check(key)) {
Georg Brandlceee0772007-11-27 23:48:05 +000012588 /* just keep integer keys */
12589 if (PyDict_SetItem(new, key, value) < 0)
12590 goto err;
12591 } else {
12592 PyErr_SetString(PyExc_TypeError, "keys in translate table must "
12593 "be strings or integers");
12594 goto err;
12595 }
12596 }
12597 }
12598 return new;
12599 err:
12600 Py_DECREF(new);
12601 return NULL;
12602}
12603
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012604PyDoc_STRVAR(translate__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012605 "S.translate(table) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012606\n\
12607Return a copy of the string S, where all characters have been mapped\n\
12608through the given translation table, which must be a mapping of\n\
Benjamin Peterson142957c2008-07-04 19:55:29 +000012609Unicode ordinals to Unicode ordinals, strings, or None.\n\
Walter Dörwald5c1ee172002-09-04 20:31:32 +000012610Unmapped characters are left untouched. Characters mapped to None\n\
12611are deleted.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012612
12613static PyObject*
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012614unicode_translate(PyObject *self, PyObject *table)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012615{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012616 return _PyUnicode_TranslateCharmap(self, table, "ignore");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012617}
12618
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012619PyDoc_STRVAR(upper__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012620 "S.upper() -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012621\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012622Return a copy of S converted to uppercase.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012623
12624static PyObject*
Victor Stinner9310abb2011-10-05 00:59:23 +020012625unicode_upper(PyObject *self)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012626{
Guido van Rossumd57fd912000-03-10 22:53:23 +000012627 return fixup(self, fixupper);
12628}
12629
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012630PyDoc_STRVAR(zfill__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012631 "S.zfill(width) -> str\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012632\n\
Benjamin Peterson9aa42992008-09-10 21:57:34 +000012633Pad a numeric string S with zeros on the left, to fill a field\n\
12634of the specified width. The string S is never truncated.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012635
12636static PyObject *
Victor Stinner9310abb2011-10-05 00:59:23 +020012637unicode_zfill(PyObject *self, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012638{
Martin v. Löwis18e16552006-02-15 17:27:45 +000012639 Py_ssize_t fill;
Victor Stinner9310abb2011-10-05 00:59:23 +020012640 PyObject *u;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012641 Py_ssize_t width;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012642 int kind;
12643 void *data;
12644 Py_UCS4 chr;
12645
12646 if (PyUnicode_READY(self) == -1)
12647 return NULL;
12648
Martin v. Löwis18e16552006-02-15 17:27:45 +000012649 if (!PyArg_ParseTuple(args, "n:zfill", &width))
Guido van Rossumd57fd912000-03-10 22:53:23 +000012650 return NULL;
12651
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012652 if (PyUnicode_GET_LENGTH(self) >= width) {
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012653 if (PyUnicode_CheckExact(self)) {
12654 Py_INCREF(self);
Victor Stinner7931d9a2011-11-04 00:22:48 +010012655 return self;
Walter Dörwald0fe940c2002-04-15 18:42:15 +000012656 }
12657 else
Victor Stinner7931d9a2011-11-04 00:22:48 +010012658 return PyUnicode_Copy(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012659 }
12660
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012661 fill = width - _PyUnicode_LENGTH(self);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012662
12663 u = pad(self, fill, 0, '0');
12664
Walter Dörwald068325e2002-04-15 13:36:47 +000012665 if (u == NULL)
12666 return NULL;
12667
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012668 kind = PyUnicode_KIND(u);
12669 data = PyUnicode_DATA(u);
12670 chr = PyUnicode_READ(kind, data, fill);
12671
12672 if (chr == '+' || chr == '-') {
Guido van Rossumd57fd912000-03-10 22:53:23 +000012673 /* move sign to beginning of string */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012674 PyUnicode_WRITE(kind, data, 0, chr);
12675 PyUnicode_WRITE(kind, data, fill, '0');
Guido van Rossumd57fd912000-03-10 22:53:23 +000012676 }
12677
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012678 assert(_PyUnicode_CheckConsistency(u, 1));
Victor Stinner7931d9a2011-11-04 00:22:48 +010012679 return u;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012680}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012681
12682#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012683static PyObject *
12684unicode__decimal2ascii(PyObject *self)
12685{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012686 return PyUnicode_TransformDecimalAndSpaceToASCII(self);
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012687}
Guido van Rossumd57fd912000-03-10 22:53:23 +000012688#endif
12689
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012690PyDoc_STRVAR(startswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012691 "S.startswith(prefix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012692\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012693Return True if S starts with the specified prefix, False otherwise.\n\
12694With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012695With optional end, stop comparing S at that position.\n\
12696prefix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012697
12698static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012699unicode_startswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012700 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012701{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012702 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012703 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012704 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012705 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012706 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012707
Jesus Ceaac451502011-04-20 17:09:23 +020012708 if (!stringlib_parse_args_finds("startswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012709 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012710 if (PyTuple_Check(subobj)) {
12711 Py_ssize_t i;
12712 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012713 substring = PyUnicode_FromObject(PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012714 if (substring == NULL)
12715 return NULL;
12716 result = tailmatch(self, substring, start, end, -1);
12717 Py_DECREF(substring);
12718 if (result) {
12719 Py_RETURN_TRUE;
12720 }
12721 }
12722 /* nothing matched */
12723 Py_RETURN_FALSE;
12724 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012725 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012726 if (substring == NULL) {
12727 if (PyErr_ExceptionMatches(PyExc_TypeError))
12728 PyErr_Format(PyExc_TypeError, "startswith first arg must be str or "
12729 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012730 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012731 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012732 result = tailmatch(self, substring, start, end, -1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012733 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012734 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012735}
12736
12737
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000012738PyDoc_STRVAR(endswith__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012739 "S.endswith(suffix[, start[, end]]) -> bool\n\
Guido van Rossumd57fd912000-03-10 22:53:23 +000012740\n\
Guido van Rossuma7132182003-04-09 19:32:45 +000012741Return True if S ends with the specified suffix, False otherwise.\n\
12742With optional start, test S beginning at that position.\n\
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012743With optional end, stop comparing S at that position.\n\
12744suffix can also be a tuple of strings to try.");
Guido van Rossumd57fd912000-03-10 22:53:23 +000012745
12746static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012747unicode_endswith(PyObject *self,
Benjamin Peterson29060642009-01-31 22:14:21 +000012748 PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000012749{
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012750 PyObject *subobj;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012751 PyObject *substring;
Martin v. Löwis18e16552006-02-15 17:27:45 +000012752 Py_ssize_t start = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012753 Py_ssize_t end = PY_SSIZE_T_MAX;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012754 int result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000012755
Jesus Ceaac451502011-04-20 17:09:23 +020012756 if (!stringlib_parse_args_finds("endswith", args, &subobj, &start, &end))
Benjamin Peterson29060642009-01-31 22:14:21 +000012757 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012758 if (PyTuple_Check(subobj)) {
12759 Py_ssize_t i;
12760 for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012761 substring = PyUnicode_FromObject(
Benjamin Peterson29060642009-01-31 22:14:21 +000012762 PyTuple_GET_ITEM(subobj, i));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012763 if (substring == NULL)
Benjamin Peterson29060642009-01-31 22:14:21 +000012764 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012765 result = tailmatch(self, substring, start, end, +1);
12766 Py_DECREF(substring);
12767 if (result) {
12768 Py_RETURN_TRUE;
12769 }
12770 }
12771 Py_RETURN_FALSE;
12772 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012773 substring = PyUnicode_FromObject(subobj);
Ezio Melottiba42fd52011-04-26 06:09:45 +030012774 if (substring == NULL) {
12775 if (PyErr_ExceptionMatches(PyExc_TypeError))
12776 PyErr_Format(PyExc_TypeError, "endswith first arg must be str or "
12777 "a tuple of str, not %s", Py_TYPE(subobj)->tp_name);
Benjamin Peterson29060642009-01-31 22:14:21 +000012778 return NULL;
Ezio Melottiba42fd52011-04-26 06:09:45 +030012779 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012780 result = tailmatch(self, substring, start, end, +1);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012781 Py_DECREF(substring);
Thomas Wouters0e3f5912006-08-11 14:57:12 +000012782 return PyBool_FromLong(result);
Guido van Rossumd57fd912000-03-10 22:53:23 +000012783}
12784
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012785#include "stringlib/unicode_format.h"
Eric Smith8c663262007-08-25 02:26:07 +000012786
12787PyDoc_STRVAR(format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012788 "S.format(*args, **kwargs) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012789\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012790Return a formatted version of S, using substitutions from args and kwargs.\n\
12791The substitutions are identified by braces ('{' and '}').");
Eric Smith8c663262007-08-25 02:26:07 +000012792
Eric Smith27bbca62010-11-04 17:06:58 +000012793PyDoc_STRVAR(format_map__doc__,
12794 "S.format_map(mapping) -> str\n\
12795\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012796Return a formatted version of S, using substitutions from mapping.\n\
12797The substitutions are identified by braces ('{' and '}').");
Eric Smith27bbca62010-11-04 17:06:58 +000012798
Eric Smith4a7d76d2008-05-30 18:10:19 +000012799static PyObject *
12800unicode__format__(PyObject* self, PyObject* args)
12801{
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012802 PyObject *format_spec, *out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012803
12804 if (!PyArg_ParseTuple(args, "U:__format__", &format_spec))
12805 return NULL;
12806
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012807 out = _PyUnicode_FormatAdvanced(self, format_spec, 0,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012808 PyUnicode_GET_LENGTH(format_spec));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020012809 return out;
Eric Smith4a7d76d2008-05-30 18:10:19 +000012810}
12811
Eric Smith8c663262007-08-25 02:26:07 +000012812PyDoc_STRVAR(p_format__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012813 "S.__format__(format_spec) -> str\n\
Eric Smith8c663262007-08-25 02:26:07 +000012814\n\
Eric Smith51d2fd92010-11-06 19:27:37 +000012815Return a formatted version of S as described by format_spec.");
Eric Smith8c663262007-08-25 02:26:07 +000012816
12817static PyObject *
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012818unicode__sizeof__(PyObject *v)
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012819{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012820 Py_ssize_t size;
12821
12822 /* If it's a compact object, account for base structure +
12823 character data. */
12824 if (PyUnicode_IS_COMPACT_ASCII(v))
12825 size = sizeof(PyASCIIObject) + PyUnicode_GET_LENGTH(v) + 1;
12826 else if (PyUnicode_IS_COMPACT(v))
12827 size = sizeof(PyCompactUnicodeObject) +
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012828 (PyUnicode_GET_LENGTH(v) + 1) * PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012829 else {
12830 /* If it is a two-block object, account for base object, and
12831 for character block if present. */
12832 size = sizeof(PyUnicodeObject);
Victor Stinnerc3c74152011-10-02 20:39:55 +020012833 if (_PyUnicode_DATA_ANY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012834 size += (PyUnicode_GET_LENGTH(v) + 1) *
Martin v. Löwisc47adb02011-10-07 20:55:35 +020012835 PyUnicode_KIND(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012836 }
12837 /* If the wstr pointer is present, account for it unless it is shared
Victor Stinnera3be6132011-10-03 02:16:37 +020012838 with the data pointer. Check if the data is not shared. */
Victor Stinner03490912011-10-03 23:45:12 +020012839 if (_PyUnicode_HAS_WSTR_MEMORY(v))
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012840 size += (PyUnicode_WSTR_LENGTH(v) + 1) * sizeof(wchar_t);
Victor Stinner829c0ad2011-10-03 01:08:02 +020012841 if (_PyUnicode_HAS_UTF8_MEMORY(v))
Victor Stinnere90fe6a2011-10-01 16:48:13 +020012842 size += PyUnicode_UTF8_LENGTH(v) + 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012843
12844 return PyLong_FromSsize_t(size);
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012845}
12846
12847PyDoc_STRVAR(sizeof__doc__,
Benjamin Peterson29060642009-01-31 22:14:21 +000012848 "S.__sizeof__() -> size of S in memory, in bytes");
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012849
12850static PyObject *
Victor Stinner034f6cf2011-09-30 02:26:44 +020012851unicode_getnewargs(PyObject *v)
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012852{
Victor Stinner034f6cf2011-09-30 02:26:44 +020012853 PyObject *copy = PyUnicode_Copy(v);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012854 if (!copy)
12855 return NULL;
12856 return Py_BuildValue("(N)", copy);
Guido van Rossum5d9113d2003-01-29 17:58:45 +000012857}
12858
Guido van Rossumd57fd912000-03-10 22:53:23 +000012859static PyMethodDef unicode_methods[] = {
12860
12861 /* Order is according to common usage: often used methods should
12862 appear first, since lookup is done sequentially. */
12863
Benjamin Peterson28a4dce2010-12-12 01:33:04 +000012864 {"encode", (PyCFunction) unicode_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012865 {"replace", (PyCFunction) unicode_replace, METH_VARARGS, replace__doc__},
12866 {"split", (PyCFunction) unicode_split, METH_VARARGS, split__doc__},
Hye-Shik Chang3ae811b2003-12-15 18:49:53 +000012867 {"rsplit", (PyCFunction) unicode_rsplit, METH_VARARGS, rsplit__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012868 {"join", (PyCFunction) unicode_join, METH_O, join__doc__},
12869 {"capitalize", (PyCFunction) unicode_capitalize, METH_NOARGS, capitalize__doc__},
12870 {"title", (PyCFunction) unicode_title, METH_NOARGS, title__doc__},
12871 {"center", (PyCFunction) unicode_center, METH_VARARGS, center__doc__},
12872 {"count", (PyCFunction) unicode_count, METH_VARARGS, count__doc__},
12873 {"expandtabs", (PyCFunction) unicode_expandtabs, METH_VARARGS, expandtabs__doc__},
12874 {"find", (PyCFunction) unicode_find, METH_VARARGS, find__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012875 {"partition", (PyCFunction) unicode_partition, METH_O, partition__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012876 {"index", (PyCFunction) unicode_index, METH_VARARGS, index__doc__},
12877 {"ljust", (PyCFunction) unicode_ljust, METH_VARARGS, ljust__doc__},
12878 {"lower", (PyCFunction) unicode_lower, METH_NOARGS, lower__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012879 {"lstrip", (PyCFunction) unicode_lstrip, METH_VARARGS, lstrip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012880 {"rfind", (PyCFunction) unicode_rfind, METH_VARARGS, rfind__doc__},
12881 {"rindex", (PyCFunction) unicode_rindex, METH_VARARGS, rindex__doc__},
12882 {"rjust", (PyCFunction) unicode_rjust, METH_VARARGS, rjust__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012883 {"rstrip", (PyCFunction) unicode_rstrip, METH_VARARGS, rstrip__doc__},
Thomas Wouters477c8d52006-05-27 19:21:47 +000012884 {"rpartition", (PyCFunction) unicode_rpartition, METH_O, rpartition__doc__},
Mark Dickinson0d5f6ad2011-09-24 09:14:39 +010012885 {"splitlines", (PyCFunction) unicode_splitlines, METH_VARARGS | METH_KEYWORDS, splitlines__doc__},
Walter Dörwaldde02bcb2002-04-22 17:42:37 +000012886 {"strip", (PyCFunction) unicode_strip, METH_VARARGS, strip__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012887 {"swapcase", (PyCFunction) unicode_swapcase, METH_NOARGS, swapcase__doc__},
12888 {"translate", (PyCFunction) unicode_translate, METH_O, translate__doc__},
12889 {"upper", (PyCFunction) unicode_upper, METH_NOARGS, upper__doc__},
12890 {"startswith", (PyCFunction) unicode_startswith, METH_VARARGS, startswith__doc__},
12891 {"endswith", (PyCFunction) unicode_endswith, METH_VARARGS, endswith__doc__},
12892 {"islower", (PyCFunction) unicode_islower, METH_NOARGS, islower__doc__},
12893 {"isupper", (PyCFunction) unicode_isupper, METH_NOARGS, isupper__doc__},
12894 {"istitle", (PyCFunction) unicode_istitle, METH_NOARGS, istitle__doc__},
12895 {"isspace", (PyCFunction) unicode_isspace, METH_NOARGS, isspace__doc__},
12896 {"isdecimal", (PyCFunction) unicode_isdecimal, METH_NOARGS, isdecimal__doc__},
12897 {"isdigit", (PyCFunction) unicode_isdigit, METH_NOARGS, isdigit__doc__},
12898 {"isnumeric", (PyCFunction) unicode_isnumeric, METH_NOARGS, isnumeric__doc__},
12899 {"isalpha", (PyCFunction) unicode_isalpha, METH_NOARGS, isalpha__doc__},
12900 {"isalnum", (PyCFunction) unicode_isalnum, METH_NOARGS, isalnum__doc__},
Martin v. Löwis47383402007-08-15 07:32:56 +000012901 {"isidentifier", (PyCFunction) unicode_isidentifier, METH_NOARGS, isidentifier__doc__},
Georg Brandl559e5d72008-06-11 18:37:52 +000012902 {"isprintable", (PyCFunction) unicode_isprintable, METH_NOARGS, isprintable__doc__},
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012903 {"zfill", (PyCFunction) unicode_zfill, METH_VARARGS, zfill__doc__},
Eric Smith9cd1e092007-08-31 18:39:38 +000012904 {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
Eric Smith27bbca62010-11-04 17:06:58 +000012905 {"format_map", (PyCFunction) do_string_format_map, METH_O, format_map__doc__},
Eric Smith4a7d76d2008-05-30 18:10:19 +000012906 {"__format__", (PyCFunction) unicode__format__, METH_VARARGS, p_format__doc__},
Georg Brandlceee0772007-11-27 23:48:05 +000012907 {"maketrans", (PyCFunction) unicode_maketrans,
12908 METH_VARARGS | METH_STATIC, maketrans__doc__},
Georg Brandlc28e1fa2008-06-10 19:20:26 +000012909 {"__sizeof__", (PyCFunction) unicode__sizeof__, METH_NOARGS, sizeof__doc__},
Walter Dörwald068325e2002-04-15 13:36:47 +000012910#if 0
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000012911 {"capwords", (PyCFunction) unicode_capwords, METH_NOARGS, capwords__doc__},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012912#endif
12913
12914#if 0
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012915 /* These methods are just used for debugging the implementation. */
Alexander Belopolsky942af5a2010-12-04 03:38:46 +000012916 {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012917#endif
12918
Benjamin Peterson14339b62009-01-31 16:36:08 +000012919 {"__getnewargs__", (PyCFunction)unicode_getnewargs, METH_NOARGS},
Guido van Rossumd57fd912000-03-10 22:53:23 +000012920 {NULL, NULL}
12921};
12922
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012923static PyObject *
12924unicode_mod(PyObject *v, PyObject *w)
12925{
Brian Curtindfc80e32011-08-10 20:28:54 -050012926 if (!PyUnicode_Check(v))
12927 Py_RETURN_NOTIMPLEMENTED;
Benjamin Peterson29060642009-01-31 22:14:21 +000012928 return PyUnicode_Format(v, w);
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012929}
12930
12931static PyNumberMethods unicode_as_number = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012932 0, /*nb_add*/
12933 0, /*nb_subtract*/
12934 0, /*nb_multiply*/
12935 unicode_mod, /*nb_remainder*/
Neil Schemenauerce30bc92002-11-18 16:10:18 +000012936};
12937
Guido van Rossumd57fd912000-03-10 22:53:23 +000012938static PySequenceMethods unicode_as_sequence = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000012939 (lenfunc) unicode_length, /* sq_length */
12940 PyUnicode_Concat, /* sq_concat */
12941 (ssizeargfunc) unicode_repeat, /* sq_repeat */
12942 (ssizeargfunc) unicode_getitem, /* sq_item */
12943 0, /* sq_slice */
12944 0, /* sq_ass_item */
12945 0, /* sq_ass_slice */
12946 PyUnicode_Contains, /* sq_contains */
Guido van Rossumd57fd912000-03-10 22:53:23 +000012947};
12948
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012949static PyObject*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012950unicode_subscript(PyObject* self, PyObject* item)
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012951{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012952 if (PyUnicode_READY(self) == -1)
12953 return NULL;
12954
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000012955 if (PyIndex_Check(item)) {
12956 Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012957 if (i == -1 && PyErr_Occurred())
12958 return NULL;
12959 if (i < 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012960 i += PyUnicode_GET_LENGTH(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012961 return unicode_getitem(self, i);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012962 } else if (PySlice_Check(item)) {
Martin v. Löwis18e16552006-02-15 17:27:45 +000012963 Py_ssize_t start, stop, step, slicelength, cur, i;
Antoine Pitrou7aec4012011-10-04 19:08:01 +020012964 PyObject *result;
12965 void *src_data, *dest_data;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012966 int src_kind, dest_kind;
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012967 Py_UCS4 ch, max_char, kind_limit;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012968
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012969 if (PySlice_GetIndicesEx(item, PyUnicode_GET_LENGTH(self),
Benjamin Peterson29060642009-01-31 22:14:21 +000012970 &start, &stop, &step, &slicelength) < 0) {
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012971 return NULL;
12972 }
12973
12974 if (slicelength <= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020012975 return PyUnicode_New(0, 0);
12976 } else if (start == 0 && step == 1 &&
12977 slicelength == PyUnicode_GET_LENGTH(self) &&
Thomas Woutersed03b412007-08-28 21:37:11 +000012978 PyUnicode_CheckExact(self)) {
12979 Py_INCREF(self);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012980 return self;
Thomas Woutersed03b412007-08-28 21:37:11 +000012981 } else if (step == 1) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020012982 return PyUnicode_Substring(self,
Victor Stinner12bab6d2011-10-01 01:53:49 +020012983 start, start + slicelength);
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000012984 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012985 /* General case */
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012986 src_kind = PyUnicode_KIND(self);
12987 src_data = PyUnicode_DATA(self);
Victor Stinner55c99112011-10-13 01:17:06 +020012988 if (!PyUnicode_IS_ASCII(self)) {
12989 kind_limit = kind_maxchar_limit(src_kind);
12990 max_char = 0;
12991 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
12992 ch = PyUnicode_READ(src_kind, src_data, cur);
12993 if (ch > max_char) {
12994 max_char = ch;
12995 if (max_char >= kind_limit)
12996 break;
12997 }
Victor Stinnerc80d6d22011-10-05 14:13:28 +020012998 }
Antoine Pitrou875f29b2011-10-04 20:00:49 +020012999 }
Victor Stinner55c99112011-10-13 01:17:06 +020013000 else
13001 max_char = 127;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013002 result = PyUnicode_New(slicelength, max_char);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013003 if (result == NULL)
13004 return NULL;
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013005 dest_kind = PyUnicode_KIND(result);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013006 dest_data = PyUnicode_DATA(result);
13007
13008 for (cur = start, i = 0; i < slicelength; cur += step, i++) {
Antoine Pitrou875f29b2011-10-04 20:00:49 +020013009 Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, cur);
13010 PyUnicode_WRITE(dest_kind, dest_data, i, ch);
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013011 }
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013012 assert(_PyUnicode_CheckConsistency(result, 1));
Antoine Pitrou7aec4012011-10-04 19:08:01 +020013013 return result;
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013014 } else {
13015 PyErr_SetString(PyExc_TypeError, "string indices must be integers");
13016 return NULL;
13017 }
13018}
13019
13020static PyMappingMethods unicode_as_mapping = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013021 (lenfunc)unicode_length, /* mp_length */
13022 (binaryfunc)unicode_subscript, /* mp_subscript */
13023 (objobjargproc)0, /* mp_ass_subscript */
Michael W. Hudson5efaf7e2002-06-11 10:55:12 +000013024};
13025
Guido van Rossumd57fd912000-03-10 22:53:23 +000013026
Guido van Rossumd57fd912000-03-10 22:53:23 +000013027/* Helpers for PyUnicode_Format() */
13028
13029static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +000013030getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013031{
Martin v. Löwis18e16552006-02-15 17:27:45 +000013032 Py_ssize_t argidx = *p_argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013033 if (argidx < arglen) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013034 (*p_argidx)++;
13035 if (arglen < 0)
13036 return args;
13037 else
13038 return PyTuple_GetItem(args, argidx);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013039 }
13040 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013041 "not enough arguments for format string");
Guido van Rossumd57fd912000-03-10 22:53:23 +000013042 return NULL;
13043}
13044
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013045/* Returns a new reference to a PyUnicode object, or NULL on failure. */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013046
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013047static PyObject *
13048formatfloat(PyObject *v, int flags, int prec, int type)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013049{
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013050 char *p;
13051 PyObject *result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013052 double x;
Tim Petersced69f82003-09-16 20:30:58 +000013053
Guido van Rossumd57fd912000-03-10 22:53:23 +000013054 x = PyFloat_AsDouble(v);
13055 if (x == -1.0 && PyErr_Occurred())
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013056 return NULL;
13057
Guido van Rossumd57fd912000-03-10 22:53:23 +000013058 if (prec < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013059 prec = 6;
Eric Smith0923d1d2009-04-16 20:16:10 +000013060
Eric Smith0923d1d2009-04-16 20:16:10 +000013061 p = PyOS_double_to_string(x, type, prec,
13062 (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013063 if (p == NULL)
13064 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013065 result = PyUnicode_DecodeASCII(p, strlen(p), NULL);
Eric Smith0923d1d2009-04-16 20:16:10 +000013066 PyMem_Free(p);
13067 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013068}
13069
Tim Peters38fd5b62000-09-21 05:43:11 +000013070static PyObject*
13071formatlong(PyObject *val, int flags, int prec, int type)
13072{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013073 char *buf;
13074 int len;
13075 PyObject *str; /* temporary string object. */
13076 PyObject *result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013077
Benjamin Peterson14339b62009-01-31 16:36:08 +000013078 str = _PyBytes_FormatLong(val, flags, prec, type, &buf, &len);
13079 if (!str)
13080 return NULL;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013081 result = PyUnicode_DecodeASCII(buf, len, NULL);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013082 Py_DECREF(str);
13083 return result;
Tim Peters38fd5b62000-09-21 05:43:11 +000013084}
13085
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013086static Py_UCS4
13087formatchar(PyObject *v)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013088{
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013089 /* presume that the buffer is at least 3 characters long */
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013090 if (PyUnicode_Check(v)) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013091 if (PyUnicode_GET_LENGTH(v) == 1) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013092 return PyUnicode_READ_CHAR(v, 0);
Benjamin Peterson29060642009-01-31 22:14:21 +000013093 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013094 goto onError;
13095 }
13096 else {
13097 /* Integer input truncated to a character */
13098 long x;
13099 x = PyLong_AsLong(v);
13100 if (x == -1 && PyErr_Occurred())
13101 goto onError;
13102
13103 if (x < 0 || x > 0x10ffff) {
13104 PyErr_SetString(PyExc_OverflowError,
13105 "%c arg not in range(0x110000)");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013106 return (Py_UCS4) -1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013107 }
13108
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013109 return (Py_UCS4) x;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013110 }
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +000013111
Benjamin Peterson29060642009-01-31 22:14:21 +000013112 onError:
Marc-André Lemburgd4ab4a52000-06-08 17:54:00 +000013113 PyErr_SetString(PyExc_TypeError,
Benjamin Peterson29060642009-01-31 22:14:21 +000013114 "%c requires int or char");
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013115 return (Py_UCS4) -1;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013116}
13117
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013118static int
13119repeat_accumulate(_PyAccu *acc, PyObject *obj, Py_ssize_t count)
13120{
13121 int r;
13122 assert(count > 0);
13123 assert(PyUnicode_Check(obj));
13124 if (count > 5) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013125 PyObject *repeated = unicode_repeat(obj, count);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013126 if (repeated == NULL)
13127 return -1;
13128 r = _PyAccu_Accumulate(acc, repeated);
13129 Py_DECREF(repeated);
13130 return r;
13131 }
13132 else {
13133 do {
13134 if (_PyAccu_Accumulate(acc, obj))
13135 return -1;
13136 } while (--count);
13137 return 0;
13138 }
13139}
13140
Alexander Belopolsky40018472011-02-26 01:02:56 +000013141PyObject *
13142PyUnicode_Format(PyObject *format, PyObject *args)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013143{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013144 void *fmt;
13145 int fmtkind;
13146 PyObject *result;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013147 int kind;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013148 int r;
13149 Py_ssize_t fmtcnt, fmtpos, arglen, argidx;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013150 int args_owned = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013151 PyObject *dict = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013152 PyObject *temp = NULL;
13153 PyObject *second = NULL;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013154 PyObject *uformat;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013155 _PyAccu acc;
13156 static PyObject *plus, *minus, *blank, *zero, *percent;
13157
13158 if (!plus && !(plus = get_latin1_char('+')))
13159 return NULL;
13160 if (!minus && !(minus = get_latin1_char('-')))
13161 return NULL;
13162 if (!blank && !(blank = get_latin1_char(' ')))
13163 return NULL;
13164 if (!zero && !(zero = get_latin1_char('0')))
13165 return NULL;
13166 if (!percent && !(percent = get_latin1_char('%')))
13167 return NULL;
Tim Petersced69f82003-09-16 20:30:58 +000013168
Guido van Rossumd57fd912000-03-10 22:53:23 +000013169 if (format == NULL || args == NULL) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013170 PyErr_BadInternalCall();
13171 return NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013172 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013173 uformat = PyUnicode_FromObject(format);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013174 if (uformat == NULL || PyUnicode_READY(uformat) == -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013175 return NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013176 if (_PyAccu_Init(&acc))
13177 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013178 fmt = PyUnicode_DATA(uformat);
13179 fmtkind = PyUnicode_KIND(uformat);
13180 fmtcnt = PyUnicode_GET_LENGTH(uformat);
13181 fmtpos = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013182
Guido van Rossumd57fd912000-03-10 22:53:23 +000013183 if (PyTuple_Check(args)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013184 arglen = PyTuple_Size(args);
13185 argidx = 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013186 }
13187 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013188 arglen = -1;
13189 argidx = -2;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013190 }
Christian Heimes90aa7642007-12-19 02:45:37 +000013191 if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
Christian Heimesf3863112007-11-22 07:46:41 +000013192 !PyUnicode_Check(args))
Benjamin Peterson29060642009-01-31 22:14:21 +000013193 dict = args;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013194
13195 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013196 if (PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013197 PyObject *nonfmt;
13198 Py_ssize_t nonfmtpos;
13199 nonfmtpos = fmtpos++;
13200 while (fmtcnt >= 0 &&
13201 PyUnicode_READ(fmtkind, fmt, fmtpos) != '%') {
13202 fmtpos++;
13203 fmtcnt--;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013204 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013205 nonfmt = PyUnicode_Substring(uformat, nonfmtpos, fmtpos);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013206 if (nonfmt == NULL)
13207 goto onError;
13208 r = _PyAccu_Accumulate(&acc, nonfmt);
13209 Py_DECREF(nonfmt);
13210 if (r)
13211 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013212 }
13213 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013214 /* Got a format specifier */
13215 int flags = 0;
13216 Py_ssize_t width = -1;
13217 int prec = -1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013218 Py_UCS4 c = '\0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013219 Py_UCS4 fill, sign;
Benjamin Peterson29060642009-01-31 22:14:21 +000013220 int isnumok;
13221 PyObject *v = NULL;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013222 void *pbuf = NULL;
13223 Py_ssize_t pindex, len;
13224 PyObject *signobj = NULL, *fillobj = NULL;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013225
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013226 fmtpos++;
13227 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(') {
13228 Py_ssize_t keystart;
Benjamin Peterson29060642009-01-31 22:14:21 +000013229 Py_ssize_t keylen;
13230 PyObject *key;
13231 int pcount = 1;
Christian Heimesa612dc02008-02-24 13:08:18 +000013232
Benjamin Peterson29060642009-01-31 22:14:21 +000013233 if (dict == NULL) {
13234 PyErr_SetString(PyExc_TypeError,
13235 "format requires a mapping");
13236 goto onError;
13237 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013238 ++fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013239 --fmtcnt;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013240 keystart = fmtpos;
Benjamin Peterson29060642009-01-31 22:14:21 +000013241 /* Skip over balanced parentheses */
13242 while (pcount > 0 && --fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013243 if (PyUnicode_READ(fmtkind, fmt, fmtpos) == ')')
Benjamin Peterson29060642009-01-31 22:14:21 +000013244 --pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013245 else if (PyUnicode_READ(fmtkind, fmt, fmtpos) == '(')
Benjamin Peterson29060642009-01-31 22:14:21 +000013246 ++pcount;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013247 fmtpos++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013248 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013249 keylen = fmtpos - keystart - 1;
Benjamin Peterson29060642009-01-31 22:14:21 +000013250 if (fmtcnt < 0 || pcount > 0) {
13251 PyErr_SetString(PyExc_ValueError,
13252 "incomplete format key");
13253 goto onError;
13254 }
Victor Stinner7931d9a2011-11-04 00:22:48 +010013255 key = PyUnicode_Substring(uformat,
Victor Stinner12bab6d2011-10-01 01:53:49 +020013256 keystart, keystart + keylen);
Benjamin Peterson29060642009-01-31 22:14:21 +000013257 if (key == NULL)
13258 goto onError;
13259 if (args_owned) {
13260 Py_DECREF(args);
13261 args_owned = 0;
13262 }
13263 args = PyObject_GetItem(dict, key);
13264 Py_DECREF(key);
13265 if (args == NULL) {
13266 goto onError;
13267 }
13268 args_owned = 1;
13269 arglen = -1;
13270 argidx = -2;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013271 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013272 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013273 switch (c = PyUnicode_READ(fmtkind, fmt, fmtpos++)) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013274 case '-': flags |= F_LJUST; continue;
13275 case '+': flags |= F_SIGN; continue;
13276 case ' ': flags |= F_BLANK; continue;
13277 case '#': flags |= F_ALT; continue;
13278 case '0': flags |= F_ZERO; continue;
13279 }
13280 break;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013281 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013282 if (c == '*') {
13283 v = getnextarg(args, arglen, &argidx);
13284 if (v == NULL)
13285 goto onError;
13286 if (!PyLong_Check(v)) {
13287 PyErr_SetString(PyExc_TypeError,
13288 "* wants int");
13289 goto onError;
13290 }
13291 width = PyLong_AsLong(v);
13292 if (width == -1 && PyErr_Occurred())
13293 goto onError;
13294 if (width < 0) {
13295 flags |= F_LJUST;
13296 width = -width;
13297 }
13298 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013299 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013300 }
13301 else if (c >= '0' && c <= '9') {
13302 width = c - '0';
13303 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013304 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013305 if (c < '0' || c > '9')
13306 break;
13307 if ((width*10) / 10 != width) {
13308 PyErr_SetString(PyExc_ValueError,
13309 "width too big");
Benjamin Peterson14339b62009-01-31 16:36:08 +000013310 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013311 }
13312 width = width*10 + (c - '0');
13313 }
13314 }
13315 if (c == '.') {
13316 prec = 0;
13317 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013318 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013319 if (c == '*') {
13320 v = getnextarg(args, arglen, &argidx);
13321 if (v == NULL)
13322 goto onError;
13323 if (!PyLong_Check(v)) {
13324 PyErr_SetString(PyExc_TypeError,
13325 "* wants int");
13326 goto onError;
13327 }
13328 prec = PyLong_AsLong(v);
13329 if (prec == -1 && PyErr_Occurred())
13330 goto onError;
13331 if (prec < 0)
13332 prec = 0;
13333 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013334 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013335 }
13336 else if (c >= '0' && c <= '9') {
13337 prec = c - '0';
13338 while (--fmtcnt >= 0) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013339 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013340 if (c < '0' || c > '9')
13341 break;
13342 if ((prec*10) / 10 != prec) {
13343 PyErr_SetString(PyExc_ValueError,
13344 "prec too big");
13345 goto onError;
13346 }
13347 prec = prec*10 + (c - '0');
13348 }
13349 }
13350 } /* prec */
13351 if (fmtcnt >= 0) {
13352 if (c == 'h' || c == 'l' || c == 'L') {
13353 if (--fmtcnt >= 0)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013354 c = PyUnicode_READ(fmtkind, fmt, fmtpos++);
Benjamin Peterson29060642009-01-31 22:14:21 +000013355 }
13356 }
13357 if (fmtcnt < 0) {
13358 PyErr_SetString(PyExc_ValueError,
13359 "incomplete format");
13360 goto onError;
13361 }
13362 if (c != '%') {
13363 v = getnextarg(args, arglen, &argidx);
13364 if (v == NULL)
13365 goto onError;
13366 }
13367 sign = 0;
13368 fill = ' ';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013369 fillobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013370 switch (c) {
13371
13372 case '%':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013373 _PyAccu_Accumulate(&acc, percent);
13374 continue;
Benjamin Peterson29060642009-01-31 22:14:21 +000013375
13376 case 's':
13377 case 'r':
13378 case 'a':
Victor Stinner808fc0a2010-03-22 12:50:40 +000013379 if (PyUnicode_CheckExact(v) && c == 's') {
Benjamin Peterson29060642009-01-31 22:14:21 +000013380 temp = v;
13381 Py_INCREF(temp);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013382 }
13383 else {
Benjamin Peterson29060642009-01-31 22:14:21 +000013384 if (c == 's')
13385 temp = PyObject_Str(v);
13386 else if (c == 'r')
13387 temp = PyObject_Repr(v);
13388 else
13389 temp = PyObject_ASCII(v);
13390 if (temp == NULL)
13391 goto onError;
13392 if (PyUnicode_Check(temp))
13393 /* nothing to do */;
13394 else {
13395 Py_DECREF(temp);
13396 PyErr_SetString(PyExc_TypeError,
13397 "%s argument has non-string str()");
13398 goto onError;
13399 }
13400 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013401 if (PyUnicode_READY(temp) == -1) {
13402 Py_CLEAR(temp);
13403 goto onError;
13404 }
13405 pbuf = PyUnicode_DATA(temp);
13406 kind = PyUnicode_KIND(temp);
13407 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013408 if (prec >= 0 && len > prec)
13409 len = prec;
13410 break;
13411
13412 case 'i':
13413 case 'd':
13414 case 'u':
13415 case 'o':
13416 case 'x':
13417 case 'X':
Benjamin Peterson29060642009-01-31 22:14:21 +000013418 isnumok = 0;
13419 if (PyNumber_Check(v)) {
13420 PyObject *iobj=NULL;
13421
13422 if (PyLong_Check(v)) {
13423 iobj = v;
13424 Py_INCREF(iobj);
13425 }
13426 else {
13427 iobj = PyNumber_Long(v);
13428 }
13429 if (iobj!=NULL) {
13430 if (PyLong_Check(iobj)) {
13431 isnumok = 1;
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -070013432 temp = formatlong(iobj, flags, prec, (c == 'i'? 'd': c));
Benjamin Peterson29060642009-01-31 22:14:21 +000013433 Py_DECREF(iobj);
13434 if (!temp)
13435 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013436 if (PyUnicode_READY(temp) == -1) {
13437 Py_CLEAR(temp);
13438 goto onError;
13439 }
13440 pbuf = PyUnicode_DATA(temp);
13441 kind = PyUnicode_KIND(temp);
13442 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013443 sign = 1;
13444 }
13445 else {
13446 Py_DECREF(iobj);
13447 }
13448 }
13449 }
13450 if (!isnumok) {
13451 PyErr_Format(PyExc_TypeError,
13452 "%%%c format: a number is required, "
13453 "not %.200s", (char)c, Py_TYPE(v)->tp_name);
13454 goto onError;
13455 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013456 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013457 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013458 fillobj = zero;
13459 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013460 break;
13461
13462 case 'e':
13463 case 'E':
13464 case 'f':
13465 case 'F':
13466 case 'g':
13467 case 'G':
Mark Dickinsonf489caf2009-05-01 11:42:00 +000013468 temp = formatfloat(v, flags, prec, c);
13469 if (!temp)
Benjamin Peterson29060642009-01-31 22:14:21 +000013470 goto onError;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013471 if (PyUnicode_READY(temp) == -1) {
13472 Py_CLEAR(temp);
13473 goto onError;
13474 }
13475 pbuf = PyUnicode_DATA(temp);
13476 kind = PyUnicode_KIND(temp);
13477 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013478 sign = 1;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013479 if (flags & F_ZERO) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013480 fill = '0';
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013481 fillobj = zero;
13482 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013483 break;
13484
13485 case 'c':
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013486 {
13487 Py_UCS4 ch = formatchar(v);
13488 if (ch == (Py_UCS4) -1)
Benjamin Peterson29060642009-01-31 22:14:21 +000013489 goto onError;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013490 temp = _PyUnicode_FromUCS4(&ch, 1);
13491 if (temp == NULL)
13492 goto onError;
13493 pbuf = PyUnicode_DATA(temp);
13494 kind = PyUnicode_KIND(temp);
13495 len = PyUnicode_GET_LENGTH(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013496 break;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013497 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013498
13499 default:
13500 PyErr_Format(PyExc_ValueError,
13501 "unsupported format character '%c' (0x%x) "
13502 "at index %zd",
13503 (31<=c && c<=126) ? (char)c : '?',
13504 (int)c,
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013505 fmtpos - 1);
Benjamin Peterson29060642009-01-31 22:14:21 +000013506 goto onError;
13507 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013508 /* pbuf is initialized here. */
13509 pindex = 0;
Benjamin Peterson29060642009-01-31 22:14:21 +000013510 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013511 if (PyUnicode_READ(kind, pbuf, pindex) == '-') {
13512 signobj = minus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013513 len--;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013514 pindex++;
13515 }
13516 else if (PyUnicode_READ(kind, pbuf, pindex) == '+') {
13517 signobj = plus;
13518 len--;
13519 pindex++;
Benjamin Peterson29060642009-01-31 22:14:21 +000013520 }
13521 else if (flags & F_SIGN)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013522 signobj = plus;
Benjamin Peterson29060642009-01-31 22:14:21 +000013523 else if (flags & F_BLANK)
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013524 signobj = blank;
Benjamin Peterson29060642009-01-31 22:14:21 +000013525 else
13526 sign = 0;
13527 }
13528 if (width < len)
13529 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013530 if (sign) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013531 if (fill != ' ') {
13532 assert(signobj != NULL);
13533 if (_PyAccu_Accumulate(&acc, signobj))
13534 goto onError;
13535 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013536 if (width > len)
13537 width--;
13538 }
13539 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013540 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013541 assert(PyUnicode_READ(kind, pbuf, pindex + 1) == c);
Benjamin Peterson29060642009-01-31 22:14:21 +000013542 if (fill != ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013543 second = get_latin1_char(
13544 PyUnicode_READ(kind, pbuf, pindex + 1));
13545 pindex += 2;
13546 if (second == NULL ||
13547 _PyAccu_Accumulate(&acc, zero) ||
13548 _PyAccu_Accumulate(&acc, second))
13549 goto onError;
13550 Py_CLEAR(second);
Benjamin Peterson29060642009-01-31 22:14:21 +000013551 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013552 width -= 2;
13553 if (width < 0)
13554 width = 0;
13555 len -= 2;
13556 }
13557 if (width > len && !(flags & F_LJUST)) {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013558 assert(fillobj != NULL);
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013559 if (repeat_accumulate(&acc, fillobj, width - len))
13560 goto onError;
13561 width = len;
Benjamin Peterson29060642009-01-31 22:14:21 +000013562 }
13563 if (fill == ' ') {
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013564 if (sign) {
13565 assert(signobj != NULL);
13566 if (_PyAccu_Accumulate(&acc, signobj))
13567 goto onError;
13568 }
Benjamin Peterson29060642009-01-31 22:14:21 +000013569 if ((flags & F_ALT) && (c == 'x' || c == 'X' || c == 'o')) {
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013570 assert(PyUnicode_READ(kind, pbuf, pindex) == '0');
13571 assert(PyUnicode_READ(kind, pbuf, pindex+1) == c);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013572 second = get_latin1_char(
13573 PyUnicode_READ(kind, pbuf, pindex + 1));
13574 pindex += 2;
13575 if (second == NULL ||
13576 _PyAccu_Accumulate(&acc, zero) ||
13577 _PyAccu_Accumulate(&acc, second))
13578 goto onError;
13579 Py_CLEAR(second);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013580 }
13581 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013582 /* Copy all characters, preserving len */
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013583 if (temp != NULL) {
13584 assert(pbuf == PyUnicode_DATA(temp));
13585 v = PyUnicode_Substring(temp, pindex, pindex + len);
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013586 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013587 else {
13588 const char *p = (const char *) pbuf;
13589 assert(pbuf != NULL);
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013590 p += kind * pindex;
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013591 v = PyUnicode_FromKindAndData(kind, p, len);
13592 }
13593 if (v == NULL)
13594 goto onError;
13595 r = _PyAccu_Accumulate(&acc, v);
13596 Py_DECREF(v);
13597 if (r)
13598 goto onError;
Antoine Pitrou978b9d22011-10-07 12:35:48 +020013599 if (width > len && repeat_accumulate(&acc, blank, width - len))
13600 goto onError;
Benjamin Peterson29060642009-01-31 22:14:21 +000013601 if (dict && (argidx < arglen) && c != '%') {
13602 PyErr_SetString(PyExc_TypeError,
13603 "not all arguments converted during string formatting");
Benjamin Peterson29060642009-01-31 22:14:21 +000013604 goto onError;
13605 }
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013606 Py_CLEAR(temp);
Benjamin Peterson29060642009-01-31 22:14:21 +000013607 } /* '%' */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013608 } /* until end */
13609 if (argidx < arglen && !dict) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013610 PyErr_SetString(PyExc_TypeError,
13611 "not all arguments converted during string formatting");
13612 goto onError;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013613 }
13614
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013615 result = _PyAccu_Finish(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013616 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013617 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013618 }
13619 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013620 Py_XDECREF(temp);
13621 Py_XDECREF(second);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013622 return result;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013623
Benjamin Peterson29060642009-01-31 22:14:21 +000013624 onError:
Guido van Rossumd57fd912000-03-10 22:53:23 +000013625 Py_DECREF(uformat);
Antoine Pitrou5c0ba362011-10-07 01:54:09 +020013626 Py_XDECREF(temp);
13627 Py_XDECREF(second);
13628 _PyAccu_Destroy(&acc);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013629 if (args_owned) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013630 Py_DECREF(args);
Guido van Rossumd57fd912000-03-10 22:53:23 +000013631 }
13632 return NULL;
13633}
13634
Jeremy Hylton938ace62002-07-17 16:30:39 +000013635static PyObject *
Guido van Rossume023fe02001-08-30 03:12:59 +000013636unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
13637
Tim Peters6d6c1a32001-08-02 04:15:00 +000013638static PyObject *
13639unicode_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13640{
Benjamin Peterson29060642009-01-31 22:14:21 +000013641 PyObject *x = NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013642 static char *kwlist[] = {"object", "encoding", "errors", 0};
13643 char *encoding = NULL;
13644 char *errors = NULL;
Tim Peters6d6c1a32001-08-02 04:15:00 +000013645
Benjamin Peterson14339b62009-01-31 16:36:08 +000013646 if (type != &PyUnicode_Type)
13647 return unicode_subtype_new(type, args, kwds);
13648 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oss:str",
Benjamin Peterson29060642009-01-31 22:14:21 +000013649 kwlist, &x, &encoding, &errors))
Benjamin Peterson14339b62009-01-31 16:36:08 +000013650 return NULL;
13651 if (x == NULL)
Victor Stinner7931d9a2011-11-04 00:22:48 +010013652 return PyUnicode_New(0, 0);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013653 if (encoding == NULL && errors == NULL)
13654 return PyObject_Str(x);
13655 else
Benjamin Peterson29060642009-01-31 22:14:21 +000013656 return PyUnicode_FromEncodedObject(x, encoding, errors);
Tim Peters6d6c1a32001-08-02 04:15:00 +000013657}
13658
Guido van Rossume023fe02001-08-30 03:12:59 +000013659static PyObject *
13660unicode_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
13661{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013662 PyObject *unicode, *self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013663 Py_ssize_t length, char_size;
13664 int share_wstr, share_utf8;
13665 unsigned int kind;
13666 void *data;
Guido van Rossume023fe02001-08-30 03:12:59 +000013667
Benjamin Peterson14339b62009-01-31 16:36:08 +000013668 assert(PyType_IsSubtype(type, &PyUnicode_Type));
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013669
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013670 unicode = unicode_new(&PyUnicode_Type, args, kwds);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013671 if (unicode == NULL)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013672 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020013673 assert(_PyUnicode_CHECK(unicode));
Victor Stinnere06e1452011-10-04 20:52:31 +020013674 if (PyUnicode_READY(unicode))
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013675 return NULL;
13676
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013677 self = type->tp_alloc(type, 0);
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013678 if (self == NULL) {
13679 Py_DECREF(unicode);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013680 return NULL;
13681 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013682 kind = PyUnicode_KIND(unicode);
13683 length = PyUnicode_GET_LENGTH(unicode);
13684
13685 _PyUnicode_LENGTH(self) = length;
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013686#ifdef Py_DEBUG
13687 _PyUnicode_HASH(self) = -1;
13688#else
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013689 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013690#endif
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013691 _PyUnicode_STATE(self).interned = 0;
13692 _PyUnicode_STATE(self).kind = kind;
13693 _PyUnicode_STATE(self).compact = 0;
Victor Stinner3cf46372011-10-03 14:42:15 +020013694 _PyUnicode_STATE(self).ascii = _PyUnicode_STATE(unicode).ascii;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013695 _PyUnicode_STATE(self).ready = 1;
13696 _PyUnicode_WSTR(self) = NULL;
13697 _PyUnicode_UTF8_LENGTH(self) = 0;
13698 _PyUnicode_UTF8(self) = NULL;
13699 _PyUnicode_WSTR_LENGTH(self) = 0;
Victor Stinnerc3c74152011-10-02 20:39:55 +020013700 _PyUnicode_DATA_ANY(self) = NULL;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013701
13702 share_utf8 = 0;
13703 share_wstr = 0;
13704 if (kind == PyUnicode_1BYTE_KIND) {
13705 char_size = 1;
13706 if (PyUnicode_MAX_CHAR_VALUE(unicode) < 128)
13707 share_utf8 = 1;
13708 }
13709 else if (kind == PyUnicode_2BYTE_KIND) {
13710 char_size = 2;
13711 if (sizeof(wchar_t) == 2)
13712 share_wstr = 1;
13713 }
13714 else {
13715 assert(kind == PyUnicode_4BYTE_KIND);
13716 char_size = 4;
13717 if (sizeof(wchar_t) == 4)
13718 share_wstr = 1;
13719 }
13720
13721 /* Ensure we won't overflow the length. */
13722 if (length > (PY_SSIZE_T_MAX / char_size - 1)) {
13723 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013724 goto onError;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013725 }
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013726 data = PyObject_MALLOC((length + 1) * char_size);
13727 if (data == NULL) {
13728 PyErr_NoMemory();
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013729 goto onError;
13730 }
13731
Victor Stinnerc3c74152011-10-02 20:39:55 +020013732 _PyUnicode_DATA_ANY(self) = data;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013733 if (share_utf8) {
13734 _PyUnicode_UTF8_LENGTH(self) = length;
13735 _PyUnicode_UTF8(self) = data;
13736 }
13737 if (share_wstr) {
13738 _PyUnicode_WSTR_LENGTH(self) = length;
13739 _PyUnicode_WSTR(self) = (wchar_t *)data;
13740 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013741
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013742 Py_MEMCPY(data, PyUnicode_DATA(unicode),
Martin v. Löwisc47adb02011-10-07 20:55:35 +020013743 kind * (length + 1));
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013744 assert(_PyUnicode_CheckConsistency(self, 1));
Victor Stinnerfb9ea8c2011-10-06 01:45:57 +020013745#ifdef Py_DEBUG
13746 _PyUnicode_HASH(self) = _PyUnicode_HASH(unicode);
13747#endif
Victor Stinnerdd18d3a2011-10-22 11:08:10 +020013748 Py_DECREF(unicode);
Victor Stinner7931d9a2011-11-04 00:22:48 +010013749 return self;
Victor Stinner07ac3eb2011-10-01 16:16:43 +020013750
13751onError:
13752 Py_DECREF(unicode);
13753 Py_DECREF(self);
13754 return NULL;
Guido van Rossume023fe02001-08-30 03:12:59 +000013755}
13756
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000013757PyDoc_STRVAR(unicode_doc,
Benjamin Peterson29060642009-01-31 22:14:21 +000013758 "str(string[, encoding[, errors]]) -> str\n\
Tim Peters6d6c1a32001-08-02 04:15:00 +000013759\n\
Collin Winterd474ce82007-08-07 19:42:11 +000013760Create a new string object from the given encoded string.\n\
Skip Montanaro35b37a52002-07-26 16:22:46 +000013761encoding defaults to the current default string encoding.\n\
13762errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'.");
Tim Peters6d6c1a32001-08-02 04:15:00 +000013763
Guido van Rossum50e9fb92006-08-17 05:42:55 +000013764static PyObject *unicode_iter(PyObject *seq);
13765
Guido van Rossumd57fd912000-03-10 22:53:23 +000013766PyTypeObject PyUnicode_Type = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +000013767 PyVarObject_HEAD_INIT(&PyType_Type, 0)
Benjamin Peterson14339b62009-01-31 16:36:08 +000013768 "str", /* tp_name */
13769 sizeof(PyUnicodeObject), /* tp_size */
13770 0, /* tp_itemsize */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013771 /* Slots */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013772 (destructor)unicode_dealloc, /* tp_dealloc */
13773 0, /* tp_print */
13774 0, /* tp_getattr */
13775 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000013776 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013777 unicode_repr, /* tp_repr */
13778 &unicode_as_number, /* tp_as_number */
13779 &unicode_as_sequence, /* tp_as_sequence */
13780 &unicode_as_mapping, /* tp_as_mapping */
13781 (hashfunc) unicode_hash, /* tp_hash*/
13782 0, /* tp_call*/
13783 (reprfunc) unicode_str, /* tp_str */
13784 PyObject_GenericGetAttr, /* tp_getattro */
13785 0, /* tp_setattro */
13786 0, /* tp_as_buffer */
13787 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Benjamin Peterson29060642009-01-31 22:14:21 +000013788 Py_TPFLAGS_UNICODE_SUBCLASS, /* tp_flags */
Benjamin Peterson14339b62009-01-31 16:36:08 +000013789 unicode_doc, /* tp_doc */
13790 0, /* tp_traverse */
13791 0, /* tp_clear */
13792 PyUnicode_RichCompare, /* tp_richcompare */
13793 0, /* tp_weaklistoffset */
13794 unicode_iter, /* tp_iter */
13795 0, /* tp_iternext */
13796 unicode_methods, /* tp_methods */
13797 0, /* tp_members */
13798 0, /* tp_getset */
13799 &PyBaseObject_Type, /* tp_base */
13800 0, /* tp_dict */
13801 0, /* tp_descr_get */
13802 0, /* tp_descr_set */
13803 0, /* tp_dictoffset */
13804 0, /* tp_init */
13805 0, /* tp_alloc */
13806 unicode_new, /* tp_new */
13807 PyObject_Del, /* tp_free */
Guido van Rossumd57fd912000-03-10 22:53:23 +000013808};
13809
13810/* Initialize the Unicode implementation */
13811
Victor Stinner3a50e702011-10-18 21:21:00 +020013812int _PyUnicode_Init(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013813{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013814 int i;
13815
Thomas Wouters477c8d52006-05-27 19:21:47 +000013816 /* XXX - move this array to unicodectype.c ? */
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013817 Py_UCS2 linebreak[] = {
Thomas Wouters477c8d52006-05-27 19:21:47 +000013818 0x000A, /* LINE FEED */
13819 0x000D, /* CARRIAGE RETURN */
13820 0x001C, /* FILE SEPARATOR */
13821 0x001D, /* GROUP SEPARATOR */
13822 0x001E, /* RECORD SEPARATOR */
13823 0x0085, /* NEXT LINE */
13824 0x2028, /* LINE SEPARATOR */
13825 0x2029, /* PARAGRAPH SEPARATOR */
13826 };
13827
Fred Drakee4315f52000-05-09 19:53:39 +000013828 /* Init the implementation */
Victor Stinnera464fc12011-10-02 20:39:30 +020013829 unicode_empty = PyUnicode_New(0, 0);
Victor Stinnerbb10a1f2011-10-05 01:34:17 +020013830 assert(_PyUnicode_CheckConsistency(unicode_empty, 1));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013831 if (!unicode_empty)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013832 Py_FatalError("Can't create empty string");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013833
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013834 for (i = 0; i < 256; i++)
Benjamin Peterson29060642009-01-31 22:14:21 +000013835 unicode_latin1[i] = NULL;
Guido van Rossumcacfc072002-05-24 19:01:59 +000013836 if (PyType_Ready(&PyUnicode_Type) < 0)
Benjamin Peterson29060642009-01-31 22:14:21 +000013837 Py_FatalError("Can't initialize 'unicode'");
Thomas Wouters477c8d52006-05-27 19:21:47 +000013838
13839 /* initialize the linebreak bloom filter */
13840 bloom_linebreak = make_bloom_mask(
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013841 PyUnicode_2BYTE_KIND, linebreak,
Victor Stinner63941882011-09-29 00:42:28 +020013842 Py_ARRAY_LENGTH(linebreak));
Thomas Wouters0e3f5912006-08-11 14:57:12 +000013843
13844 PyType_Ready(&EncodingMapType);
Victor Stinner3a50e702011-10-18 21:21:00 +020013845
13846#ifdef HAVE_MBCS
13847 winver.dwOSVersionInfoSize = sizeof(winver);
13848 if (!GetVersionEx((OSVERSIONINFO*)&winver)) {
13849 PyErr_SetFromWindowsErr(0);
13850 return -1;
13851 }
13852#endif
13853 return 0;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013854}
13855
13856/* Finalize the Unicode implementation */
13857
Christian Heimesa156e092008-02-16 07:38:31 +000013858int
13859PyUnicode_ClearFreeList(void)
13860{
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013861 return 0;
Christian Heimesa156e092008-02-16 07:38:31 +000013862}
13863
Guido van Rossumd57fd912000-03-10 22:53:23 +000013864void
Thomas Wouters78890102000-07-22 19:25:51 +000013865_PyUnicode_Fini(void)
Guido van Rossumd57fd912000-03-10 22:53:23 +000013866{
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013867 int i;
Guido van Rossumd57fd912000-03-10 22:53:23 +000013868
Guido van Rossum4ae8ef82000-10-03 18:09:04 +000013869 Py_XDECREF(unicode_empty);
13870 unicode_empty = NULL;
Barry Warsaw5b4c2282000-10-03 20:45:26 +000013871
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013872 for (i = 0; i < 256; i++) {
Benjamin Peterson29060642009-01-31 22:14:21 +000013873 if (unicode_latin1[i]) {
13874 Py_DECREF(unicode_latin1[i]);
13875 unicode_latin1[i] = NULL;
13876 }
Marc-André Lemburg8155e0e2001-04-23 14:44:21 +000013877 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +020013878 _PyUnicode_ClearStaticStrings();
Christian Heimesa156e092008-02-16 07:38:31 +000013879 (void)PyUnicode_ClearFreeList();
Guido van Rossumd57fd912000-03-10 22:53:23 +000013880}
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +000013881
Walter Dörwald16807132007-05-25 13:52:07 +000013882void
13883PyUnicode_InternInPlace(PyObject **p)
13884{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013885 register PyObject *s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013886 PyObject *t;
Victor Stinner4fae54c2011-10-03 02:01:52 +020013887#ifdef Py_DEBUG
13888 assert(s != NULL);
13889 assert(_PyUnicode_CHECK(s));
13890#else
Benjamin Peterson14339b62009-01-31 16:36:08 +000013891 if (s == NULL || !PyUnicode_Check(s))
Victor Stinner4fae54c2011-10-03 02:01:52 +020013892 return;
13893#endif
Benjamin Peterson14339b62009-01-31 16:36:08 +000013894 /* If it's a subclass, we don't really know what putting
13895 it in the interned dict might do. */
13896 if (!PyUnicode_CheckExact(s))
13897 return;
13898 if (PyUnicode_CHECK_INTERNED(s))
13899 return;
Victor Stinner1b4f9ce2011-10-03 13:28:14 +020013900 if (_PyUnicode_READY_REPLACE(p)) {
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013901 assert(0 && "_PyUnicode_READY_REPLACE fail in PyUnicode_InternInPlace");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013902 return;
13903 }
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013904 s = *p;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013905 if (interned == NULL) {
13906 interned = PyDict_New();
13907 if (interned == NULL) {
13908 PyErr_Clear(); /* Don't leave an exception */
13909 return;
13910 }
13911 }
13912 /* It might be that the GetItem call fails even
13913 though the key is present in the dictionary,
13914 namely when this happens during a stack overflow. */
13915 Py_ALLOW_RECURSION
Victor Stinner7931d9a2011-11-04 00:22:48 +010013916 t = PyDict_GetItem(interned, s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013917 Py_END_ALLOW_RECURSION
Martin v. Löwis5b222132007-06-10 09:51:05 +000013918
Benjamin Peterson29060642009-01-31 22:14:21 +000013919 if (t) {
13920 Py_INCREF(t);
13921 Py_DECREF(*p);
13922 *p = t;
13923 return;
13924 }
Walter Dörwald16807132007-05-25 13:52:07 +000013925
Benjamin Peterson14339b62009-01-31 16:36:08 +000013926 PyThreadState_GET()->recursion_critical = 1;
Victor Stinner7931d9a2011-11-04 00:22:48 +010013927 if (PyDict_SetItem(interned, s, s) < 0) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013928 PyErr_Clear();
13929 PyThreadState_GET()->recursion_critical = 0;
13930 return;
13931 }
13932 PyThreadState_GET()->recursion_critical = 0;
13933 /* The two references in interned are not counted by refcnt.
13934 The deallocator will take care of this */
13935 Py_REFCNT(s) -= 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013936 _PyUnicode_STATE(s).interned = SSTATE_INTERNED_MORTAL;
Walter Dörwald16807132007-05-25 13:52:07 +000013937}
13938
13939void
13940PyUnicode_InternImmortal(PyObject **p)
13941{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013942 PyUnicode_InternInPlace(p);
13943 if (PyUnicode_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
Victor Stinneraf9e4b82011-10-23 20:07:00 +020013944 _PyUnicode_STATE(*p).interned = SSTATE_INTERNED_IMMORTAL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013945 Py_INCREF(*p);
13946 }
Walter Dörwald16807132007-05-25 13:52:07 +000013947}
13948
13949PyObject *
13950PyUnicode_InternFromString(const char *cp)
13951{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013952 PyObject *s = PyUnicode_FromString(cp);
13953 if (s == NULL)
13954 return NULL;
13955 PyUnicode_InternInPlace(&s);
13956 return s;
Walter Dörwald16807132007-05-25 13:52:07 +000013957}
13958
Alexander Belopolsky40018472011-02-26 01:02:56 +000013959void
13960_Py_ReleaseInternedUnicodeStrings(void)
Walter Dörwald16807132007-05-25 13:52:07 +000013961{
Benjamin Peterson14339b62009-01-31 16:36:08 +000013962 PyObject *keys;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013963 PyObject *s;
Benjamin Peterson14339b62009-01-31 16:36:08 +000013964 Py_ssize_t i, n;
13965 Py_ssize_t immortal_size = 0, mortal_size = 0;
Walter Dörwald16807132007-05-25 13:52:07 +000013966
Benjamin Peterson14339b62009-01-31 16:36:08 +000013967 if (interned == NULL || !PyDict_Check(interned))
13968 return;
13969 keys = PyDict_Keys(interned);
13970 if (keys == NULL || !PyList_Check(keys)) {
13971 PyErr_Clear();
13972 return;
13973 }
Walter Dörwald16807132007-05-25 13:52:07 +000013974
Benjamin Peterson14339b62009-01-31 16:36:08 +000013975 /* Since _Py_ReleaseInternedUnicodeStrings() is intended to help a leak
13976 detector, interned unicode strings are not forcibly deallocated;
13977 rather, we give them their stolen references back, and then clear
13978 and DECREF the interned dict. */
Walter Dörwald16807132007-05-25 13:52:07 +000013979
Benjamin Peterson14339b62009-01-31 16:36:08 +000013980 n = PyList_GET_SIZE(keys);
13981 fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
Benjamin Peterson29060642009-01-31 22:14:21 +000013982 n);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013983 for (i = 0; i < n; i++) {
Victor Stinner9db1a8b2011-10-23 20:04:37 +020013984 s = PyList_GET_ITEM(keys, i);
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013985 if (PyUnicode_READY(s) == -1) {
13986 assert(0 && "could not ready string");
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013987 fprintf(stderr, "could not ready string\n");
Victor Stinner6b56a7f2011-10-04 20:04:52 +020013988 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013989 switch (PyUnicode_CHECK_INTERNED(s)) {
Benjamin Peterson14339b62009-01-31 16:36:08 +000013990 case SSTATE_NOT_INTERNED:
13991 /* XXX Shouldn't happen */
13992 break;
13993 case SSTATE_INTERNED_IMMORTAL:
13994 Py_REFCNT(s) += 1;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013995 immortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000013996 break;
13997 case SSTATE_INTERNED_MORTAL:
13998 Py_REFCNT(s) += 2;
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020013999 mortal_size += PyUnicode_GET_LENGTH(s);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014000 break;
14001 default:
14002 Py_FatalError("Inconsistent interned string state.");
14003 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014004 _PyUnicode_STATE(s).interned = SSTATE_NOT_INTERNED;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014005 }
14006 fprintf(stderr, "total size of all interned strings: "
14007 "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
14008 "mortal/immortal\n", mortal_size, immortal_size);
14009 Py_DECREF(keys);
14010 PyDict_Clear(interned);
14011 Py_DECREF(interned);
14012 interned = NULL;
Walter Dörwald16807132007-05-25 13:52:07 +000014013}
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014014
14015
14016/********************* Unicode Iterator **************************/
14017
14018typedef struct {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014019 PyObject_HEAD
14020 Py_ssize_t it_index;
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014021 PyObject *it_seq; /* Set to NULL when iterator is exhausted */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014022} unicodeiterobject;
14023
14024static void
14025unicodeiter_dealloc(unicodeiterobject *it)
14026{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014027 _PyObject_GC_UNTRACK(it);
14028 Py_XDECREF(it->it_seq);
14029 PyObject_GC_Del(it);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014030}
14031
14032static int
14033unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg)
14034{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014035 Py_VISIT(it->it_seq);
14036 return 0;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014037}
14038
14039static PyObject *
14040unicodeiter_next(unicodeiterobject *it)
14041{
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014042 PyObject *seq, *item;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014043
Benjamin Peterson14339b62009-01-31 16:36:08 +000014044 assert(it != NULL);
14045 seq = it->it_seq;
14046 if (seq == NULL)
14047 return NULL;
Victor Stinner910337b2011-10-03 03:20:16 +020014048 assert(_PyUnicode_CHECK(seq));
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014049
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014050 if (it->it_index < PyUnicode_GET_LENGTH(seq)) {
14051 int kind = PyUnicode_KIND(seq);
14052 void *data = PyUnicode_DATA(seq);
14053 Py_UCS4 chr = PyUnicode_READ(kind, data, it->it_index);
14054 item = PyUnicode_FromOrdinal(chr);
Benjamin Peterson14339b62009-01-31 16:36:08 +000014055 if (item != NULL)
14056 ++it->it_index;
14057 return item;
14058 }
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014059
Benjamin Peterson14339b62009-01-31 16:36:08 +000014060 Py_DECREF(seq);
14061 it->it_seq = NULL;
14062 return NULL;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014063}
14064
14065static PyObject *
14066unicodeiter_len(unicodeiterobject *it)
14067{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014068 Py_ssize_t len = 0;
14069 if (it->it_seq)
Victor Stinnerc4f281e2011-10-11 22:11:42 +020014070 len = PyUnicode_GET_LENGTH(it->it_seq) - it->it_index;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014071 return PyLong_FromSsize_t(len);
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014072}
14073
14074PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
14075
14076static PyMethodDef unicodeiter_methods[] = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014077 {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS,
Benjamin Peterson29060642009-01-31 22:14:21 +000014078 length_hint_doc},
Benjamin Peterson14339b62009-01-31 16:36:08 +000014079 {NULL, NULL} /* sentinel */
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014080};
14081
14082PyTypeObject PyUnicodeIter_Type = {
Benjamin Peterson14339b62009-01-31 16:36:08 +000014083 PyVarObject_HEAD_INIT(&PyType_Type, 0)
14084 "str_iterator", /* tp_name */
14085 sizeof(unicodeiterobject), /* tp_basicsize */
14086 0, /* tp_itemsize */
14087 /* methods */
14088 (destructor)unicodeiter_dealloc, /* tp_dealloc */
14089 0, /* tp_print */
14090 0, /* tp_getattr */
14091 0, /* tp_setattr */
Mark Dickinsone94c6792009-02-02 20:36:42 +000014092 0, /* tp_reserved */
Benjamin Peterson14339b62009-01-31 16:36:08 +000014093 0, /* tp_repr */
14094 0, /* tp_as_number */
14095 0, /* tp_as_sequence */
14096 0, /* tp_as_mapping */
14097 0, /* tp_hash */
14098 0, /* tp_call */
14099 0, /* tp_str */
14100 PyObject_GenericGetAttr, /* tp_getattro */
14101 0, /* tp_setattro */
14102 0, /* tp_as_buffer */
14103 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
14104 0, /* tp_doc */
14105 (traverseproc)unicodeiter_traverse, /* tp_traverse */
14106 0, /* tp_clear */
14107 0, /* tp_richcompare */
14108 0, /* tp_weaklistoffset */
14109 PyObject_SelfIter, /* tp_iter */
14110 (iternextfunc)unicodeiter_next, /* tp_iternext */
14111 unicodeiter_methods, /* tp_methods */
14112 0,
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014113};
14114
14115static PyObject *
14116unicode_iter(PyObject *seq)
14117{
Benjamin Peterson14339b62009-01-31 16:36:08 +000014118 unicodeiterobject *it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014119
Benjamin Peterson14339b62009-01-31 16:36:08 +000014120 if (!PyUnicode_Check(seq)) {
14121 PyErr_BadInternalCall();
14122 return NULL;
14123 }
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014124 if (PyUnicode_READY(seq) == -1)
14125 return NULL;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014126 it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type);
14127 if (it == NULL)
14128 return NULL;
14129 it->it_index = 0;
14130 Py_INCREF(seq);
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014131 it->it_seq = seq;
Benjamin Peterson14339b62009-01-31 16:36:08 +000014132 _PyObject_GC_TRACK(it);
14133 return (PyObject *)it;
Guido van Rossum50e9fb92006-08-17 05:42:55 +000014134}
14135
Martin v. Löwis0d3072e2011-10-31 08:40:56 +010014136
14137size_t
14138Py_UNICODE_strlen(const Py_UNICODE *u)
14139{
14140 int res = 0;
14141 while(*u++)
14142 res++;
14143 return res;
14144}
14145
14146Py_UNICODE*
14147Py_UNICODE_strcpy(Py_UNICODE *s1, const Py_UNICODE *s2)
14148{
14149 Py_UNICODE *u = s1;
14150 while ((*u++ = *s2++));
14151 return s1;
14152}
14153
14154Py_UNICODE*
14155Py_UNICODE_strncpy(Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14156{
14157 Py_UNICODE *u = s1;
14158 while ((*u++ = *s2++))
14159 if (n-- == 0)
14160 break;
14161 return s1;
14162}
14163
14164Py_UNICODE*
14165Py_UNICODE_strcat(Py_UNICODE *s1, const Py_UNICODE *s2)
14166{
14167 Py_UNICODE *u1 = s1;
14168 u1 += Py_UNICODE_strlen(u1);
14169 Py_UNICODE_strcpy(u1, s2);
14170 return s1;
14171}
14172
14173int
14174Py_UNICODE_strcmp(const Py_UNICODE *s1, const Py_UNICODE *s2)
14175{
14176 while (*s1 && *s2 && *s1 == *s2)
14177 s1++, s2++;
14178 if (*s1 && *s2)
14179 return (*s1 < *s2) ? -1 : +1;
14180 if (*s1)
14181 return 1;
14182 if (*s2)
14183 return -1;
14184 return 0;
14185}
14186
14187int
14188Py_UNICODE_strncmp(const Py_UNICODE *s1, const Py_UNICODE *s2, size_t n)
14189{
14190 register Py_UNICODE u1, u2;
14191 for (; n != 0; n--) {
14192 u1 = *s1;
14193 u2 = *s2;
14194 if (u1 != u2)
14195 return (u1 < u2) ? -1 : +1;
14196 if (u1 == '\0')
14197 return 0;
14198 s1++;
14199 s2++;
14200 }
14201 return 0;
14202}
14203
14204Py_UNICODE*
14205Py_UNICODE_strchr(const Py_UNICODE *s, Py_UNICODE c)
14206{
14207 const Py_UNICODE *p;
14208 for (p = s; *p; p++)
14209 if (*p == c)
14210 return (Py_UNICODE*)p;
14211 return NULL;
14212}
14213
14214Py_UNICODE*
14215Py_UNICODE_strrchr(const Py_UNICODE *s, Py_UNICODE c)
14216{
14217 const Py_UNICODE *p;
14218 p = s + Py_UNICODE_strlen(s);
14219 while (p != s) {
14220 p--;
14221 if (*p == c)
14222 return (Py_UNICODE*)p;
14223 }
14224 return NULL;
14225}
Victor Stinner331ea922010-08-10 16:37:20 +000014226
Victor Stinner71133ff2010-09-01 23:43:53 +000014227Py_UNICODE*
Victor Stinner9db1a8b2011-10-23 20:04:37 +020014228PyUnicode_AsUnicodeCopy(PyObject *unicode)
Victor Stinner71133ff2010-09-01 23:43:53 +000014229{
Victor Stinner577db2c2011-10-11 22:12:48 +020014230 Py_UNICODE *u, *copy;
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014231 Py_ssize_t len, size;
Victor Stinner71133ff2010-09-01 23:43:53 +000014232
Martin v. Löwisd63a3b82011-09-28 07:41:54 +020014233 if (!PyUnicode_Check(unicode)) {
14234 PyErr_BadArgument();
14235 return NULL;
14236 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014237 u = PyUnicode_AsUnicodeAndSize(unicode, &len);
Victor Stinner577db2c2011-10-11 22:12:48 +020014238 if (u == NULL)
14239 return NULL;
Victor Stinner71133ff2010-09-01 23:43:53 +000014240 /* Ensure we won't overflow the size. */
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014241 if (len > ((PY_SSIZE_T_MAX / sizeof(Py_UNICODE)) - 1)) {
Victor Stinner71133ff2010-09-01 23:43:53 +000014242 PyErr_NoMemory();
14243 return NULL;
14244 }
Victor Stinner57ffa9d2011-10-23 20:10:08 +020014245 size = len + 1; /* copy the null character */
Victor Stinner71133ff2010-09-01 23:43:53 +000014246 size *= sizeof(Py_UNICODE);
14247 copy = PyMem_Malloc(size);
14248 if (copy == NULL) {
14249 PyErr_NoMemory();
14250 return NULL;
14251 }
Victor Stinner577db2c2011-10-11 22:12:48 +020014252 memcpy(copy, u, size);
Victor Stinner71133ff2010-09-01 23:43:53 +000014253 return copy;
14254}
Martin v. Löwis5b222132007-06-10 09:51:05 +000014255
Georg Brandl66c221e2010-10-14 07:04:07 +000014256/* A _string module, to export formatter_parser and formatter_field_name_split
14257 to the string.Formatter class implemented in Python. */
14258
14259static PyMethodDef _string_methods[] = {
14260 {"formatter_field_name_split", (PyCFunction) formatter_field_name_split,
14261 METH_O, PyDoc_STR("split the argument as a field name")},
14262 {"formatter_parser", (PyCFunction) formatter_parser,
14263 METH_O, PyDoc_STR("parse the argument as a format string")},
14264 {NULL, NULL}
14265};
14266
14267static struct PyModuleDef _string_module = {
14268 PyModuleDef_HEAD_INIT,
14269 "_string",
14270 PyDoc_STR("string helper module"),
14271 0,
14272 _string_methods,
14273 NULL,
14274 NULL,
14275 NULL,
14276 NULL
14277};
14278
14279PyMODINIT_FUNC
14280PyInit__string(void)
14281{
14282 return PyModule_Create(&_string_module);
14283}
14284
14285
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014286#ifdef __cplusplus
14287}
14288#endif